Plot Taylor series for cos?
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi guys, I have been trying to create a Taylor series to solve for cos x, it works will with me but when I want to plot the series it gives me a white graph, here is the code I have written, but I don't know where to but the plot so the series would be drawn
x = input('enter the angle')
n = input ('number of terms')
i=0;
sum=0;
past=0;
present=0;
while i<=n
error=abs(present-past)/present*100
sum= sum+(((-1)^i)*x^(2*i)/factorial(2*i))
past=present;
present=sum;
i=i+1;
end
댓글 수: 0
답변 (1개)
Geoff Hayes
2015년 10월 17일
Abdullah - what do you want to plot? The sum at each iteration of the loop so that you can see the Taylor series converge to the expected solution? If so, then you will have to keep track of each sum from each iteration (step) of the loop. A couple of things - never name a local variable to have the same name as a MATLAB built in function. In this case, use taylorSeries (or something else) instead of sum. Try the following code
x = input('enter the angle: ');
x = x*pi/180; % convert to radians
n = input ('number of terms: ');
func = @(x,k)(((-1)^k)*x^(2*k)/factorial(2*k));
taylorSeries = zeros(n,1);
taylorSeries(1) = func(x,0);
for k = 1:n-1
taylorSeries(k+1) = taylorSeries(k) + func(x,k);
end
plot(taylorSeries);
Try the above and see what happens!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Annotations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!