Here's my code:
import cmath
root = (cmath.sqrt(25))
print (root)
raw_input()
The problem i face is the result of root is 5+0j which is undesirable i only want the square root. How can i fix this?
Here's my code:
import cmath
root = (cmath.sqrt(25))
print (root)
raw_input()
The problem i face is the result of root is 5+0j which is undesirable i only want the square root. How can i fix this?
Use the math
module instead of the cmath
module; the latter is for complex numbers only:
>>> import math
>>> print math.sqrt(25)
5.0
For what it's worth, the cmath
result is correct, if you expected a complex number. You could take just the .real
component of the result, but since there is a regular floating point equivalent in the math
module there is no point in having your computer do the extra work.
The result itself is correct. The square root of 25 + 0j
is 5 + 0j
.
Where did the j
come from ? Its implicit because you are using the complex math (cmath
) library.
If you only want the real part of the complex number, then do :
>>> root = (cmath.sqrt(25))
>>> root.real
5.0
Lastly, if you want to deal with only real numbers, then use the math
library.
The result is correct!
That's because you're using the complex math library to find the square root.
After all,
5+0j
Is the complex square root of 25:
(5+0j)*(5+0j) = 25 + 2*0j + (0j)^2 = 25 + 0 + 0 = 25
Use the math
module instead for "regular" square roots.
Or: use access the real part via:
root.real
Generally, you may want to use complex numbers instead of natural numbers for generality and for math error detection - but that's another discussion.
cmath
is good for complex numbers, not real ones. This should work!
import math
import cmath
def sqrt(n):
if n < 0:
return cmath.sqrt(n)
else:
return math.sqrt(n)