Counting up forever in int and float
Question
A loop adds 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 . A 32-bit signed int overflows after (formally undefined behaviour, in practice wrapping to ), giving a sawtooth. A single-precision float has a 24-bit significand, so at adding 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