Why does this not correctly evaluate e^x using the Taylor series?

89 Views Asked by At

I am attempting to write a function called expSeries which uses another function factFunc to evaluate e^x. I have already written the function factFunc, as shown below:

function fact = factFunc(n) 
    f = 1;
    for a = 1:b
        f = f*a;            
    end
    fact = f;
end

I am now attempting to write the function expSeries which evaulates e^x using the Taylor series. This is what I have so far:

function expo = exponentialFunc(x) 
terms = input('Enter the number of terms');
b = 0;
for i = 1:terms
        b = x/factFunc(terms);
end
expo = b;
end

And in the main program, I have

n = exponentialFunc(4);
disp(n);

Where in this instance I am trying to find e^4. However, the output is not what expected. Does anyone have any idea where I am going wrong?

1

There are 1 best solutions below

0
On

Fix to factFunc:

function fact = factFunc(n) 
    f = 1;
    for a = 1:n
        f = f*a;            
    end
    fact = f;
end

Fix to exponentialFunc

function expo = exponentialFunc(x) 
    terms = input('Enter the number of terms');
    b = 0;
    for i = 0:terms-1
            b = b + x^i/factFunc(i);
    end
    expo = b;
end

Example

>> exponentialFunc(4)
Enter the number of terms10

ans =

   54.1541

Note exp(4) = 54.59815...