%------------------------------------------------------------- % % For A321 course % %------------------------------------------------------------- % % Randall Bramley % Department of Computer Science % Indiana University, Bloomington % bramley somewhere at cs dot indiana dot (allegedly) edu % % Started: Mon 04 Feb 2008, 09:05 AM % Last Modified: Mon 16 Feb 2009, 03:46 PM % echo on; %------------------------------------------------------------- % % This shows some effects of floating point arithmetic. % The two expressions below are equal in exact arithmetic, % but not in floating point. % % Moral of this m-file: never test for equality between % floating point numbers. Instead use "less than or % equal to" <= or greater than or equal to >=, etc. % % Second moral: addition is not associative and commutative % on computers. The only difference below is the order in % which the numbers are added. % %------------------------------------------------------------- should_be_true = ( (-0.08 + 0.5 - 0.42) == (0.5 - 0.42 - 0.08)) offby = abs( (-0.08 + 0.5 - 0.42) - (0.5 - 0.42 - 0.08)); echo off; if (should_be_true) disp('Woo whoo! Computation was exact.'); else disp('Bummer, floating point inequality here.'); disp(['The two expressions are off by ' num2str(offby) ]); disp(['This should be roughly the size of eps = ' num2str(eps) ]); end