Computing a series with large numbers : Python

2019-08-17 18:21发布

Note: Corrected the silly mistake pointed out in the line for i in xrange(10000)

I am writing a code for calculating and plotting MittagLeffler functions using a series expansion,

import numpy as np
import scipy as sp
from decimal import Decimal
import pylab as plt
from math import gamma


def MLf(x,a):
    mlf = Decimal(0)
    X = (x)
    term = Decimal(0)
    for j in xrange(100):
        term = Decimal((-1)**j*(X**(j*a)))/Decimal(gamma(a*j+1))
        mlf = Decimal( term + mlf )
    return mlf


x = np.arange(0,1000,0.1)
y = np.arange(0,1000,0.1)

for i in xrange(10000):
    y[i] = MLf(x[i],1)


plt.plot(x,y)
plt.show()

However, the calculation of the function (MLf) seems to fail for x>30.

This is likely due to the divergence of series due to the limited number of iterations. But, if I increase the number of iterations, it shows a math range error.

Here is the snippet of values, showing where it starts diverging

x        y 
40.8 -10.9164990034 
40.9 -12.2457070844 
41.0 -17.4658523232 
41.1 -10.8310002768 
41.2 -10.5217830371 
41.3 -13.9001627961 
41.4 -30.8944707201 

1条回答
三岁会撩人
2楼-- · 2019-08-17 19:06

You are re-using x and y at the end, but only replacing indices up to 100. So do this at the end and it works:

for i in range(10000):  # Or use xrange in Python 2.7
    y[i] = MLf(x[i], 1)

plt.plot(x,y)
plt.show()

Or make different arrays for this part.

查看更多
登录 后发表回答