Docsity

MATH 128A, Summer 2009: Programming Assignment 1 Solutions, Assignments of Mathematical Methods for Numerical Analysis and Optimization

Toggle sidebar
bg1
MATH 128A, SUMMER 2009: PROGRAMMING ASSIGNMENT 1: SOLUTIONS
1. In the file divided_difference.m:
function y=divided_difference(f, xi)
n=length(xi);
if length(xi) == 1
y = f(xi(1));
else
y = (divided_difference(f,xi(2:n)) - divided_difference(f,xi(1:n-1))) / ...
(xi(n) - xi(1));
end
The ellipsis (“. . . ”) above tells MATLAB that the formula continues on the next line.
2. In the command window:
>> format long
>> xi = linspace(0, 10, 6);
>> for k=1:6
ai(k) = divided_difference(@cos, xi(1:k));
end
>> actual = cos([pi/3 pi/2 pi]);
>> approx = newton_eval([pi/3 pi/2 pi], ai, xi)
approx =
0.694083092853490 0.067661126195064 -1.003526514017955
>> abserr = abs(actual - approx)
abserr =
0.194083092853490 0.067661126195064 0.003526514017955
The command “format long” tells MATLAB to print more decimal digits than the default number
(5). The last two calculations were printed because they weren’t followed by semicolons.
3. >> xdata = linspace(0, 10);
>> ydata1 = newton_eval(xdata, ai, xi);
>> ydata2 = cos(xdata);
>> plot(xdata, ydata1, xdata, ydata2)
These commands produce figure 1 when run in MATLAB and figure 2 when run in Octave. (The
figure can be saved to disk using a command like “print -dpdf pa1graph”.)
Date: Due Monday 7/20.
1
pf2

Partial preview of the text

Download MATH 128A, Summer 2009: Programming Assignment 1 Solutions and more Assignments Mathematical Methods for Numerical Analysis and Optimization in PDF only on Docsity!

MATH 128A, SUMMER 2009: PROGRAMMING ASSIGNMENT 1: SOLUTIONS

  1. In the file divided_difference.m: function y=divided_difference(f, xi) n=length(xi); if length(xi) == 1 y = f(xi(1)); else y = (divided_difference(f,xi(2:n)) - divided_difference(f,xi(1:n-1))) / ... (xi(n) - xi(1)); end The ellipsis (“... ”) above tells MATLAB that the formula continues on the next line.
  2. In the command window:

    format long xi = linspace(0, 10, 6); for k=1: ai(k) = divided_difference(@cos, xi(1:k)); end actual = cos([pi/3 pi/2 pi]); approx = newton_eval([pi/3 pi/2 pi], ai, xi)

approx =

0.694083092853490 0.067661126195064 -1.

abserr = abs(actual - approx)

abserr =

0.194083092853490 0.067661126195064 0. The command “format long” tells MATLAB to print more decimal digits than the default number (5). The last two calculations were printed because they weren’t followed by semicolons.

  1. xdata = linspace(0, 10); ydata1 = newton_eval(xdata, ai, xi); ydata2 = cos(xdata); plot(xdata, ydata1, xdata, ydata2) These commands produce figure 1 when run in MATLAB and figure 2 when run in Octave. (The figure can be saved to disk using a command like “print -dpdf pa1graph”.)

Date: Due Monday 7/20. 1

Figure 1. Graph from problem 3 (MATLAB)

Figure 2. Graph from problem 3 (Octave)

-1.

-0.

0

1

0 2 4 6 8 10 2