필터 지우기
필터 지우기

Approximation of Sine Using Script

조회 수: 10 (최근 30일)
Ben
Ben 2012년 5월 27일
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.

답변 (1개)

Walter Roberson
Walter Roberson 2012년 5월 27일
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
Ben
Ben 2012년 5월 27일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by