1 post tagged


Computers are very bad at math

Let's say you are creating an online store where customers can deposit money to increase their balance and then use the balance to buy things. You choose a time-tested and powerful language like C++.

Read the short code below and see if it makes sense:

// when a customer registers, set their balance to zero
float balance = 0.0; // in dollars

// customer deposited $12.20
balance += 12.2;

// customer is trying to buy something for $12.20,
// so you want to check if they have enough money for a purchase
if (balance >= 12.2) {
    // give the item to the customer
} else {
   // return a "not enough money" error

So this looks very simple. But this will actually throw a “not enough money” error. Because according to a computer

0.0 + 12.2 = 12.19999981

And there is nothing magical about number 12.2. Computer struggles with floating point arithmetic because there are many many numbers that can't be represented with a finite number of binary digits. If you are not careful, this will inevitably lead to errors that are really hard to debug.

In this case it is easily avoidable if you use integer and store balance in cents rather than in dollars, because any integer can be exactly represented in binary.

2017   C++