0

Hello, im trying to create a cos function in MATLAB, but it is wrong. :/

well from Taylor serie we have

cosx = 1 - x^2/2! + x^4/4! - x^6/6! +... + x^n/n!

or for noobs ->

cosx = x^1/1! - x^2/2! + x^4/4! - x^6/6! +... + x^n/n!

this is my code in MATLAB

function y = cosine(x,n)
sum = x;
term = x;
for i = 1:2:n %with step 2
      temp = -temp * (x^i/i);
      sum = sum + temp;
end
y = sum;

I try this also

function y = cosine(x,n)
sum = x;
term = x;
for i = 1:2:n %with step 2
      temp = -temp * x *x /(i*(i+1)); 
      sum = sum + temp;
end
y = sum;

Any help how i can fix term?

Edited by Panathinaikos22: n/a

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by Panathinaikos22
0

You are adding it wrong... I can't remember whether Matlab has a built-in function for factorial. If not, you need to implement it yourself. Shouldn't be that difficult.

Actually x^1/1! is not always equal to 1. If it is wrong, you may need to do it differently as...

Let see if this is what should be like...

sum = 1;
temp = -1;
for i = 2:2:n %with step 2
      sum += temp * ((x^i)/fact(i));
      temp = -temp;
end

PS: Your code starts the value of "i" with 1 and step up 2, so the values used in the function are 1, 3, 5, ...
PSS: The value "n" in your function is still unclear to me. Is it the maximum it should go or it is else?

Edited by Taywin: n/a

-1

You are adding it wrong... I can't remember whether Matlab has a built-in function for factorial. If not, you need to implement it yourself. Shouldn't be that difficult.

Actually x^1/1! is not always equal to 1. If it is wrong, you may need to do it differently as...

Let see if this is what should be like...

sum = 1;
temp = -1;
for i = 2:2:n %with step 2
      sum += temp * ((x^i)/fact(i));
      temp = -temp;
end

PS: Your code starts the value of "i" with 1 and step up 2, so the values used in the function are 1, 3, 5, ...
PSS: The value "n" in your function is still unclear to me. Is it the maximum it should go or it is else?

Founded

Edited by Panathinaikos22: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.