davidhigh
davidhigh

Reputation: 15528

Is the inverse of std::numeric_limits::infinity() zero?

Is there anything in the C++ standard (or the IEEE 754 floating-point standard) that guarantees that 1./std::numeric_limits<double>::infinity() is zero (or at least a small number)?

Upvotes: 21

Views: 1911

Answers (4)

Gonen I
Gonen I

Reputation: 6127

Yes, according to the GNU C library reference manual (assuming IEEE 754):

Infinities propagate through calculations as one would expect: for example, 2 + ∞ = ∞, 4/∞ = 0

https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html

You may want to check if your C++ compiler uses IEEE 754:

How to check if C++ compiler uses IEEE 754 floating point standard

Upvotes: 11

John Zwinck
John Zwinck

Reputation: 249652

Any finite number divided by infinity results in zero under IEEE 754 (and therefore the same in most typical C++ implementations).

If the sign of the of numerator and denominator differ, the result will be negative zero, which is equal to zero.

Upvotes: 14

Eric Postpischil
Eric Postpischil

Reputation: 224596

IEEE 754-2008 6.1 says:

The behavior of infinity in floating-point arithmetic is derived from the limiting cases of real arithmetic with operands of arbitrarily large magnitude, when such a limit exists. Infinities shall be interpreted in the affine sense, that is: −∞ < {every finite number} < +∞.

Operations on infinite operands are usually exact and therefore signal no exceptions,…

Since the limit of 1/x as x increases without bound is zero, a consequence of this clause is that 1/∞ is zero.

Clause 6.3 tells us the sign of the result is +:

When neither the inputs nor result are NaN, the sign of a product or quotient is the exclusive OR of the operands’ signs;…

Upvotes: 4

Damon
Damon

Reputation: 70206

if(std::numeric_limits<double>::is_iec559) yes(); else no();

(see 18.3.2.4)

IEC 559, which is identical with IEEE 754, guarantees that to be the case. However, C++ does not guarantee in any way that IEC 559 is in place (although 99.99% of the time that's just what happens to be the case, you still need to verify to be sure).

Upvotes: 2

Related Questions