%
% basics: floating numbers and machine roundoff
%
format long e
% some Matlab variables
%
pi % pi = 3.141592653589793e+000
eps % eps = 2.220446049250313e-016
%
realmax % realmax = 1.797693134862316e+308
realmin % realmin = 2.225073858507201e-308
%
2^-52 % 2^-52 = 2.220446049250313e-016
%
(1+2^-52)-1 % (1+2^-52)-1 = 2.220446049250313e-016
(1+2^-53)-1 % (1+2^-53)-1 = 0
% The machine epsilon is the distance from
% 1 to the next larger float
%----------------------------------------------------
a = 1;
b = 1;
while a+b ~= a
b = b/2;
end
b % b = 1.110223024625157e-016
% shows that a+b = a is satisfied by numbers not 0
%----------------------------------------------------
a = 1.0e+308
b = 1.1e+308
c =-1.001e+308
a+(b+c) % 1.099000000000000e+308
(a+b)+c % Inf
% commutativity not true
%----------------------------------------------------
% loss of precision via cancellation
x = 1.e-15;
((1+x)-1)/x % 1.110223024625157e+000
% relative error: 11%
%----------------------------------------------------
% an example for loss of precision
y = linspace(0,400,401) % to understand "linspace"
x = linspace(1-2*10^-8,1+2*10^-8,401);
f = x.^7-7*x.^6+21*x.^5-35*x.^4+35*x.^3-21*x.^2+7*x-1;
plot(x,f)
%alternatively
g = -1+x.*(7+x.*(-21+x.*(35+x.*(-35+x.*(21+x.*(-7+x))))));
plot(x,g)
h = (x-1).^7;
plot(x,h,x,g,x,f)
%-----------------------------------------------------
% another example
z(1) = 0; z(2) = 2;
for k = 2:29
z(k+1) = 2^(k-1/2)*(1-(1-4^(1-k)*z(k)^2)^(1/2))^(1/2);
end
semilogy(1:30,abs(z-pi)/pi)
%-----------------------------------------------------
% complex numbers
z = 3 + i*4;
zbar = conj(z)
real(z)
imag(z)
abs(z)
angle(z)
x = -1; y = x^(1/3)
compass(y,'r')
%-----------------------------------------------------