1
sqrtnum_ = 0
sqrtnum_ = cmath.sqrt(snum_)

print "Using cmath.sqrt:"
print "    sqrt(", snum_, ") =      ", '%.12f' %sqrtnum_

How can I limit the number of decimal places. Normally I would use the above but it does not work with complex numbers

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Kurohane
  • 33
  • 2
  • 9

2 Answers2

1

This looks to be a duplicate of Formatting Complex Numbers

hopefully that helps!

(would have followed duplicate marking/commenting/etc protocol, but lack the rep for it)

Community
  • 1
  • 1
rbauer
  • 78
  • 5
1

You can use imag and real attributes of a complex number to get their respective values.

>>> a = cmath.sqrt(-1000)
>>> "%.12f + %.12fj"%(a.real,a.imag)
'0.000000000000 + 31.622776601684j'

This works for completely real numbers also

>>> a = cmath.sqrt(1000)
>>> "%.12f + %.12fj"%(a.real,a.imag)
'31.622776601684 + 0.000000000000j'
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140