필터 지우기
필터 지우기

Finding an approximation for cos(x) using for loops

조회 수: 7 (최근 30일)
Laura
Laura 2013년 11월 17일
댓글: Weeraphol Egsaphung 2017년 9월 23일
Hi there,
I recently got help on creating a script to calculate the value of cos(x) using for loops. The question asks:
"Write a script which will calculate the value of cos(x) (ask the user for the value of x and n):
cos(x)=( from k=1 –> n )∑(-1) ̂(k-1)(x ̂(2(k-1))/(2(k-1))!)
" I had real problems getting the answer and so asked a tutor to help me with it. She managed to get the code working but I failed to understand how it actually works. (her explanation was not very clear)
So, I have sat staring at it for ages and it still doesn't make sense to me.
Here it is:
% Ask user for values x, n
x=input('Please enter a value for x: '); %cos angle
x_rad=x*pi/180;
n=input('Please enter a value for n: '); %nth term
%factorial
fact=1;
sum=0;
for k=1:n
initial=-1;
for a=0:(k-1)
initial=(-1)*initial;
end
numerator=1;
for b=1:2*(k-1)
numerator=numerator*x_rad;
end
for t=1:2*(k-1)
fact=fact*t;
end
total=(initial*numerator)/fact;
sum=sum+total;
end
fprintf('cos(%d)=%6.6f \n',x,sum);
Can anyone explain how this code is working in the for loop? I am so confused.
Also, any advice on a simpler way to do this?
Thanks so much, Laura
  댓글 수: 2
Walter Roberson
Walter Roberson 2013년 11월 17일
Which "for" loop ?
Laura
Laura 2013년 11월 17일
All of them. I don't understand why we need nested for loops in the first place and why the end values for each one is different. (e.g. for b=1:2*(k-1))

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

채택된 답변

Umair Nadeem
Umair Nadeem 2013년 11월 17일
편집: Umair Nadeem 2013년 11월 17일
The code has been developed using a more complex approach. You can simply implement the equation you gave above. Here is how to do it.
% Ask user for values x, n
x=input('Please enter a value for x: '); %cos angle
x_rad=x*pi/180;
n=input('Please enter a value for n: '); %nth term
% Initialize resultant variable
sum=0;
for k=1:n
initial = (-1)^(k-1);
numerator = x_rad^(2*(k-1));
denominator = factorial(2*(k-1));
total=(initial*numerator)/denominator;
sum=sum+total;
end
fprintf('cos(%d)=%6.6f \n',x,sum);
It will give the same result. You dont have to use nested for loops to calculate the values of ^ (to the power), you can do it right away.
Hope it helps
  댓글 수: 1
Weeraphol Egsaphung
Weeraphol Egsaphung 2017년 9월 23일
Hi, I wonder the value of >> fprintf('cos(%d)=%6.6f \n',x,sum); if I want it sin How could I use the code

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by