Skip to content

Instantly share code, notes, and snippets.

# higham/rel_err_formula.m

Last active August 6, 2017 13:23
Show Gist options
• Save higham/6f2ce1cdde0aae83697bca8577d22a6e to your computer and use it in GitHub Desktop.
MATLAB script to compare two formulas for relative error.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 %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')
to join this conversation on GitHub. Already have an account? Sign in to comment