Why do I get math domain error?

时光毁灭记忆、已成空白 提交于 2019-12-02 08:12:26

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

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.

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