OverflowError: long int too large to convert to float in python

后端 未结 4 1871
灰色年华
灰色年华 2020-11-29 10:00

I tried to calculate poisson distribution in python as below:

p = math.pow(3,idx)
depart = math.exp(-3) * p 
depart = depart / math.factorial(idx)

4条回答
  •  自闭症患者
    2020-11-29 10:26

    The scipy module could help you.

    scipy.misc.factorial is a factorial function that can use the gamma function approximation to calculate the factorial, and returns the result using floating points.

    import numpy
    from scipy.misc import factorial
    
    i = numpy.arange(10)
    print(numpy.exp(-3) * 3**i / factorial(i))
    

    Gives:

    [ 0.04978707  0.14936121  0.22404181  0.22404181  0.16803136  0.10081881
      0.05040941  0.02160403  0.00810151  0.0027005 ]
    

    There is also a module to calculate Poisson distributions. For example:

    import numpy
    from scipy.stats import poisson
    
    i = numpy.arange(10)
    p = poisson(3)
    print(p.pmf(i))
    

    Gives:

    [ 0.04978707  0.14936121  0.22404181  0.22404181  0.16803136  0.10081881
      0.05040941  0.02160403  0.00810151  0.0027005 ]
    

提交回复
热议问题