While loop runs infinitely
Show older comments
I'm trying to create a function that takes two parameters: x and threshold. X is the angle and the threshold is the percent error I need to get when approximating sine with the taylor series. However my while loop runs infinitely and I'm very confused as to how do go about fixing it.
Here's what I have so far.
function [approx, terms] = approx_sine(x, threshold)
approx = x; % Initial approximation
terms = 0; % Number of additional terms added to improve the approximation;
% Write your code here using a while loop to improve the above approximation
while threshold <= abs((sin(x)-approx)/sin(x))
terms = terms + 2;
approx = (-1)^(terms+1)*(x.^terms)/ factorial(terms)+x;
end
end
Accepted Answer
More Answers (1)
Walter Roberson
on 1 Dec 2015
Remove the line
threshold = abs((sin(x)-approx)/sin(x))
It is overwriting the threshold that you passed in.
2 Comments
Anthony Siddique
on 1 Dec 2015
Walter Roberson
on 1 Dec 2015
>> limit((-1)^(terms+1)*x^terms/factorial(terms), terms = infinity);
0
Your approx is (-1)^(terms+1)*x^terms/factorial(terms) + x . As I indicate above, as terms increases, the first part of that tends to 0 for all x. With the first part tending to 0, only the second part will start to matter, the "+ x" part. Your approx goes to x.
Your termination test then becomes
threshold <= abs((sin(x)-x)/sin(x))
or threshold <= abs(1 - x/sin(x))
For any given threshold there is a limited range of x that can satisfy this, and that range of x does not increase smoothly with the threshold.
Categories
Find more on Special Functions in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!