Python 我收到一个警告 <RuntimeWarning: invalid value 在 sqrt>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39123766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:53:36  来源:igfitidea点击:

I am getting a warning <RuntimeWarning: invalid value encountered in sqrt>

pythonpython-2.7python-3.xnumpymath

提问by Maroof G

I am trying to run a quadratic equation in python. However, it keeps on giving me a warning

我正在尝试在 python 中运行二次方程。但是,它不断给我警告

RuntimeWarning: invalid value encountered in sqrt

Here's my code:

这是我的代码:

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)

回答by DeepSpace

This is not 100% Python related. You can't calculate the square root of a negative number (when dealing with real numbers that is).

这不是 100% 与 Python 相关的。您无法计算负数的平方根(在处理实数时)。

You didn't take any precautions for when b**2 - (4*a*c)is a negative number.

您没有对 whenb**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

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

回答by Michael Green

If you're hoping to do complex analysis (working with imaginary numbers as defined by sqrt(-1)) you can import cmath and use cmath.sqrt(-1) instead of numpy.sqrt(-1).

如果您希望进行复杂分析(使用由 sqrt(-1) 定义的虚数),您可以导入 cmath 并使用 cmath.sqrt(-1) 而不是 numpy.sqrt(-1)。

For example, when I'm calculating the refractive index of materials from permittivity and permeability (by definition, j is involved), I'll write functions in python as such:

例如,当我根据介电常数和磁导率计算材料的折射率时(根据定义,涉及 j),我将在 python 中编写如下函数:

def n(f):
    y = cmath.sqrt(mu1f(f) - j*mu2f(f)) * (e1f(f) - j*e2f(f))
    return y.real

Where e1f etc. are previously defined interpolating functions, all of which are a function of incident frequency f. The y resultant is, in it of itself, a complex value, the complex index of refraction, but I'm oftentimes only interested in the real portion (the refractive index) so that is what is returned.

其中 e1f 等是先前定义的插值函数,所有这些都是入射频率 f 的函数。结果 y 本身就是一个复数值,即复折射率,但我通常只对实部(折射率)感兴趣,所以这就是返回的内容。

Hope this helps

希望这可以帮助