math module and complex numbers
import math math.sqrt(-1)
Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> math.sqrt(-1) ValueError: math domain error I'd say math.sqrt(-1) should return 1j. Sturla Molden
On Wed, Mar 11, 2009 at 8:26 AM, Sturla Molden <sturla@molden.no> wrote:
import math math.sqrt(-1)
Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> math.sqrt(-1) ValueError: math domain error
I'd say math.sqrt(-1) should return 1j.
import cmath cmath.sqrt(-1) 1j
Greg F
On Wed, Mar 11, 2009 at 02:12:10PM +0100, Sturla Molden wrote:
Greg Falcon wrote:
import cmath cmath.sqrt(-1)
1j
What is the point of having two math modules? It just adds confusion, like pickle and cPickle.
'c' in 'cmath' stands for 'complex'. There is a difference between float and complex math. See http://docs.python.org/library/math.html : "These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don't is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection" Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd@phd.pp.ru Programmers don't die, they just GOSUB without RETURN.
On Wed, Mar 11, 2009 at 1:31 PM, Oleg Broytmann <phd@phd.pp.ru> wrote:
numbers. The distinction between functions which support complex numbers and those which don't is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection"
Furthermore, even those users who *do* understand complex numbers don't always want sqrt(-1) to return 1j. I find the math/cmath duality useful. Mark
from cmath import sqrt sqrt(-complex(1)) -1j sqrt(complex(-1)) 1j
participants (4)
-
Greg Falcon -
Mark Dickinson -
Oleg Broytmann -
Sturla Molden