计算级数时除以零误差
Division by Zero error in calculating series
我正在尝试计算一个序列,但我 运行 遇到了一个我不知道为什么会发生的问题。
“运行时警告:在 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 = 1 运行 你的代码。在第二次迭代中,k^(2*z)
的结果等于 0,所以零除法误差来自哪里 (2^2 *1 = 0).
我正在尝试计算一个序列,但我 运行 遇到了一个我不知道为什么会发生的问题。
“运行时警告:在 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 = 1 运行 你的代码。在第二次迭代中,k^(2*z)
的结果等于 0,所以零除法误差来自哪里 (2^2 *1 = 0).