我如何优化我的代码,使之和无穷大或非常大的数字在下面的具体公式?

2024-05-23 17:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一个公式来确定成功概率为p的Bernoulli试验。公式是:https://imgur.com/gallery/IyqcYSr

下面的代码适用于小数字,比如如果输入是outerSum(2,20,7,.25,.75),它的计算结果大约是2.44x10^-6(这是正确的,我用maple检查过)。你知道吗

然而,我的问题是,当我在大数字上运行它时(我使用的是公式),代码对它不起作用,并给我一个错误:ValueError: -inf + inf in fsum。你知道吗

我的理想输入是outerSum(2,31290,1755,.25,.75),但是我收到了上面的错误。我如何优化我的代码,使之和无穷大或非常大的数字在下面的具体公式?理想的输入场景是outerSum(2,31290,1755,.25,.75)

import math
from sympy import binomial
import numpy
def innerSum(k,n,x,y):
   #z = ((n - k * x - y) / k)

   f = []
   g = 0
   for j in range(0, int(math.floor(n - k * x - y / k))):
     b = math.pow(-1, j)
     c = binomial(y + 1, j)
     d = binomial(n - k * x - j * k, y)

     e = b * c * d
     f.append(e)
     g = math.fsum(f)

  return g

def outerSum(k,n,x,p,q):
  a = math.floor((n - k * x) / k)  # math.floor(((n-k*x)/k))
  a = int(a)
  b = (n - k * x)
  b = int(b)

  h = []

  for y in range(a, b + 1):
    c = math.pow(q, y)
    d = math.pow(p, n - y)
    e = binomial(y + x, x)

    f = innerSum(k, n, x, y)

    g = c*d*e*f
    h.append(g)
    i = math.fsum(h)
    #print(i)
  print(i)

outerSum(2,20,7,.25,.75)

Tags: 代码inimport错误数字math公式int