Clear Filters
Clear Filters

Approximation of Sine Using Script

10 views (last 30 days)
Ben
Ben on 27 May 2012
Hello. I made a script that approximates sin(x) using the series x - x^3.3! + x^5/5! - ..... It is (x = value you wish to approximate, n = number of terms for the approximation series):
function out = ApproxSin (x,n)
out = 0;
for k = 0:n-1;
out = out + (-1)^k * x^(2*k+1)/factorial(2*k+1);
end
y = sin(x);
percenterror = (abs((out - y)/y))*100;
It works well - I was able to make it display the amount of percent error based on how many terms were used in the equation.
What I want to try doing now is the opposite. I want an approximation of less or equal to 1%, and MATlab to be able to calculate the number of terms automatically to do so. I've been trying to use a while loop to do so:
function out = ApproxSin2 (x)
y = sin(x);
b = (1/100*y) + y
c = -(b-y)+y
k = 0
p = 0
while b < p < c
k = k+1
p = x + (-1)^k * x^(2*k+1)/factorial(2*k+1)
end
But this doesn't work and I'm not sure why it doesn't. I was wondering if someone could modify the code above slightly so that the "while loop" could work. Thanks for your assistance.

Answers (1)

Walter Roberson
Walter Roberson on 27 May 2012
while b < p < c
means
while (b < p) < c
which means to compare b to p, get the value 0 (false) or 1 (true), and then compare that 0 or 1 to c.
while b < p & p < c
  1 Comment
Ben
Ben on 27 May 2012
Alright, I tried it, but for some reason it still doesn't work.
From the code, I was trying to get a loop to keep going until p was within 1% from the actual answer (b was the actual value + 1% and c was the actual value - 1%).
When I run the code though it states "k = 0 and p = 0" and it stops; I wanted it to keep increasing "k" until p was between b and c, but the code just seems to stop at p = 0 (the entire "while" loop is somehow being skipped). What could I do to fix this?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!