我正在尝试在 python 中运行二次方程。但是,它一直给我警告
RuntimeWarning: invalid value encountered in sqrt
这是我的代码:
import numpy as np
a = 0.75 + (1.25 - 0.75)*np.random.randn(10000)
print(a)
b = 8 + (12 - 8)*np.random.randn(10000)
print(b)
c = -12 + 2*np.random.randn(10000)
print(c)
x0 = (-b - np.sqrt(b**2 - (4*a*c)))/(2 * a)
print(x0)
最佳答案
这不是 100% Python 相关的。您无法计算负数的平方根(在处理实数时)。
当 b**2 - (4*a*c)
为负数时,您没有采取任何预防措施。
>>> import numpy as np
>>>
>>> np.sqrt(4)
2.0
>>> np.sqrt(-4)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan
让我们测试一下你是否有负值:
>>> import numpy as np
>>>
>>> a = 0.75 + (1.25 - 0.75) * np.random.randn(10000)
>>> b = 8 + (12 - 8) * np.random.randn(10000)
>>> c = -12 + 2 * np.random.randn(10000)
>>>
>>> z = b ** 2 - (4 * a * c)
>>> print len([_ for _ in z if _ < 0])
71
关于python - 我收到警告 <RuntimeWarning : invalid value encountered in sqrt>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39123766/