Why do I get math domain error?

北慕城南 提交于 2019-12-02 16:00:41

问题


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 Programacion I/Clase 5/11.py", line 6, in <module>
    x1 = (-b + sqrt(b ** 2 - a * c)) / (2 * a)
ValueError: math domain error

回答1:


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 "<stdin>", line 1, in <module>
ValueError: math domain error



回答2:


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.



来源:https://stackoverflow.com/questions/22151038/why-do-i-get-math-domain-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!