# Thread: Floating point error when performing division

1. ## Floating point error when performing division

Hey,
I've been working on some CFD code over the past few months and noticed a strange floating point error occuring when performing a division. For some reason I'm getting a difference between the values 'a' and 'b' in the following code. Does anyone know why this is happening?
Cheers,
Kieran

Code:
#include <stdio.h>

/* This function is to illustrate the difference between dividing by a number
and multiplying by 1/number  */

int main() {
double num,a,b,div;

div = 0.9;
num = 0.0000000000003;

a = num/div;
b = num*(1.0/div);

printf("%e\n",a-b);

return 0;
}

2. If you work it out even in decimal, you should see what happens: 9e-1 / 3e-12 is 3e11, while 1/3e-12 is 3.333e11, multiplied by 9e-1 gives 2.9997e11. The reciprocal will get rounded off before the multiply. (You could probably work out what IEEE says each of the answers should be, but I'm not that motivated.)

3. Part of the problem lies in the selection of those two numbers. Decimal div (=0.9) and num (=3e-13) in binary are recurring fractions. Hence the difference in the output is because of the rounding-off or truncation depending upon the fp implementation.

4. I may be off track here, but here is a good link nonetheless

Cprogramming.com - Articles - Understanding Floating Point Number Representation