简体   繁体   中英

turn negative number to imaginary

I am making a program that can calculate the resolution of a quadratic equation. This works when the discriminant d is non-negative, but not for complex roots.

How can I insert a imaginary square root?

import math
a = input("insert the value of a: ")
b = input("insert the value of b: ")
c = input("insert the value of c: ")
def d(a,b,c) : return (b**2)-(4.*a*c)
def x1(d,a,b,c) : return (b-(2.*b))+(math.sqrt ( d ))/2.*a
def x2(d,a,b,c) : return (b-(2.*b))-(math.sqrt ( d ))/2.*a
print ("the values of D,X' e X'' respectively: ")
print (d(a,b,c),x1(d,a,b,c),x2(d,a,b,c))

Also, when I use a=4 b=4 c=1 and d was going to be 0 , I get the following error. I'm not sure what's wrong here.

    Traceback (most recent call last):
  File "H:/Python27/equation2.py", line 9, in <module>
    print (d(a,b,c),x1(d,a,b,c),x2(d,a,b,c))
  File "H:/Python27/equation2.py", line 6, in x1
    def x1(d,a,b,c) : return (b-(2.*b))+(math.sqrt ( d ))/2.*a
TypeError: a float is required

You're trying to take the sqrt of a function. The function name does not automatically represent the result of the most recent call. Try a temporary variable:

d_result = d(a,b,c)
print (d_result, x1(d_result,a,b,c), x2(d_result,a,b,c))

This fixes only the fatal error; the immediate problem is still that you don't handle complex roots. Note: for your given case of a=b=c=4, the discriminant is -48, not 0, as your posting states.

Here, you have two courses:

  1. Read the documentation on complex numbers available in Python
  2. Write the complex parts yourself: take the sqrt of abs(d_result), save that as the imaginary part, and compute the real part separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM