Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEEE 754 floating point, what is the largest number < 1?

Tags:

c++

When using IEEE 754 floating point representation (double type in c++), numbers that are very close to (representable) integers are rounded to their closest integer and represented exactly. Is that true?
Exactly how close does a number have to be to the nearest representable integer before it is rounded?
Is this distance constant?
For example, given that 1 can be represented exactly, what is the largest double less than 1?

like image 902
user1971455 Avatar asked Feb 10 '23 04:02

user1971455


2 Answers

When using IEEE 754 floating point representation (double type in c++), numbers that are very close to (representable) integers are rounded to their closest integer and represented exactly.

This depends upon whether the number is closer to the integer than to other values representable. 0.99999999999999994 is not equal to 1, but 0.99999999999999995 is.

Is this distance constant?

No, it becomes less with larger magnitudes - in particular with larger exponents in the representation. Larger exponents imply larger intervals to be covered by the mantissa, which in turn implies less precision overall.

For example, what is the largest double less than 1?

std::nexttoward(1.0, 0.0). E.g. 0.999999999999999889 on Coliru.

like image 164
Columbo Avatar answered Feb 11 '23 18:02

Columbo


You will find much more definitive statements regarding the opposite direction from 1.0 The difference between 1.0 and the next larger number is documented here:

std::numeric_limits<double>::epsilon()

The way floating point works, the next smaller number should be exactly half as far away from 1.0 as the next larger number.

like image 32
JSF Avatar answered Feb 11 '23 17:02

JSF