-6

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?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
user2151341
  • 47
  • 2
  • 3
  • 5

4 Answers4

6

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

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.

asheeshr
  • 4,088
  • 6
  • 31
  • 50
0

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.

jrd1
  • 10,358
  • 4
  • 34
  • 51
0

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)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Lucas Urban
  • 627
  • 4
  • 15