python - 我收到警告 <RuntimeWarning : invalid value encountered in sqrt>

标签 python python-2.7 python-3.x numpy math

我正在尝试在 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/

相关文章:

python - PyQt5 使用 QFileDialog 将 QlineEdit 保存到文本文件

python - 根据值对列表进行切片

python - 聚类经纬度gps数据

限制可能值的 Python 类型提示友好类型

python - 基方法和子方法签名中的参数数量不一致

python - <训练样本> 和 <验证样本> 是什么意思?

python - 在 Python 中使用 scikit-learn kmeans 对文本文档进行聚类

Python Tkinter : Remove window border

Python/Regex 部分字符串替换

python - 检索数据直到它与下一个正则表达式模式匹配