comparing numbers(floats)

This is a discussion on comparing numbers(floats) within the C Programming forums, part of the General Programming Boards category; HI all I need a piece of code that will compare 3 numbers of type floating point and then list ...

  1. #1
    Unregistered
    Guest

    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
    Posts
    523
    Comparing floats is a dodgy business as any difference no matter how small will effect your comparison, example:
    Code:
    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
    Unregistered
    Guest
    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, 11:13 AM
  2. bit vs bytes when comparing a file
    By Overworked_PhD in forum C Programming
    Replies: 6
    Last Post: 05-20-2007, 12:22 AM
  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

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