---
title: Integers, floats and rounding error
heading: Why 0.1 + 0.2 isn't 0.3
eyebrow: A4 · Lesson 2 · Integers, floats and rounding error
xp: 40
---

::: hook
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.5 1 3.5`
- [x] `3 1 3.5`
- [ ] `3 3 3.5`
- [ ] `4 1 3.5`

::: reveal
`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.
:::
:::

::: nameit
## 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 $10^{308}$. 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 $0.000110011001100\ldots$, 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.
:::

::: example
## A buffer holds 1000 samples. Sample number 2537 lands in which slot, and how many times has the buffer wrapped?

::: solution
1. **Take the remainder and the floor quotient.** `%` gives the slot and `//` counts the wraps.

```
slot = 2537 % 1000     # 537
wraps = 2537 // 1000   # 2
```

2. **Check.** The two always reassemble the original: `wraps * 1000 + slot` is 2537.
3. **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.
:::
:::

::: example
## Step time from 0 to 1 s in steps of 0.1 s without drifting.

::: 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))
```

3. **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
kind: python
given: n = 1000..9999 int; N = 16 | 64 | 256

## Sample number `n` = {n} goes into a circular buffer of length `N` = {N}. Set `slot` to its position (0 to N − 1) and `wraps` to how many full times the buffer has filled before it.

```python starter
slot = 0
wraps = 0
print(slot, wraps)
```

```python solution
slot = n % N
wraps = n // N
print(slot, wraps)
```

```python tests
assert isinstance(slot, int) and isinstance(wraps, int), "Use integer operations, // and %, so both come out as whole numbers."
assert wraps * N + slot == n, "wraps * N + slot should give back n. Use n // N and n % N."
assert 0 <= slot < N, "slot must be between 0 and N − 1."
```

::: right
Right. `//` and `%` split a count into whole groups and what's left over.
:::
:::

::: check
kind: python
given: a = 370 | 725 | -30 | -400 | 1090

## 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` = {a}.

```python starter
def wrap(angle):
    return angle

w = wrap(a)
print(w)
```

```python solution
def wrap(angle):
    return angle % 360

w = wrap(a)
print(w)
```

```python tests
assert wrap(370) == 10, "wrap(370) should be 10."
assert wrap(-30) == 330, "wrap(-30) should be 330: Python's % always gives a result with the sign of the divisor."
assert wrap(720) == 0, "wrap(720) should be 0."
assert w == a % 360, "w doesn't match for this lab's angle."
```

::: right
Right. Python's `%` gives a result between 0 and the divisor even for negative numbers, which is exactly what wrapping needs.
:::
:::

::: check
kind: python
given: dt = 0.1 | 0.2 | 0.7 | 0.01; n = 10 | 20 | 100

## The code adds `dt` = {dt} to a running total `n` = {n} times. Set `same` to whether the total matches `n * dt`, using `math.isclose` so that rounding error doesn't count as a difference.

```python starter
import math
total = 0.0
for _ in range(n):
    total += dt
same = (total == n * dt)
print(total, n * dt, same)
```

```python solution
import math
total = 0.0
for _ in range(n):
    total += dt
same = math.isclose(total, n * dt)
print(total, n * dt, same)
```

```python tests
assert same is True, "Print the two numbers: they differ only in the last few digits. Compare with math.isclose, not ==."
```

::: right
Right. The running total picks up a little rounding at every step, so it lands a hair away from `n * dt`. A tolerance treats them as the same number they are.
:::
:::

::: check
kind: python
given: T = 1 | 2 | 5; dt = 0.1 | 0.01 | 0.05

## Make a list `times` of every time from 0 to `T` = {T} s inclusive in steps of `dt` = {dt} s, computing each from an integer counter so the last one is exactly `T`.

```python starter
times = []
t = 0.0
while t <= T:
    times.append(t)
    t += dt
print(len(times), times[-1])
```

```python solution
n = round(T / dt)
times = [k * dt for k in range(n + 1)]
print(len(times), times[-1])
```

```python tests
n = round(T / dt)
assert len(times) == n + 1, f"There should be {n + 1} times, from 0 to T inclusive. Adding dt repeatedly can skip the last one."
assert times[-1] == T, "The last time should be exactly T. Adding dt over and over drifts; compute each time as k * dt."
assert abs(times[1] - dt) < 1e-15, "The second time should be dt."
```

::: right
Right. Counting with an integer and multiplying never drifts, and the number of steps is exact.
:::
:::

::: check
kind: python
given: Vref = 3.3 | 2.5 | 5.0; c = 100..4000 int; x = 0.1..2.4 sig 3

## A 12-bit ADC turns a voltage from 0 to `Vref` = {Vref} 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` = {c} (`c * lsb`), and `code` to the code for `x` = {x} V: the nearest whole step, as an `int`, clipped to the range 0 to 4095.

```python starter
lsb = Vref / 4095
v = c * lsb
code = x / lsb
print(lsb, v, code)
```

```python solution
lsb = Vref / 4096
v = c * lsb
code = int(round(x / lsb))
code = max(0, min(4095, code))
print(lsb, v, code)
```

```python tests
step = Vref / 4096
assert abs(lsb - step) < 1e-15, "One step is Vref / 4096: 12 bits give 4096 codes."
assert abs(v - c * step) < 1e-12, "v should be c * lsb."
want = max(0, min(4095, int(round(x / step))))
assert isinstance(code, int), "code should be an int: use int(round(...))."
assert code == want, f"For {x} V the nearest code is {want}."
```

::: right
Right. One step of a {Vref} V, 12-bit converter is about {Vref}/4096 V, and rounding to the nearest step instead of truncating keeps the error within half a step.
:::
:::

::: check
kind: choice

## What does `round(2.5)` give in Python?

- [x] `2`
- [ ] `3`
- [ ] `2.0`
- [ ] `3.0`

::: right
Right. Python rounds a value exactly halfway between two integers to the even one, so `round(2.5)` is 2 and `round(3.5)` is 4. Rounding halves to even keeps a long sum of rounded values from drifting upward, and `round` with one argument returns an `int`.
:::

::: misses
- [2] That's the school rule, halves up. Python rounds halves to the even neighbor, which is 2 here.
- [3] `round` with one argument returns an `int`, and Python rounds exact halves to the even neighbor.
- [4] `round` with one argument returns an `int`, and it rounds exact halves to the even neighbor, 2.
:::
:::

::: explain
## Why does `0.1 + 0.2 == 0.3` come out `False` in Python, and what should you write instead?

::: model
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 $10^{-17}$, 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

::: check
kind: python
given: s = 3600..86399 int

## A clock counts `s` = {s} seconds since midnight. Set `h`, `m` and `sec` to the hours, minutes and seconds.

```python starter
h = m = sec = 0
print(h, m, sec)
```

```python solution
h = s // 3600
m = (s % 3600) // 60
sec = s % 60
print(h, m, sec)
```

```python tests
assert h * 3600 + m * 60 + sec == s, "h, m and sec should add back to s seconds."
assert 0 <= m < 60 and 0 <= sec < 60, "Minutes and seconds should each be under 60."
```
:::

::: check
kind: python
given: v = 3.14159 | 2.71828 | 1.41421; n = 1 | 2 | 3

## Set `r` to `v` = {v} rounded to `n` = {n} decimal places.

```python starter
r = v
print(r)
```

```python solution
r = round(v, n)
print(r)
```

```python tests
assert abs(r - round(v, n)) < 1e-12, "Use round(v, n)."
assert r != v, "r should be rounded."
```
:::

::: check
kind: python
given: a = 5 | 9 | 14; b = 2 | 4

## Set `q` to `a // b` and `f` to `a / b`, with `a` = {a} and `b` = {b}, and set `diff` to `f - q`.

```python starter
q = f = diff = 0
print(q, f, diff)
```

```python solution
q = a // b
f = a / b
diff = f - q
print(q, f, diff)
```

```python tests
assert q == a // b and isinstance(q, int), "q should be the floor division, a whole number."
assert abs(f - a / b) < 1e-12, "f should be the ordinary division."
assert abs(diff - (a % b) / b) < 1e-12, "diff should be f − q, the fractional part."
```
:::
:::
