Thread: comparing numbers(floats)

  1. #1

    Question comparing numbers(floats)

    HI all

    I need a piece of code that will compare 3 numbers of type floating point and then list them in some order eg largest num first then second largest etc. (order dont matter really).

    thanx ppl

  2. #2
    Registered User C_Coder's Avatar
    Join Date
    Oct 2001
    Comparing floats is a dodgy business as any difference no matter how small will effect your comparison, example:
    if( num1 == num2 )
        // do stuff
    Say at this point in your program you expect that num1 should be 25.5 and num2 should also be 25.5. But if num1 is actually 25.50001 then the test for comparison will fail.
    Last edited by C_Coder; 03-30-2002 at 03:32 AM.
    All spelling mistakes, syntatical errors and stupid comments are intentional.

  3. #3
    Why dont you define some error of size, say 1e-4. Then just see if the difference between them is less than the error.

    float error = 1e-4;

    if(abs(num1 - num2) < error)
    // do stuff...

    If you're working with floats in the first place, there is going to be round off errors anyway...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-29-2009, 10:13 AM
  2. bit vs bytes when comparing a file
    By Overworked_PhD in forum C Programming
    Replies: 6
    Last Post: 05-19-2007, 11:22 PM
  3. comparing bitmaps
    By bigSteve in forum C++ Programming
    Replies: 1
    Last Post: 11-08-2002, 10:40 AM
  4. comparing problem
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 03-05-2002, 06:19 AM
  5. comparing struct members
    By breed in forum C Programming
    Replies: 4
    Last Post: 11-22-2001, 12:27 PM