【问题标题】:Division by Zero error in calculating series计算系列中除以零误差
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 大声笑,谢谢!这给出了一个确定的值,我忘了把 ^ 改成 **。
  • 从 C 切换到 Python 后,它也曾经和我在一起。祝你好运!
猜你喜欢
  • 1970-01-01
  • 2020-07-31
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多