Can't convert complex to float on python 3

I write this code for uri online judge(problem no.1036)...It is an Bhaskara's formula...

import cmath
A,B,C=input().split()
A = float(A)
B = float(B)
C = float(C)
D = (B*B)-(4*A*C)
if((D== -D)|(A==0)): print("Impossivel calcular")
else: T = cmath.sqrt(D) x1 = (-B+T)/(2*A) x2 = (-B-T)/(2*A) print("R1 = %.5f" %x1) print("R2 = %.5f" %x2)

but when i submit this program...that runtime error occured...

Traceback (most recent call last): File "Main.py", line 14, in print("R1 = %.5f" %x1)
TypeError: can't convert complex to float
Command exited with non-zero status (1)

please help me to solve this problem.

1

2 Answers

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

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():
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like