%% Loss of Significance %% % This script demonstrates loss of significant digits and how to fix it for % the specific example of evaluation of % % $$ f(x) = \sqrt{x^2+1}-1 $$ %% % Number of trials N = 5; %% Result using double-precision disp('Result using double precision') for n=0:N x = 10^(-n); f = sqrt(x^2+1)-1; disp(sprintf('x=%f, sqrt(x^2+1)-1 = %e',x,f)) end %% Using single-precision % Here is where we see the problems pause disp('Result using single precision') for n=0:N x = 10^(-n); f = single(sqrt(x^2+1))-1; disp(sprintf('x=%f, sqrt(x^2+1)-1 = %e',x,f)) end %% Using single-precision, but fixed pause disp('Result using single precision, but fixed') for n=0:N x = 10^(-n); f = single(x^2)/(single(sqrt(x^2+1))+1); disp(sprintf('x=%f, x^2/(sqrt(x^2+1)+1) = %e',x,f)) end