Mar*_*f G 7 python math numpy python-2.7 python-3.x
我试图在python中运行二次方程.但是,它一直给我一个错误"RuntimeWarning:在sqrt中遇到无效值".
这是我的代码:
RuntimeWarning: invalid value encountered in sqrt
Run Code Online (Sandbox Code Playgroud)
您的专家建议将非常有帮助.提前致谢
Dee*_*ace 12
这不是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
Run Code Online (Sandbox Code Playgroud)
让我们测试你是否有负值:
>>> 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
Run Code Online (Sandbox Code Playgroud)
uke*_*emi 11
平方根不是为严格的负实数定义的,numpy 将为nan“实数”dtype 的负输入生成int, float,它是两个特殊值-np.inf和nan。
然而,平方根是为所有复数数据类型定义的:
\n| 符号 | 数据类型 | 例如 ( x) | np.sqrt(x) | 运行时警告 |
|---|---|---|---|---|
| \xe2\x9e\x95 | 浮点/整数 | 1./1 | 1./1 | |
| \xe2\x9e\x95 | 复杂的 | 1+0J | 1 | |
| \xe2\x9e\x95 | 无穷 | np.inf | np.inf | |
| \xe2\x9e\x96 | 浮点/整数 | -1./-1 | nan | \xe2\x9a\xa0\xef\xb8\x8f |
| \xe2\x9e\x96 | 复杂的 | -1+0j | 1j | |
| \xe2\x9e\x96 | 无穷 | -np.inf | nan | \xe2\x9a\xa0\xef\xb8\x8f |
| 不适用 | 南 | np.nan | nan |
| 归档时间: |
|
| 查看次数: |
25365 次 |
| 最近记录: |