【发布时间】:2020-11-03 20:52:25
【问题描述】:
我正在尝试计算一个序列,但我遇到了一个我不知道为什么会发生的问题。
“RuntimeWarning:在 double_scalars 中遇到除以零”
当我检查代码时,它似乎没有任何奇点,所以我很困惑。这是当前的代码(log 代表自然对数)(编辑:如果有帮助,请扩展代码):
from numpy import pi, log
#Create functions to calculate the sums
def phi(z: int):
k = 0
phi = 0
#Loop through 1000 times to try to approximate the series value as if it went to infinity
while k <= 100:
phi += ((1/(k+1)) - (1/(k+(2*z))))
k += 1
return phi
def psi(z: int):
psi = 0
k = 1
while k <= 101:
psi += ((log(k))/( k**(2*z)))
k += 1
return psi
def sig(z: int):
sig = 0
k = 1
while k <= 101:
sig += ((log(k))**2)/(k^(2*z))
k += 1
return sig
def beta(z: int):
beta = 0
k = 1
while k <= 101:
beta += (1/(((2*z)+k)^2))
k += 1
return beta
#Create the formula to approximate the value. For higher accuracy, either calculate more derivatives of Bernoulli numbers or increase the boundry of k.
def Bern(z :int):
#Define Euler–Mascheroni constant
c = 0.577215664901532860606512
#Begin computations (only approximation)
B = (pi/6) * (phi(1) - c - 2 * log(2 * pi) - 1) - z * ((pi/6) * ((phi(1)- c - (2 * log(2 * pi)) - 1) * (phi(1) - c) + beta(1) - 2 * psi(1)) - 2 * (psi(1) * (phi(1) - c) + sig(1) + 2 * psi(1) * log(2 * pi)))
#output
return B
A = int(input("Choose any value: "))
print("The answer is", Bern(A + 1))
任何帮助将不胜感激。
【问题讨论】:
-
为了完整起见,您传入的 z 值是多少?
-
就我的目的而言,说 z 是一种约定,尽管稍后在代码中我创建了一个输入,并将结果打印出来。所以没有确定的值,不管我插件什么,只要大于0,就说无穷大。错误似乎来自这里。
标签: numpy math divide-by-zero