Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
MATLAB script to compare two formulas for relative error.
%REL_ERR_FORMULA Compare two formulas for relative error.
n = 500;
a = 3;
x = a*ones(n,1,'single');
y = zeros(size(x));
d = eps(single(a));
for i=1:n
i-n/2
% Consecutive fl pt numbers but for the 1e4 factor.
y(i) = x(i) + (i-n/2)*d*1e4;
end
format hex
[x y]
format short e
e1 = double(abs( (x-y)./x )); % Standard formula.
e2 = double(abs( 1-y./x )); % Alternative formula.
exact = abs( (double(x)-double(y))./double(x) );
err1 = abs( (e1-exact)./exact);
err2 = abs( (e2-exact)./exact);
[y exact e1 e2 err1 err2]
subplot(211)
semilogy(y,[err2,err1],'.','MarkerSize',10)
ylim([5e-9 max(err2)])
xlim([min(y), max(y)])
set(gca,'ytick',[1e-8 1e-7 1e-6 1e-5 1e-4 1])
set(gca,'xtick',[min(y) 3 max(y)])
grid
title('Relative errors in two formulas for the relative error',...
'FontWeight','normal')
legend({'$|1-y/x|$','$|x-y|/|x|$'},'Interpreter','latex',...
'location','northeast')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment