Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C IEEE-Floats inf equal inf

In C, on a implementation with IEEE-754 floats, when I compare two floating point numbers which are NaN, it return 0 or "false". But why do two floating point numbers which both are inf count as equal?

This Program prints "equal: ..." (at least under Linux AMD64 with gcc) and in my opinion it should print "different: ...".

#include <stdio.h>
#include <stdlib.h>

int main(void)
  {
    volatile double a = 1e200; //use volatile to suppress compiler warnings
    volatile double b = 3e200;
    volatile double c = 1e200;
    double resA = a * c;  //resA and resB should by inf
    double resB = b * c;
    if (resA == resB)
      {   
        printf("equal: %e * %e = %e = %e = %e * %e\n",a,c,resA,resB,b,c);
      }   
    else
      {   
        printf("different: %e * %e = %e != %e = %e * %e\n", a, c, resA, resB, b, c);
      }   
    return EXIT_SUCCESS;
  }

A other example, why I think inf is not the same as inf, is: the numbers of natural numbers and rational numbers, both are infinite but not the same.

So why is inf == inf?

like image 854
12431234123412341234123 Avatar asked Dec 05 '25 06:12

12431234123412341234123


2 Answers

Infinities compare equal because that's what the standard says. From section 5.11 Details of comparison predicates:

Infinite operands of the same sign shall compare equal.

like image 72
nwellnhof Avatar answered Dec 07 '25 20:12

nwellnhof


inf==inf for the same reason that almost all floating point numbers compare equal to themselves: Because they're equal. They contain the same sign, exponent, and mantissa.

You might be thinking of how NaN != NaN. But that's a relatively unimportant consequence of a much more important invariant: NaN != x for any x. As the name implies, NaN is not any number at all, and hence cannot compare equal to anything, because the comparison in question is a numeric one (hence why -0 == +0).

It would certainly make some amount of sense to have inf compare unequal to other infs, since in a mathematical context they're almost certainly unequal. But keep in mind that floating point equality is not the same thing as absolute mathematical equality; 0.1f * 10.0f != 1.0f, and 1e100f + 1.0f == 1e100f. Just as floating point numbers gradually underflow into denormals without compromising as-good-as-possible equality, so they overflow into infinity without compromising as-good-as-possible equality.

If you want inf != inf, you can emulate it: 1e400 == 3e400 evaluates to true, but 1e400 - 3e400 == 0 evaluates to false, because the result of +inf + -inf is NaN. (Arguably you could say it should evaluate to 0, but that would serve nobody's interest.)

like image 31
Sneftel Avatar answered Dec 07 '25 20:12

Sneftel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!