Write a recursive version horner_recursive m of horner.m. Test it on the polynom
ID: 3111787 • Letter: W
Question
Write a recursive version horner_recursive m of horner.m. Test it on the polynomial p and x values from Example 5.1, but with 1,000 terms instead of 100,000. Evaluate p(x) = sigma^100000_k = 1 x^k/k^2 at x = - 1, - 1/2, 1/2 1 with peval, horner, and polyval: > > format long > > a = [0, 1./(1: 100000).2]: % a_0 = 0 > > x = [- 1, -.5, .5, 1]: > > tic, peval(a, x), toc ans = - 0.822467033374095 -0.448414206923646 0.582240526465012 1.644924066898242 Elapsed time is 0.082717 seconds. > > tic, horner(a, x), toc ans = - 0.822467033374114 - 0.448414206923646 0.582240526465013 1.644924066898226 Elapsed time is 0.030736 seconds. > > tic, polyval(a(end: -1: 1), x), toc ans = -0.822467033374114 - 0.448414206923646 0.582240526465013 1.644924066898226 Elapsed time is 0.031449 seconds. Horner's rule is more efficient. Note that polyval yields similar timing and identical values! The values obtained with peval at x = plusminus 1 are somewhat different. Since^1 sigma_k greaterthanorequalto 1 (- 1)^k/k^2 = - pi^2/12 almostequalto -0.822467033424113 and sigma_k greaterthanorequalto 1 1/k^2 = pi^2/6 almostequalto 1.644934066848226Explanation / Answer
%%%%%matlab function
function y = horner_recursive ( fx,N,x0);
for k=1:length(x0)
f=0;
for n=1:N
f=f+feval(fx,x0(k),n);
end
y(k)=f;
end
%%% Main program
format long
fx=@(x,k) x^k/k^2;
x0=[-1 -.5 0.5 1];
y=horner_recursive(fx,1000,x0)
output:
y =
-0.822466533924111 -0.448414206923646 0.582240526465012 1.643934566681562
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.