Write a MATLAB code to estimate the exponential function. Inputs should be x and n. The outputs must include approximate value, true value, error, absolute error, and relative error.

19 Ansichten (letzte 30 Tage)
This is what I have but it's not working.
function e_to_x = exp_taylor(x,n)
e_to_x = 0;
for k = 1:n
e_to_x = e_to_x + (x^(k-1))/factorial(k-1);
end
end
approx =exp_taylor(1,3);
fprintf("Approximate value %.8f\n",approx);
fprintf("True value %.8f\n",exp(1));
truevalue = exp(1);
relerror = abs(truevalue - approx)/truevalue;
fprintf("Relative error is: ");
disp(relerror);
aberror = abs(truevalue - approx)/approx;
fprintf("Absolute error is: ");
disp(aberror);
  1 Kommentar
James Tursa
James Tursa am 21 Sep. 2019
Please be specific about what "not working" means. E.g., when I run your code I get:
>> exp(1)
ans =
2.718281828459046
>> exp_taylor(1,3)
ans =
2.500000000000000
>> exp_taylor(1,10)
ans =
2.718281525573192
>> exp_taylor(1,20)
ans =
2.718281828459046
which looks good to me ...

Melden Sie sich an, um zu kommentieren.

Antworten (1)

James Tursa
James Tursa am 21 Sep. 2019
Put your function code for e_to_x() in a separate file called e_to_x.m somewhere on the MATLAB path. Then put your other code that calls e_to_x() in a separate file and run that separate file.

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by