0

Can someone explain why the output of the following piece of code is as below?

float x = std::numeric_limits<float>::max();
float y = x - 1.0f;

if(x==y)
    std::cout << "x is equal y!\n";
else 
    std::cout << "x is not equal y!\n";

std::cout << std::fixed << "x: " << x << "\n";
std::cout << std::fixed << "y: " << y << "\n";

On my machine, where the size of a float is 4 bytes, the output looks like this:

x is equal y!
x: 340282346638528859811704183484516925440.000000
y: 340282346638528859811704183484516925440.000000

Thanks in advance:-)

Bobo Feugo
  • 162
  • 1
  • 10
  • See [the Pigeonhole Principle](https://en.wikipedia.org/wiki/Pigeonhole_principle). You have a type with presumably around 4 billion possible values. There's no way it can store every integer up to 340282346638528859811704183484516925440, never mind that there are an infinite number of values between each integer. – chris Oct 10 '21 at 08:54
  • 1
    `std::numeric_limits::max() - 1` isn't representable as a float so you get `std::numeric_limits::max()` as the answer instead as it's the closest representable value to the answer – Alan Birtles Oct 10 '21 at 08:55
  • What you could use instead: [std::nexttoward](https://en.cppreference.com/w/cpp/numeric/math/nextafter): [**Demo on coliru**](http://coliru.stacked-crooked.com/a/f686f2bdf92a8b2f). – Scheff's Cat Oct 10 '21 at 10:13

0 Answers0