Is a whole number float divided by itself guaranteed to be 1.f?

C++Floating Point

C++ Problem Overview


If I write:

int x = /* any non-zero integer value */;
float y = x;
float z = y / y;

Is z guaranteed to be exactly 1.f ?

C++ Solutions


Solution 1 - C++

If your C++ implementation uses IEEE754 then yes, this is guaranteed. (The division operator is required to return the best possible floating point value).

The only exceptions for y / y, in general, not being 1.f are the cases when y is NaN, +Inf, -Inf, 0.f, and -0.f, or if you are on a platform where int is so wide that certain instances of it cannot be represented in a float without that float being set to +Inf or -Inf1. Setting aside that final point, in your case that means that int x = 0; will produce the only exception.

IEEE754 is extremely common. But to check for sure, test the value of

std::numeric_limits<float>::is_iec559;


1A platform, for example, with a 128 bit int and an IEEE754 32 bit float would exhibit this behaviour for certain values of x.

Solution 2 - C++

No, not in all cases, even for IEEE754.

For example, with int x = 0;, you'll get NaN. (Live)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionj bView Question on Stackoverflow
Solution 1 - C++BathshebaView Answer on Stackoverflow
Solution 2 - C++Baum mit AugenView Answer on Stackoverflow