2014-10-10 68 views
0

我想在Python中编写和绘制Weierstrass函数。Weierstrass Python中的函数列表索引超出范围错误

http://mathworld.wolfram.com/WeierstrassFunction.html

F(X)=Σsin(πK^(a)中X)/(πK^(a))的从k = 1到∞

我有点卡住,因为我在行yval = wer(a,(xl [i])处运行一个“列表索引超出范围错误”,e)

我不确定我要去哪里错误,或者如果我的想法过程不正确。任何帮助是极大的赞赏!谢谢!

下面是代码:

import math,pylab 

x0 = float(input('Enter beginning of interval: ')) #start of interval 
xf = float(input('Enter endpoint of interval: ')) #end of interval 
a = float(input('Enter a value for a: ')) 
#x = float(input('Enter a value for x: ')) 
e = float(input('Enter desired error tolerance: ')) 
n = int(input('Enter number of iterations: ')) 

def wer(a, x, e): # a is givin number, e is error tolerance 

    Sum1 = 0 
    Sum2 = 0 
    k = 1 

    while(True): 
     #sine of pi times k to the a times x over pi times k to the a 
     Sum1 = math.sin((math.pi)*pow(k,a)*(x))/((math.pi)*(pow(k,a))) 
     Sum2 = Sum1 + math.sin((math.pi)*pow((k+1),a)*(x))/((math.pi)*pow((k+1),a)) 

     if (abs(Sum2-Sum1) < e): 
      break 
     else: 
      k+=1 
    return Sum1 

def append(x0, xf, n): 

    xl = [] #list containing x values 
    yl = [] #corresponding y values 
    dx = (xf-x0)/n #length of each subinterval 

    for i in range (0, (n+1)): 
     xval = x0 + (i * dx) 
     yval = wer(a, (xl[i]), e) #ERROR HERE 

     xl.append(xval) 
     yl.append(yval) 
     #print i,':',xl 
    return xl, yl 


append(x0, xf, n) 
pylab.plot(xl,yl) 

回答

0

在每次迭代开始时,xl还没有第012个元素,因为您在循环的末尾添加了它;您应该在计算xval后立即执行xl.append,或者在yval公式中只使用xval而不是xl[i]

+0

非常感谢,我很确定它正常工作! – The3ventHoriz0n 2014-10-10 17:18:53

0

第一次通过设置在端XL环[0]将被传递到的WER功能,但XL是一个空数组。我不确定你在做什么,但是它应该是xval,而不是xl [0]传递给函数?

+0

谢谢,这让我指出了正确的方向! – The3ventHoriz0n 2014-10-10 17:18:21