计算大数系列:Python [英] Computing a series with large numbers : Python
问题描述
注意:更正了 for i in xrange(10000)
我正在编写使用级数展开计算和绘制 MittagLeffler 函数的代码,
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()
然而,对于 x>30,函数 (MLf) 的计算似乎失败了.
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
推荐答案
您在末尾重复使用 x
和 y
,但只替换了最多 100 个索引. 所以最后这样做,它的工作原理:
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.
这篇关于计算大数系列:Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!