Search code examples
matlabwhile-looptaylor-series

Taylor Series using a while loop in Matlab


I'm trying to approximate cos(x) using a Maclaurin Series. The value of x and error bounds need to be user inputs, and the user needs to see the estimated value and number of iterations required to reach that answer. I'm trying to demonstrate it using x=2 and error<=.001. With these parameters, my code always returns 8 iterations, and an answer of -.0476. What have I done wrong?

function [CosApprox, Numberofterms] = cos_approx(x, E)
    k(1)=1;
    T=1;
    cos_approx(1)=1
    while T>=E
        k=k+1;
        cos_approx(k)= cos_approx(k-1) + ((-1)^(k-1))*(x^(2*(k-1)))/(2*(factorial(k-1)));
        T=abs(cos_approx(k) - cos(x));
    end
    CosApprox=cos_approx(k)
    Numberofterms=k

I'm really new to matlab, so I apologize if I've missed something obvious.


Solution

  • Your code doesn't return 8 iterations, it returns 513 iterations on my computer and it terminates because we are dividing a very big number, more than 2^(512) in the numerator and another very big number 512! which is evaluated to be Inf in the denominator.

    You are using the wrong mathematical formula.

    2*(factorial(k-1))
    

    in the denominator should have been

    factorial(2*(k-1))
    

    Just by changing that would give you an answer of -0.4159 while cos(2) is approximated -0.4161.

    Now that you figure out what is wrong, you can try to improve on the code in terms of speed and readability.

    Remark: Try not to give the same name to a vector and a function, it's confusing.