Thread: Floating point error when performing division

  1. #1
    Registered User
    Join Date
    Apr 2009

    Floating point error when performing division

    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?

    #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);
            return 0;

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    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
    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 10:17 AM.

  4. #4
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    I may be off track here, but here is a good link nonetheless - 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, 08: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
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM
  5. Replies: 2
    Last Post: 09-10-2001, 12:00 PM