Taylor Series for arctan
8 views (last 30 days)
Show older comments
I need to write a function that approximates the Taylor Series of arctan(x), with the inputs being x and the error tolerance, and the outputs being the number of terms and the approximation. Here is what I have so far:
function [ARCtanx,n] = arctan_series(x,error)
n = 0;
counter = 0;
while true
counter = counter + 1;
series = (-1)^(n)*x^(2*n+1)/(2*n+1);
terms(counter) = series;
ARCtanx = sum(terms);
actualerror = abs((atan(x) - ARCtanx)/(atan(x))*100);
if actualerror <= error
break
end
n = n +1
end
end
It runs forever, so I know something is wrong with my if statement but I'm not quite sure how to fix it.
0 Comments
Answers (1)
John D'Errico
on 24 Jan 2018
Edited: John D'Errico
on 24 Jan 2018
There are a few issues here that careful coding would clean up. For example, why do you need variables n AND counter, when both of them do essentially the same thing? But that is just being picky. Code that works is adequate.
By the way, using names like error is a bad idea, as error is a useful function in MATLAB. Again just nitpicking, but it will be important one day to you.
More to the point, what values for x and what error tolerance have you chosen? Have you considered if that series will converge in a reasonable amount of time? If it will ever converge for some x? For what x does it converge?
Note that this is the kind of problem often posed by instructors. Give the student a series that will give them headaches. Then follow that up in the next class to show why. For example, what does this series reduce to when x==1? What do you know about that series?
Does your code converge for small x? For example, how does it do for x = 0.1?
The issue of how to fix the series is easy enough here, but sometimes quite difficult on some other series. For example, for abs(x)>1, is there an identity that would allow you to transform x to a value that DOES have a convergent series? This is typically how such problems are solved. Thus, can you transform the problem to a better one?
2 Comments
John D'Errico
on 24 Jan 2018
Small values of will show no problems at all. Your code should be working fine then.
That series is convergent only for abs(x)<=1. For larger values of x, things go to hell fast. If you tried it for x=pi/3, that is greater than 1. Those powers of x grow faster than the denominator goes to zero.
And look at the series when x==1. This is in fact a famous series, that converges in theory to pi/4, but it is also well known to converge incredibly slowly.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!