Difference between revisions of "Numerical Errors"

From SourceWiki
Jump to navigation Jump to search
Line 8: Line 8:
 
=I didn't expect that!=
 
=I didn't expect that!=
  
Let's take a look at our first example.
+
Let's dive into our first example:
  
 
<pre>
 
<pre>
 
svn co http://source.ggy.bris.ac.uk/subversion-open/numerics/trunk ./numerics
 
svn co http://source.ggy.bris.ac.uk/subversion-open/numerics/trunk ./numerics
 
cd numerics/examples/example1
 
cd numerics/examples/example1
 +
make
 
</pre>
 
</pre>
  
 +
There are two programs in this directory, one written in C, the other in Fortran.  Let's run the C program first:
  
 +
<pre>
 +
./surprising_c.exe
 +
</pre>
 +
 +
This program does some very simple arithmetic and yet we start to see odd things happening already!  For example the trigonometric function '''tan''' can give us hugely different values depending upon whether we give it a single precision- (typically stored using 4 bytes) or a double precision- (8 byte) number.  To be fair \tan(\pi/2) (radians) is undefined, and so it's hard to say what the right output should be.  However, is does highlight that you need to be vigilant when using floating-point numbers and not to expect that your program's behaviour will always be benign.
  
 
=Algorithms Matter=
 
=Algorithms Matter=
  
 
=Deterministic, yes.  Outputs, different=
 
=Deterministic, yes.  Outputs, different=

Revision as of 15:13, 10 November 2008

Unexpected things can happen when you use floating point numbers!

Introduction

Sooner or later, you're going to want to include real--aka floating point--numbers in your programs. These could be for measured quantities, or parameterisations. One thing's for sure, however, integers don't always cut it. Now this is all fine and as it should be. A word of warning, however. Programs containing floating point numbers can do very odd things indeed! Use them with care.

I didn't expect that!

Let's dive into our first example:

svn co http://source.ggy.bris.ac.uk/subversion-open/numerics/trunk ./numerics
cd numerics/examples/example1
make

There are two programs in this directory, one written in C, the other in Fortran. Let's run the C program first:

./surprising_c.exe

This program does some very simple arithmetic and yet we start to see odd things happening already! For example the trigonometric function tan can give us hugely different values depending upon whether we give it a single precision- (typically stored using 4 bytes) or a double precision- (8 byte) number. To be fair \tan(\pi/2) (radians) is undefined, and so it's hard to say what the right output should be. However, is does highlight that you need to be vigilant when using floating-point numbers and not to expect that your program's behaviour will always be benign.

Algorithms Matter

Deterministic, yes. Outputs, different