Why Programmers Need Math

Table of Contents

  1. The Math You Already Use
  2. Five Bugs That Are Really Math Bugs
  3. What You Need, and What You Can Skip
  4. How This Series Is Organized
  5. Set Up Node.js
  6. Create the mathlab Folder
  7. Your First Module and Demo
  8. How to Read the Code in This Series
  9. Recipe: Check That mathlab Works
  10. Try It Yourself

1. The Math You Already Use

Ask a programmer whether they use math at work and many will say "not really". Then watch what they do in a normal week:

  • Show 10 items per page, so they work out how many pages 101 items need.
  • Change a hex color like #1e90ff into red, green, and blue numbers.
  • Store a user's permissions as one number instead of twelve columns.
  • Make a carousel go from the last slide back to the first.
  • Add up prices and wonder why the total is off by a tiny amount.
  • Decide whether a search that is fast on 100 rows will survive 1,000,000.

Every item on that list is math. It is just not the math from the blackboard, with long proofs and strange Greek letters. It is smaller, more practical, and it directly decides whether your program is right.

This series teaches that practical math. We will use words, tables, and code, and we will skip proofs completely. When you finish, "that is just a modulo problem" or "that is a set operation" will be a thought you actually have, and it will save you time.

2. Five Bugs That Are Really Math Bugs

Here are five short programs. Each one looks fine and each one is wrong. You do not need to understand them yet. Each is fixed in a later chapter.

Bug 1: the price that is not quite a price.

console.log(0.1 + 0.2);    // 0.30000000000000004
console.log(19.99 * 100);   // 1998.9999999999998

Computers store decimal fractions like 0.1 in binary, and some of them cannot be stored exactly. If you use floating-point numbers for money, you will eventually lose a cent. Chapters 2 and 7 explain why and what to do instead.

Bug 2: the carousel that goes backwards into nothing.

const slides = ["a", "b", "c"];
let current = 0;
current = (current - 1) % slides.length; // go to the previous slide
console.log(current);          // -1
console.log(slides[current]);  // undefined

In JavaScript, % can return a negative number. The "previous" button on the first slide shows an empty page. Chapter 6 fixes it.

Bug 3: the page that does not exist.

const items = 101;
const perPage = 10;
console.log(Math.floor(items / perPage)); // 10
console.log(Math.ceil(items / perPage));  // 11

With Math.floor, the 101st item has no page. Rounding up or down is a decision, not a detail. Chapter 10 uses this for pageCount.

Bug 4: the ID that changes by itself.

console.log(9007199254740993); // 9007199254740992

You typed one number and JavaScript printed a different one. Numbers beyond 9007199254740991 lose exactness. Big database IDs sent as JSON numbers can silently change. Chapter 7 covers this and BigInt.

Bug 5: the feature that was fast on your laptop. A page that compares every item with every other item does 100 x 100 = 10,000 steps for 100 items, but 1,000,000 x 1,000,000 = 1,000,000,000,000 for a million. The code did not change. The growth did. Chapters 8 and 9 teach you to see that coming.

Notice the pattern: none of these needed calculus. They needed you to know how numbers are stored, how remainders behave, how to round, and how quantities grow.

3. What You Need, and What You Can Skip

Here is the honest split.

TopicNeeded for everyday programming?Where in this series
Binary and hexYes: colors, IDs, permissions, debuggingChapter 2
Bitwise operationsYes: flags, networking, file permissionsChapter 3
Boolean logicYes: every if you writeChapter 4
SetsYes: tags, roles, deduplication, diffsChapter 5
ModuloYes: wrapping, schedules, checksumsChapter 6
Integer limits, floatsYes: money, IDsChapter 7
Powers and logarithmsYes: scaling, search, storageChapters 8 and 9
CountingYes: passwords, test cases, paginationChapter 10
ProbabilityYes: random, A/B tests, collisionsChapter 11
CoordinatesYes: UI, canvas, animationChapter 12
Calculus, matrices, proofsNot for most web or app workSkipped here

Vectors, matrices, and calculus matter a great deal for machine learning and graphics, so they get their own place in the planned Math for AI series. You can build a career in web, mobile, or backend work and rarely touch them. You cannot do it without the topics in the table above.

You also do not need to be "good at math". If you can add, subtract, multiply, divide, and read a table, you have enough. Everything else is introduced when it is needed, and every symbol is explained.

4. How This Series Is Organized

There are 12 chapters in two halves.

Half one: how computers represent and combine values (chapters 1 to 7).

  1. Why Programmers Need Math (this chapter)
  2. Numbers and Number Systems
  3. Bitwise Operations and Flags
  4. Boolean Logic
  5. Sets and Set Operations
  6. Modular Arithmetic
  7. Integers, Overflow and Precision

Half two: how code scales and how to reason about chance (chapters 8 to 12).

  1. Functions, Growth and Logarithms
  2. Big-O Notation
  3. Counting: Permutations and Combinations
  4. Probability Basics
  5. Coordinates, Geometry and Putting It Together

Every chapter has the same shape. It explains an idea with small examples, then ends with a Recipe that adds one module to a project called mathlab, and finally a Try It Yourself list of exercises. Do the recipe in every chapter. Reading about math is easy to forget; writing the function that uses it is not.

5. Set Up Node.js

All the code in this series runs in Node.js, which lets you run JavaScript in the terminal. If you followed JavaScript & TypeScript Fundamentals, you may already have it. Check:

node --version

You should see a version number such as v22.12.0. Any current LTS (long-term support) version works. If you see "command not found", download the LTS installer from nodejs.org and run it, then open a new terminal and check again.

If any terminal command in this chapter feels unfamiliar, Command Line Basics covers cd, mkdir, and the rest.

6. Create the mathlab Folder

Pick a place for your projects, then create the folder structure:

mkdir mathlab
cd mathlab
mkdir src

Inside mathlab/, create a file called package.json with this content:

{
  "name": "mathlab",
  "version": "1.0.0",
  "type": "module"
}

The line "type": "module" tells Node that .js files in this folder use import and export (ES modules) instead of the older require. It matters: without it, Node refuses to run our files.

When we finish this chapter the folder looks like this:

mathlab/
  package.json
  demo.js          <- we run this to try things
  src/
    index.js       <- re-exports every module

The idea: each chapter adds one file inside src/ (for example src/numbers.js in chapter 2). src/index.js collects them so that demo.js can import everything from one place. There is nothing to install and no dependencies. You never run npm install in this series.

7. Your First Module and Demo

Create src/index.js:

// Every module we write is re-exported from here.
export const version = "0.1.0";

Right now it exports a single constant. In later chapters you will add lines such as export * from "./numbers.js";, which means "re-export everything that file exports".

Next, create demo.js in the root of mathlab/:

import { version } from "./src/index.js";

console.log(`mathlab v${version}`);
console.log("7 % 2 =", 7 % 2);
console.log("0.1 + 0.2 =", 0.1 + 0.2);
console.log("2 ** 10 =", 2 ** 10);

Run it from inside the mathlab folder:

node demo.js

Expected output:

mathlab v0.1.0
7 % 2 = 1
0.1 + 0.2 = 0.30000000000000004
2 ** 10 = 1024

Two things to notice. First, the import path is "./src/index.js": with ES modules you must write the ./ and the .js extension. Second, there it is again: 0.1 + 0.2 printing 0.30000000000000004. By the end of the next chapter you will know exactly why.

8. How to Read the Code in This Series

A few conventions keep the code easy to follow.

  • Code blocks tagged js are JavaScript. Blocks tagged bash are commands for your terminal.
  • A comment at the end of a line, such as // 1024, shows what the line prints or produces. Run the code yourself and compare.
  • Functions have plain names such as toBinary and hasFlag. The names are shared between chapters, so later chapters can use earlier modules.
  • When an exercise says "extend the demo", add lines to demo.js. Keep the old lines. A growing demo is a free regression test.

If your output differs from the comment, do not move on yet. Check typos and the import path first. Most mistakes at this stage are a missing .js or running the command from the wrong folder.

9. Recipe: Check That mathlab Works

This recipe finishes the project skeleton. Confirm each item:

  1. mathlab/package.json exists and contains "type": "module".
  2. mathlab/src/index.js exports version.
  3. node demo.js, run from the mathlab folder, prints four lines.
  4. In the demo, change "2 ** 10 =" to "2 ** 16 =" and the expression to match. You should see 65536.

If you see SyntaxError: Cannot use import statement outside a module, your package.json is missing "type": "module" or you are running Node from a different folder. If you see ERR_MODULE_NOT_FOUND, check the spelling and the .js in the import path.

You now have an empty toolkit. In the next chapter we add the first real module.

10. Try It Yourself

  1. Spot the math. Look at a small project you wrote before. Find three places where you used a remainder, a rounding function, a comparison of numbers, or a number that grows with input size. Write each one down.
  2. Predict, then run. Without running it, guess what console.log(10 % 3, -10 % 3, 10 % -3) prints. Run it. Which result surprised you? (Chapter 6 explains it.)
  3. Round three ways. Print Math.floor, Math.ceil, and Math.round of 7 / 2 and of -7 / 2. Which one would you use for the number of pages? For "how many full boxes can I fill"?
  4. Add a line. Add console.log("Cambodia riel per dollar:", 4100) to demo.js, then print the price of a $2.50 coffee in riel using 2.5 * 4100. Is the answer exactly what you expected?
  5. Break it on purpose. Remove "type": "module" from package.json and run node demo.js. Read the error message, then put the line back. Knowing what this error looks like will save you time later.

With the skeleton ready, the next chapter starts from the very bottom: Numbers and Number Systems shows how computers write numbers in binary and hex, and finally explains why 0.1 + 0.2 is not 0.3.

Buy Me a Coffee

Found this tutorial helpful? Consider buying me a coffee to support more free content!