[英]Weierstrass Function in Python-List index out of range error
I am trying to code and plot the Weierstrass function in Python. 我正在尝试在Python中编码和绘制Weierstrass函数。
http://mathworld.wolfram.com/WeierstrassFunction.html http://mathworld.wolfram.com/WeierstrassFunction.html
f(x)=∑sin(πk^(a)x)/(πk^(a)) from k=1 to ∞ f(x)= ∑sin(πk^(a)x)/(πk^(a))从k = 1到∞
I'm a little stuck because I keep running into a "list index out of range error" at the line yval = wer(a, (xl[i]), e) 我有点卡住了,因为我在yval = wer(a,(xl [i]),e)行不断遇到“列表索引超出范围错误”
I'm not sure where I'm going wrong, or if my thought process is incorrect. 我不确定我要去哪里哪里,或者我的思维过程不正确。 Any help is greatly appreciated!
任何帮助是极大的赞赏! Thanks!
谢谢!
Here is the code: 这是代码:
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)
The first time through the loop at the end xl[0] will be passed to the wer function but xl is an empty array. xl [0]末尾的循环中的第一时间将传递给wer函数,但xl是空数组。 I am not sure what you are trying to do but should it be xval that you pass to the function rather than xl[0]?
我不确定您要做什么,但是传递给函数而不是xl [0]应该是xval吗?
At the start of each iteration xl
doesn't have the i -th element yet, since you add it at the end of the loop; 在每个迭代的开始,
xl
还没有第i个元素,因为您在循环的末尾添加了该元素; you should either perform the xl.append
immediately after calculating xval
, or just use xval
instead of xl[i]
in the yval
formula. 您应该执行
xl.append
计算后立即xval
,或只使用xval
代替xl[i]
中yval
式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.