Please some body get me out from this

edited January 2010 in Science & Tech
Write your own MATLAB [FONT=Times New Roman,Times New Roman][FONT=Times New Roman,Times New Roman]function [/FONT][/FONT]to compute the cosine function directly from the Taylor series:
cosx=1-x^2/2+x^4/4-x^6/6! ........The series should end when the last term is less than 10^(-6). :D

The code I have done my self is
function[y]=tall(x)
x=0;
n=0;
err=0;
tol=10.^(-6);
y=0;

while(err<TOL)< font>
n=n+1;
y=sum((-1).^n/factorial(2*n))*x.^(2*n);
err=((-1).^n/factorial(2*n))*x.^(2*n);

end
return
end

but I am not getting result please help me on that


Comments

  • edited January 2010
    I am new in programming...........
  • drasnordrasnor Starship Operator Hawthorne, CA Icrontian
    edited January 2010
    Syntax:
    1) Your function file takes an input (x) but you overwrite whatever the input is with 0 in the line x=0; This line should be omitted.

    2) You set err=0 but your while loop condition appears to be err. Since the while loop only executes when its condition evaluates to true your loop will never execute.

    3) You do not need to use 'return' in this instance. It should be omitted.

    Logic:
    You don't need to be concerned with error, you just want to evaluate the terms of the sequence, add them to find the series result, and stop evaluating when the terms are smaller than 10^(-6). There are several ways to do this with the most obvious being a while loop.

    Also, since the Taylor series approximation for cosine only uses even numbers for n it makes more sense for n to start with 0 or 2 (depending on how you decide to implement this) and increment by 2 with each iteration. This is easier to follow as well as computationally faster than multiplying n by 2 every time you want to use it in your series.

    -drasnor :fold:
  • edited January 2010
    Cheers @Dransor But still i am confused about..I am not getting result till now. EXactly I have done like this way, In above I get some mis paste in my coding...But your suggestion is still confusing to me...Please help me get out from this.


    function
    [y]=tall(x)
    x=0;
    n=0;
    err=0;
    tol=10.^(-6);
    y=0;

    while(err<tol)
    n=n+1;
    y=sum((-1).^n/factorial(2*n))*x.^(2*n);
    err=((-1).^n/factorial(2*n))*x.^(2*n);

    end
    return
    end
  • edited January 2010
    in above there should be

    while(err<tol)
    n=n+1
    .
    .
    .
  • edited January 2010
    while( err<10^(-6))
    n=n+1;
    .
    .
    .
  • drasnordrasnor Starship Operator Hawthorne, CA Icrontian
    edited January 2010
    Your while loop will only execute when err is smaller than the cutoff point. However, you're only interested in terms larger than 10^-6, so you should use err>10^(-6) instead. There are still some other major problems with your implementation though.

    -drasnor :fold:
Sign In or Register to comment.