2

I noticed a difference in the floating point values represented for Infinity and NAN. Is this specified some where in the standard?

#include <cmath>
#include <iostream>
#include <limits>
#include <stdint.h>

union Double
{
    double value;
    uint64_t repr;
};

int main()
{
    Double d;
    d.value = std::numeric_limits<double>::infinity();
    std::cout << std::hex << "inf: " << d.repr << std::endl;

    d.value = std::numeric_limits<double>::quiet_NaN();
    std::cout << std::hex << "NAN: " << d.repr << std::endl;
    return 0;
}
Ouput: 
inf: 0x7ff0000000000000
NAN: 0x7ff8000000000000
PVRT
  • 480
  • 4
  • 13
  • 2
    The standard doesn't say anything about the representation of floating point numbers; that's an implementation detail. – Mark Ransom Sep 30 '19 at 11:59
  • 2
    First, your code has undefined behavior. Second, why should infinity and not-a-number be the same thing? – L. F. Sep 30 '19 at 12:00
  • 2
    If your implementation uses IEEE754 (and 99% it is), then it's described in IEEE754 standard. [Wikipedia on IEEE754](https://en.wikipedia.org/wiki/IEEE_floating_point) – Yksisarvinen Sep 30 '19 at 12:01
  • It's not specified in the C++ standard. But, assuming your implementation supports IEEE floating point, the representation is specified in IEEE-754 (the IEEE technical standard for floating point). And, with floating point representations that support them, NaN and infinities are distinct things, so have different representations. – Peter Sep 30 '19 at 12:04
  • If there is no upper limit defined in the standard some where then its implementation specific? – PVRT Sep 30 '19 at 12:12

1 Answers1

4

I noticed a difference in the floating point values represented for Infinity and NAN.

Yes, this is not surprising. These values differ, so their representation should differ too.

Is this specified some where in the standard?

In the C++ standard? No.

In some floating-point standard, like IEEE-754? Yes.

Note: in C++, your union trick has undefined behavior. Use memcpy instead.

geza
  • 28,403
  • 6
  • 61
  • 135