Why do I get math domain error?

前端 未结 2 1185
执念已碎
执念已碎 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:11

    It would seem that

    b**2 - a*c
    

    is negative. When you pass that value to sqrt(), you encounter the domain error.

    Even if you feel that the expression should evaluate to a positive value, floating point rounding error can lead to a negative value. Remember that floating point arithmetic is not exact.

    Although a more likely explanation is that you have transcribed the expression incorrectly. Surely you meant:

    b**2 - 4*a*c
    

    Having said that, if the quadratic has no real solutions, then you will encounter the domain error. And if the quadratic has repeated real solutions (that is both solutions have the same value), then rounding error can also lead to the domain error.

    For instance consider the equation:

    (x-0.7)(x-0.7) = 0
    

    The coefficients are:

    a: 1.0
    b: -1.4
    c: 0.49
    

    If I feed these into Python I get the following:

    >>> a=1.0
    >>> b=-1.4
    >>> c=0.49
    >>> b**2 - 4*a*c
    -2.220446049250313e-16
    

    So even with an equation that has a real solution, you can still fall foul of this problem.

提交回复
热议问题