Square root of -1

33 views
Skip to first unread message

Katie Foote

unread,
Aug 30, 2017, 10:33:14 PM8/30/17
to Glowscript Users
Hi Glowscript users,

My students pointed out that glowscript computes the square root of -1 incorrectly.  

Did anyone else notice this?  Who can fix this?

Bruce Sherwood

unread,
Aug 31, 2017, 9:13:13 AM8/31/17
to Glowscript Users
In true Python, if you say "from math import sqrt), then sqrt(-1) gives an error message "ValueError: math domain error". You need to say "from cmath import sqrt" for sqrt(-1) to deliver the result 1j, the syntax used for a pure imaginary number in Python.

The RapydScript-NG transpiler used by GlowScript, which converts Python to JavaScript, does not handle complex numbers, nor does JavaScript. As your students found, the sqrt function that is part of the JavaScript Math library invoked by GlowScript returns -1 instead of giving an error, which is not great but is really only the tip of a large iceberg.

I can't change the JavaScript math library that is built into the browser, nor would it be sufficient to do so as long as JavaScript doesn't handle complex numbers such as 1j. A colleague has expressed interest in adding a complex class to GlowScript, similar to the implementation of the vector class, but that's a long-term project. It would also necessitate the creation of a separate math library, similar to the Python cmath library.

If you are teaching a course in which complex math is important, then you need to use VPython 7, not GlowScript VPython. This is simply part of the larger issue that if special Python modules (such as cmath) are needed, then GlowScript is not the tool to use.

Reply all
Reply to author
Forward
0 new messages