问题描述
我正在尝试计算序列,但遇到了一个我不知道为什么会发生的问题。
“ RuntimeWarning:除以double_scalars中的零”
当我检查代码时,它似乎没有任何奇异之处,所以我很困惑。这是当前代码(对数代表自然对数)(编辑:如果有帮助,扩展代码):
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 = 1运行您的代码。在第二次迭代中,k^(2*z)
的结果等于0,所以零除法误差从哪里来(2 ^ 2 * 1 = 0 )。