%% Evaluating Polynomials and Subtractive Cancellation % % Script: Zoom4 % Plots (x-1)^6 near x=1 with smaller and smaller scale. % The evaluation is done two ways: one is expanded out, the % uses the form above. The expanded form leads to severe % subtractive cancellation error. %% Expanded form of polynomomial % Evaluate the following form and zoom in to see what it does. % % $$ y = x^6 - 6x^5 + 15x^4 - 20x^3 + 15x^2 - 6x +1 $$ % close all k=0; n=100; for delta = [.1 .01 .008 .007 .005 .003 ] x = linspace(1-delta,1+delta,n)'; y = x.^6 - 6*x.^5 + 15*x.^4 - 20*x.^3 + 15*x.^2 - 6*x + ones(n,1); k = k+1; subplot(2,3,k) plot(x,y,x,zeros(1,n)) axis([1-delta 1+delta -max(abs(y)) max(abs(y))]) end %% % The function is very jagged and noisy looking at when we zoom in. % This is clearly not what is expected of a polynomial when evaluated % exactly! % %% Compact form of polynomial % Now use % % $$ y = (x-1)^6 $$ % %% % and see what the zoomed in plots show. % k=0; figure; for delta = [.1 .01 .008 .007 .005 .003 ] x = linspace(1-delta,1+delta,n)'; y = (x-ones(n,1)).^6 ; k = k+1; subplot(2,3,k) plot(x,y,x,zeros(1,n)) axis([1-delta 1+delta -max(abs(y)) max(abs(y))]) end %% % Much better now! We avoided the subtractions that appear in the expanded % form, and the function performs much better! %