CS考试辅导 function approxExp(x)

function approxExp(x)
% approximate the exponential function at x using the Taylor series
% expansion 1 + x + (1/2)x^2 + (1/6)x^3 + …
% no matter how large x is, the power x^n in the numerator will eventually

Copyright By PowCoder代写 加微信 powcoder

% become smaller than the n! (n-factorial) in the denominator, so the
% terms eventually become small enough that they no longer change the
% accumulated sum
oldsum = single(0);
newsum = single(1);
term = single(1);
% terminates when new sum is no different from old sum
while newsum ~= oldsum
oldsum = newsum;
n = n + 1;
term = term*x/n; % term has the value (x^n)/(n!)
newsum = newsum + term;
fprintf(‘n = %d, term = %g, newsum = %g\n’, n,term,newsum);
fprintf(‘from summing the series, exp(x) = %g\n’, newsum);
fprintf(‘using the standard function, exp(x) = %g\n’, exp(x))

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com