A42 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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?

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 10308. Arithmetic on floats is rounded to those digits after every step.

OperationExampleResult
/ divide7 / 23.5 (always a float)
// floor divide7 // 2, -7 // 23, -4 (rounds down)
% remainder7 % 2, 370 % 3601, 10
** power2 ** 101024
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 0.000110011001100…, repeating forever, so the stored value is very slightly off. The errors are tiny, around 10−16 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. 1.000001−1.000000 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
  1. Take the remainder and the floor quotient. % gives the slot and // counts the wraps.
slot = 2537 % 1000     # 537
wraps = 2537 // 1000   # 2
  1. Check. The two always reassemble the original: wraps * 1000 + slot is 2537.
  2. 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
  1. See the problem. Adding t += 0.1 ten times ends at 0.9999999999999999.
  2. 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))
  1. Why it works. Each t is computed fresh from k, 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?

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.