Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is 1.0 / 3.0 not an undefined operation in C++? (not representable in float)

The C++ standard says:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

and

The binary / operator yields the quotient from the division of the first expression by the second. If the quotient a/b is representable in the type of the result [snip]; otherwise, the behavior of a/b is undefined.

If I have:

double x = 1.0 / 3.0;

The result of the division of 1 by 3 is the real number "one third". One third is not representable in the type of the result (double, usually the IEEE754 double-precision binary64 floating point type).

Does that mean that the above statement is an undefined operation? Surely it cannot be - but I don't understand how it isn't?

like image 526
Andrew Tomazos Avatar asked Sep 17 '25 12:09

Andrew Tomazos


1 Answers

The word "range" here refers to being in between the lowest and highest representable value. It's not the mathematical term as in "domain" and "range".

Real values can be out of range of a floating-point type due to being too large (far away from zero) or too small (nonzero values too close to zero).

Floating point types are inexact; that is in their nature. Some calculations produce a value which is an approximation to the exact real value. If such calculations produced garbage results or exceptions, floating-point would not meet its purpose.

like image 135
Kaz Avatar answered Sep 19 '25 03:09

Kaz