ValueError: Math domain error (for a 2nd grade equation function)

后端 未结 2 1139
挽巷
挽巷 2021-01-23 11:42

I\'ve tried to solve the problem myself but i cant. Its a function in order to solve 2nd grade equations when y=0 like \'ax2+bx+c=0\'. when i execute it it says me there is math

2条回答
  •  礼貌的吻别
    2021-01-23 12:14

    The issue here is that the standard math library in python cannot handle complex variables. The sqrt you've got up there reflects this.

    If you want to handle a function that could have complex variables (such as the one above) I would suggest using the cmath library, which has a replacement cmath.sqrt function.

    You could change your above code to the following:

    from cmath import sqrt
    
    a = raw_input('put a number for variable a:')    
    b = raw_input('put a number for variable b:')    
    c = raw_input('put a number for variable c:')
    
    a = float(a)    
    b = float(b)    
    c = float(c)`
    
    x = (-b + sqrt((b**2) - 4 * a * c)) / 2 * a    
    print x`
    
    x = (-b - sqrt((b**2) - 4 * a * c)) / 2 * a`    
    print x
    

    and it should fix your problem (I also made some edits to make the code look a little more pythonic (read: pep8 compliant))

提交回复
热议问题