echo on
%%%%% ch01_exa.m %%%%%
% Run script and study the effects of each line.

echo off
disp(sprintf('**** Examples from Chapter 01 ****'));
disp(sprintf('**** Example 1.6 Backward Error Analysis *'));
%%%% shows the meaning of forward and backward errors
echo on
x=1
c=cos(x)		% exact value of cos(x) to seven decimal places
ec = 1 - x^2/(1*2) 	% approximate value for cos(x) obtained by 
			%the truncated Taylor series cos(x)=1-x^2/(1*2)+x^4/(1*2*3*4)-...
xb = acos(ec)		% find the input with arccos, that would give ec with exact algorithm
fe = ec-c		% forward error - the difference between exact and approximate values
			% accuracy is fairly good because the output is close 
			% to what we want to compute.
be = xb-x		% backward error - the difference between exact and perturbed inputs
			% accuracy is fairly good because the output is correct
			% for an input that is only slightly perturbed.
			% for greater values of x accuracy becomes worse, we should take more
			% factors from the truncated Taylor series.
            
echo off
disp(sprintf('**** Example 1.8 Sensitivity *'));
echo on
format long
pi_long=pi/2		% calculate pi/2 for reference	
format short
x1=1.57079;		% two values near pi/2
x2=1.57078;
c1=tan(x1)		% tangent function
c2=tan(x2)
rc=(c2-c1)/c1		% relative change in solution
rx=(x2-x1)/x1		% relative change in input
cond1=rc/rx		% condition number is large -> the problem is sensitive
			% or ill-conditioned for x=1.57079
            
echo off
disp(sprintf('**** Example 1.10 Rounding Rules *'));
echo on
x=14.9		
fix(x)		% round towards zero resulting in integer
fix(-x)
round(x)	% round to nearest integer
round(-x)
ceil(x)		% round to the nearest integer greater than or equal to x
ceil(-x)
floor(x)	% round to the nearest integer less than or equal to x
floor(-x)


echo off
disp(sprintf('**** Example 1.11 Floating Point Arithmetic *'));
echo on
format long
x=1.92403*10^2	% consider a floating-point system p=6
y=6.35782*10^-1		
s=x+y		% addition in full resolution
format short	% rounded to seven digits: two of digits of y have no effect
s=x+y 	
format long
p=x*y		% multiplication in full resolution
format short	% rounded to seven digits: half of digits discarded
p=x*y

eps		% returns the distance from 1.0 to the next largest flp number. 
realmin		% returns the smallest normalised flp number of a particular computer. 
		% Anything smaller underflows or is an IEEE "denormal."  
realmax		% returns the largest flp number representable on a particular computer. 
		% Anything larger overflows. 
      
1/0		% Inf = Infinity 
      
0/0		% NaN = Not a Number
		% Some experiments
realmax+100
realmax*2
realmax*realmin
realmax/realmin
realmin/realmax

            
echo on
