Skip to content

Counting up forever in int and float

Question

A loop adds 11 to a variable over and over and you plot the value against the iteration count. Describe the plot when the variable is an int, and when it is a float.

Short answer

The int climbs linearly then wraps to a large negative value; the float climbs then flattens at 2242^{24}. A 32-bit signed int overflows after 231−12^{31}-1 (formally undefined behaviour, in practice wrapping to −231-2^{31}), giving a sawtooth. A single-precision float has a 24-bit significand, so at 16,777,21616{,}777{,}216 adding 11 rounds back to the same number and the line goes flat.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.18, p.227; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question