Floating point error when performing division

This is a discussion on Floating point error when performing division within the C Programming forums, part of the General Programming Boards category; Hey, I've been working on some CFD code over the past few months and noticed a strange floating point error ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    11

    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. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    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. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,058
    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.
    Last edited by itCbitC; 06-22-2009 at 11:17 AM.

  4. #4
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    I may be off track here, but here is a good link nonetheless

    Cprogramming.com - Articles - Understanding Floating Point Number Representation

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  2. checking for floating point number
    By ssharish2005 in forum C Programming
    Replies: 6
    Last Post: 10-18-2005, 09:14 PM
  3. Floating point exceptions
    By Boris in forum C++ Programming
    Replies: 8
    Last Post: 11-19-2001, 08:32 AM
  4. Floating point faster than fixed-point
    By VirtualAce in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM
  5. Replies: 2
    Last Post: 09-10-2001, 01:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21