Numbers and Math
Integers, floats, division, rounding, remainders, and how agents count steps, tokens, and cost without lying.
Agents count. They count steps, tokens, and cost. Get the math wrong, and the loop runs until the bill arrives. Python’s everyday math is small. You need it to be automatic.
A token is a chunk of text the model reads or writes. Think of it as a piece of a word. We count tokens because they cost money. This lesson does not tokenize for real. It teaches the arithmetic you run after you have counts.
Python has two everyday number types. An int is a whole number. A float is a number with a decimal point. Use int for counters. Use float for prices. For exact money, you can also count cents as whole numbers and divide by 100 only when you print.
The math operators
| Op | Meaning | Example |
|---|---|---|
+ - * | Add, subtract, multiply | 3 * 4 is 12 |
/ | Divide, always a float | 7 / 2 is 3.5 |
// | Divide, drop the leftover fraction | 7 // 2 is 3 |
% | Remainder | 7 % 2 is 1 |
** | Power | 2 ** 10 is 1024 |
/ on two whole numbers still gives a float. 10 / 2 is 5.0, not 5. If you want a whole number of batches, use //.
% is what is left. 7 % 2 is 1 because 2 fits into 7 three times, with 1 left. window = 512 and prompt_tokens % window is leftover tokens after filling full windows.
multiplies a number by itself. 2 10 is 2 times itself, 10 times. 10 3 is 1000. Useful for “per thousand tokens” as tokens / 10 3, though writing / 1000 is clearer.
Parentheses change order. prompt_tokens / 1000 * price multiplies after dividing. Write the formula so it matches the comment next to it. If you cannot read it, neither can the next reviewer.
round and int
round(x) goes to the nearest whole number. round(x, 4) keeps 4 digits after the dot. round(2.5) in Python 3 goes to the even choice in the halfway case. Do not use halfway cases for money demos. Round to 4 digits for logs.
int(x) cuts off the extra part toward zero. int(3.9) is 3. That is not rounding. int(3.1) is also 3.
min and max pick the smallest and largest values. abs(-3) drops the sign and gives 3. sum([1, 2, 3]) adds a list of numbers. sum needs a list (or similar), not loose arguments: sum([1200, 350]) works; sum(1200, 350) does not.
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(2 ** 10)
print(round(3.9), int(3.9))
print(min(1200, 350, 800), max(1200, 350, 800))Count tokens and cost
A simple cost line looks like this:
prompt_tokens = 1200
completion_tokens = 350
price_in = 0.005
price_out = 0.015
cost = prompt_tokens / 1000 * price_in + completion_tokens / 1000 * price_out
print(round(cost, 4))Keep token counts as int until you multiply by a price. Then you have dollars. Round for the log. Do not store cost as text. If you str(cost) too early, you cannot add the next call’s cost without converting back.
You pay for both. Cost is tokens times price. Count as ints. Round dollars for the log.
Tokens in, tokens outPrices are usually “dollars per 1K tokens.” That is why we divide by 1000. If a vendor prices per million, divide by 1_000_000. Underscores in numbers are allowed in Python: 1_000_000 is a million. They are only for reading.
Floats are not exact
0.1 + 0.2 is not exactly 0.3. Binary floats cannot hold some decimals. Do not compare money with ==. Round for display, or count cents as whole numbers: cents = 15 then print dollars as cents / 100.
Step counts and list lengths are ints. Prices are floats. Mixing them with == is a classic demo bug. step == 3.0 may be True, but cost == 0.3 after addition may be False. Compare costs with a round, or compare ints.
step += 1 means step = step + 1. budget -= 1 subtracts. cost += line_cost accumulates. You are moving the name to a new number, not changing the old number.
Division by zero raises ZeroDivisionError. A price of 0 is legal. A window size of 0 is not if you // by it. Guard those.
A budget line you can copy
Keep four numbers in an agent: step, max_steps, tokens, cost. Update them in one place at the end of a turn:
step = 0
max_steps = 8
tokens = 0
cost = 0.0
class="tok-c"># one turn:
step += 1
tokens += 1200 + 350
cost += 1200 / 1000 * 0.005 + 350 / 1000 * 0.015
print(class="tok-s">"step", step, class="tok-s">"of", max_steps)
print(class="tok-s">"tokens", tokens, class="tok-s">"cost", round(cost, 4))
print(class="tok-s">"stop?", step >= max_steps or cost > 0.05)The last print is the policy. Change the threshold in one place. Do not hide a second stop rule inside a tool. If two places both decide to stop, you will not know which one fired. Numbers are the policy’s inputs. if is the policy. This lesson is the inputs.
Negative costs mean you subtracted in the wrong order. abs is not a fix for that. Print the prompt tokens and the completion tokens separately until the formula looks like the vendor’s docs.
Common mistakes
- Using
/where you needed//(or the other way around). - Treating
int(3.9)as round. - Comparing floats with
==. - Forgetting parentheses in a cost formula.
- Storing
costas a string, then trying to add it. - Using
sum(1, 2, 3)instead ofsum([1, 2, 3]).
Run to execute this in your browser. Nothing is sent to a server.
Change prompt_tokens to 2000 and watch cost and window counts move together. The same numbers feed the bill and the chunking.
How agents use this
A real loop has a budget: max steps, max tokens, or max dollars. Keep step as a whole number. Multiply tokens by a price to get cost, then round for the log. Stop when step is too high or cost is too high. That math is what protects your wallet.
Each turn should add the new tokens to a running int, add the new dollars to a running float, then print both. If you only print the last call’s cost, you will miss the sum. If you never cap max_steps, a confused model will spend the whole key.
Integer division also shows up in batching: how many full chunks of 512 characters, how many leftover characters. Off-by-one in // and % drops a tail of a document. Print full and leftover when you split text. The numbers lesson is the chunking lesson’s arithmetic.
Do not let the model invent the budget math. Your Python should compute cost from counts you measured. The model can propose a tool. It should not keep the ledger.
Check your understanding