计算序列除以零误差

乔纳森·戴维斯

我正在尝试计算一个序列,但遇到了一个我不知道为什么发生的问题。

“ 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))

任何帮助将非常感激。

安德烈·赛德(Andrii Syd)

您确定需要^ 按位互斥或运算符代替**吗?我尝试使用输入参数z = 1运行您的代码。在第二次迭代中,的结果k^(2*z)等于0,所以零除法误差来自(2 ^ 2 * 1 = 0)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章