gpt4 book ai didi

python - 我收到警告

转载 作者:太空狗 更新时间:2023-10-29 22:10:41 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com