我收到警告< RuntimeWarning:在sqrt中遇到无效的值> [英] I am getting a warning <RuntimeWarning: invalid value encountered in sqrt>
本文介绍了我收到警告< RuntimeWarning:在sqrt中遇到无效的值>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在python中运行一个二次方程.但是,它一直在警告我
I am trying to run a quadratic equation in python. However, it keeps on giving me a warning
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)
推荐答案
这与Python并非100%相关.您不能计算负数的平方根(当处理实数时).
This is not 100% Python related. You can't calculate the square root of a negative number (when dealing with real numbers that is).
b**2 - (4*a*c)
为负数时,您没有采取任何预防措施.
You didn't take any precautions for when b**2 - (4*a*c)
is a negative number.
>>> import numpy as np
>>>
>>> np.sqrt(4)
2.0
>>> np.sqrt(-4)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan
让我们测试一下您是否具有负值:
Let's test if you have negative values:
>>> 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
这篇关于我收到警告< RuntimeWarning:在sqrt中遇到无效的值>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文