Why do I get math domain error?

前端 未结 2 1191
执念已碎
执念已碎 2021-01-28 21:43

Why do I get this error?

I\'m trying to solve an equation like this:

ax^2 + bx + c

Traceback (most recent call last):
  File \"I:/Taller de Progr         


        
2条回答
  •  春和景丽
    2021-01-28 22:10

    The math module (which I suppose you are using) doesn't support complex numbers. Either use cmath (python2 and python3) or the power operator ** (python3).

    This should always work, no matter the sign of the discriminant:

    x1 = (-b + (b ** 2 - 4 * a * c) ** .5) / 2 / a
    

    Example:

    >>> b = 1
    >>> a = 2
    >>> c = 3
    >>> (-b + (b ** 2 - 4 * a * c) ** .5) / 2 / a
    (-0.24999999999999992+1.1989578808281798j)
    

    While using math.sqrt with the same values raises the described error:

    >>> (-b + sqrt(b ** 2 - a * c)) / (2 * a)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: math domain error
    

提交回复
热议问题