问题
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:
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.
来源:https://stackoverflow.com/questions/48643475/computing-a-series-with-large-numbers-python