A4 · Lesson 2 · Integers, floats and rounding error
Why 0.1 + 0.2 isn't 0.3
Type 0.1 + 0.2 == 0.3 into Python and it says False. Nothing is broken. Computers store most numbers in binary with a fixed number of digits, and 0.1 has no exact binary form, just as 1/3 has no exact decimal one. Engineers meet this constantly: a loop that steps time by 0.1 s never lands exactly on 1.0, and two measurements that "should" match never compare equal. Knowing what Python's two kinds of number can and can't hold saves hours of confused debugging.
Predict
What does print(7 // 2, 7 % 2, 7 / 2) show?
3 1 3.5. // divides and rounds down to a whole number, % gives the remainder, and / always gives a float. Together // and % split a count into groups and leftovers: 7 samples into pairs is 3 pairs with 1 left over.
Name it
Two kinds of number
Integers (int) are whole numbers: 7, -3, 2**100. Python integers are exact and have no size limit, so 2**100 prints all 31 digits. Use them for counts, indexes and anything you'll compare exactly.
Floats (float) hold everything else: 3.5, 4.7e3, 1e-12. They're stored in binary with about 16 significant decimal digits and a range up to about . Arithmetic on floats is rounded to those digits after every step.
| Operation | Example | Result |
|---|---|---|
/ divide | 7 / 2 | 3.5 (always a float) |
// floor divide | 7 // 2, -7 // 2 | 3, -4 (rounds down) |
% remainder | 7 % 2, 370 % 360 | 1, 10 |
** power | 2 ** 10 | 1024 |
round(x, n) | round(3.14159, 2) | 3.14 |
int(x) | int(3.9) | 3 (cuts off toward zero) |
% is handy for wrapping: an angle of 370° is 370 % 360 = 10°, and a sample index wraps round a buffer of length N with i % N.
Rounding error
0.1 in binary is , repeating forever, so the stored value is very slightly off. The errors are tiny, around of the value, but they mean:
0.1 + 0.2 # 0.30000000000000004
0.1 + 0.2 == 0.3 # False
Never compare floats with ==. Compare with a tolerance instead:
import math
math.isclose(0.1 + 0.2, 0.3) # True (relative tolerance 1e-9)
abs(a - b) < 1e-12 # or choose your own
Don't step a float to an exact stopping point. Adding 0.1 ten times gives 0.9999999999999999, so while t != 1.0 runs forever. Count steps with an integer and compute the time from it: t = k * dt.
Subtracting nearly equal numbers loses digits. keeps only one or two good digits of the difference. That limits numerical derivatives, as lesson 39 shows.
Worked example
A buffer holds 1000 samples. Sample number 2537 lands in which slot, and how many times has the buffer wrapped?
Show the solution
- Take the remainder and the floor quotient.
%gives the slot and//counts the wraps.
slot = 2537 % 1000 # 537
wraps = 2537 // 1000 # 2
- Check. The two always reassemble the original:
wraps * 1000 + slotis 2537. - Where it's used. Circular buffers in audio and data logging use exactly this.
Answer sample 2537 lands in slot 537, and the buffer has wrapped 2 times.
Worked example
Step time from 0 to 1 s in steps of 0.1 s without drifting.
Show the solution
- See the problem. Adding
t += 0.1ten times ends at 0.9999999999999999. - Use an integer counter instead. Compute each time from the counter.
dt = 0.1
for k in range(11):
t = k * dt
print(round(t, 10))
- Why it works. Each
tis computed fresh fromk, so errors don't pile up, and the loop runs exactly 11 times.
Answer loop an integer k from 0 to 10 and set t = k * dt each time.
Check
Sample number n = 4230 goes into a circular buffer of length N = 16. Set slot to its position (0 to N − 1) and wraps to how many full times the buffer has filled before it.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write wrap(angle) that brings any angle in degrees into the range 0 to 360 (360 itself not included). Then set w to wrap(a) with a = 725.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
The code adds dt = 0.2 to a running total n = 10 times. Set same to whether the total matches n * dt, using math.isclose so that rounding error doesn't count as a difference.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Make a list times of every time from 0 to T = 2 s inclusive in steps of dt = 0.1 s, computing each from an integer counter so the last one is exactly T.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A 12-bit ADC turns a voltage from 0 to Vref = 2.5 V into a whole-number code from 0 to 4095, one step being Vref / 4096. Set lsb to one step in volts, v to the voltage for code c = 513 (c * lsb), and code to the code for x = 0.855 V: the nearest whole step, as an int, clipped to the range 0 to 4095.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
What does round(2.5) give in Python?
Explain why
Why does 0.1 + 0.2 == 0.3 come out False in Python, and what should you write instead?
Floats are stored in binary with a fixed number of digits, and 0.1, 0.2 and 0.3 have no exact binary form, so each is stored very slightly off and the sum rounds to a different last digit than 0.3 does. The difference is around , but == checks for exact equality. Instead, check that the two are close: math.isclose(0.1 + 0.2, 0.3), or abs(a - b) < tolerance with a tolerance suited to the problem.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.