Overflow and Round-Off Errors

Part of: Data

Limited Bits, Limited Numbers Real computers store numbers in a fixed number of bits . That limit creates two classic problems on the AP exam: overflow and round-off errors. Both happen because the true value cannot fit in the available space. Overflow Errors An overflow error occurs when a calculation produces a number too large for the allotted bits. Imagine a system that stores values in 4 bits, so the largest value it can hold is 1111 = 15. If you compute 15 + 1, the result 16 needs a fifth bit that does not exist. The number may "wrap around" to 0 or produce a wrong value. We can simulate a fixed-width counter using the modulo operator, which keeps only the bits that fit: With bits = 4, start = 15, add = 1, the result wraps to 0 instead of 16. That wraparound is overflow. Round-Off Errors A round-off error happens when a value cannot be represented exactly, so the computer stores the closest value it can. This is common with fractions in floating-point numbers. For example, 0.1 + 0.2 in Python prints 0.30000000000000004 because 0.1 and 0.2 have no exact binary representation. Key points: - Overflow comes from numbers that are too big for the bits available. - Round-off comes f

Challenge: Fixed-Width Counter