Skip to content

Instantly share code, notes, and snippets.

@higham higham/rel_err_formula.m
Last active Aug 6, 2017

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
% Consecutive fl pt numbers but for the 1e4 factor.
y(i) = x(i) + (i-n/2)*d*1e4;
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]
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)])
title('Relative errors in two formulas for the relative error',...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.