【问题标题】:I am getting a warning <RuntimeWarning: invalid value encountered in sqrt>我收到警告 <RuntimeWarning: 在 sqrt 中遇到无效值>
【发布时间】:2016-12-31 14:46:54
【问题描述】:

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

【问题讨论】:

  • 根据变量 a、b 和 c 的输出以及我的样本计算。我不应该得到 b**2 - (4*a*c) 的值的 -ve 数字。尽管如此,它还是给出了一些“nan”值。
  • b**2 - (4*a*c) 中有一个值为-3.1107176892482471 的负数。其实有很多
  • @MaroofG 你肯定有负值。看我的回答。

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


【解决方案1】:

这不是 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

【讨论】:

  • 是的!!,它确实会生成 -ve 值。感谢您指出了这一点。我将随机样本生成器更改为“np.random.sample”,它按预期工作。感谢您的帮助 DeepSpace 和 @dunder
【解决方案2】:

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

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

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

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

希望对你有帮助

【讨论】:

    【解决方案3】:

    没有为严格的负实数定义平方根,numpy 将为“实”dtype intfloat 的负输入产生nan,它是两个特殊值-np.infnan

    但是,对于所有 complex dtype 都定义了平方根:

    dtype example x np.sqrt(x) RuntimeWarning
    Positive float 1. 1.
    Positive int 1 1
    Positive complex 1+0J 1
    Negative float -1. nan ⚠️
    Negative int -1 nan ⚠️
    Negative complex -1+0j 1j
    np.inf np.inf
    -np.inf nan ⚠️
    np.nan nan

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2013-01-29
      • 2019-04-10
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多