Cant convert complex to float on python 3

Cant convert complex to float on python 3

the problem is just that your format string is for floats and not for complex numbers. something like this will work:

print({:#.3} .format(5.1234 + 4.123455j))
# (5.12+4.12j) 

or – more explicit:

print({0.real:.3f} + {0.imag:.3f}i.format(5.123456789 + 4.1234556547643j))
# 5.123 + 4.123i

you may want to have a look at the format specification mini language.

# as format specifier will not work with the old-style % formatting…

then there are more issues with your code:

if((D== -D)|(A==0)):

why not if D==0:? and for that it might be better to use cmath.isclose.

then: | is a bit-wise operator the way you use it; you may want to replace it with or.

your if statement could look like this:

if D == 0 or A == 0:
# or maybe
# if D.isclose(0) or A.isclose():

The problem with using sqrt imported from cmath is that it outputs a complex number, which cannot be converted to float. If you are calculating a sqrt from positive number, use math library (see below).

>>> from cmath import sqrt
>>> sqrt(2)
(1.4142135623730951+0j)
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951

Cant convert complex to float on python 3

Leave a Reply

Your email address will not be published. Required fields are marked *