Android’s calculator evaluating 10^(100)+1−10^(99)−9×10^(99) and showing the result 1

A while ago I saw this post from Digiato making fun of Apple’s calculator for not being able to get a simple calculation like

10^100+1-10^100

right: it outputs 0, while Android’s calculator handles it with ease and outputs 1.

Unfortunately, many years of academic training meant that instead of forwarding the post to my Apple-using friends and bullying them, I got hung up on how Android’s calculator pulls this off and manages to get the right answer! Because at first glance, I would have expected 0 too, not 1!

So that friends without a computer background can follow what’s going on (if you’re familiar with IEEE 754, feel free to skip this part!): in the world of computers nothing is infinite, so numbers get capped somewhere too. For example, the variables we work with in a computer are usually 64 bits at most, which means a single variable can represent at most 2^64 different numbers. That’s a really big number, but on the scale of 10^100, the 100-digit number from the example above, this guy only has 20 digits! In other words, you can’t represent more than 10^20 different numbers with 64 bits; or, put another way, if you start counting from 0, once you reach 10^20 you can’t represent the next number!

That’s why a standard called IEEE 754 was introduced, and its whole mindset is: in exchange for giving up precision, let’s cover a bigger range of numbers.

For example, you can think of it like this: if my number system only had multiples of 10, then 11 and 12 might be no different to me and I’d see both of them as 10 (loss of precision), but in exchange I could represent numbers up to 10^21, which is a bigger range. Of course, the main goal of IEEE 754 is to store numbers with a fractional part, and to store them in a way that makes the four basic operations on them easy. In 64 bits it can cover fractional numbers in the range -1e308 to +1e308, which is roughly 300 digits! But, as I said, it has a precision problem: for example, adding 0.1 and 0.2 in IEEE 754 gives you 0.30000000000000004! Why? Because we had to lower our precision, and we can’t tell 0.3 and 0.30000000000000004 apart.

Something similar is happening with Apple’s calculator. When it adds 1 to 10^100, because of that error it can’t tell the result apart from plain old 10^100, so when you then subtract 10^100, it shows 0 instead of 1!

How Android gets it right#

Now that we know what the problem is, it’s time to get to the solution. When I brought this up with the shadowy figures pulling the strings at the department, a little crow told me there’s a thread on Twitter that talks about this at an abstract level but doesn’t really get into the details, and we all know the devil is in the details!

Google’s main solution for the calculator code was to go get Mr. Boehm, who had previously worked on the Boehm garbage collector and had managed to solve the garbage collection problem for C++, and sit him down in front of the calculator code! (Talk about overkill.) 😂

Boehm describes his approach to the problem in this paper and this paper, and after N papers he finally got to write the calculator code!

And now, Boehm’s solution.

Boehm’s take on the problem was that we’re dealing with mathematical expressions, and unlike usual, where an approximation of a number is good enough and processing speed is what matters, this time precision is what matters and speed isn’t all that important. So, specifically, what we care about is knowing whether two numbers are exactly equal or not. In fact, in the cases where error makes two different numbers look identical, we want to know whether their difference is 0 or just tends to 0.

For integers this is relatively easy. We just use big ints instead of int. A big int is implemented by giving you one int per digit: instead of being a single variable, your number is an array of variables where each cell holds one digit. In this setup the four basic operations take a bit longer, but in a world where we can do 100 million operations in under a second, you barely feel the slowdown. This approach alone easily solves the example we started with.

use num_bigint::BigInt;
type Num = BigInt;

Unfortunately, though, the real numbers are a much bigger deal than that.

The next step is supporting rational numbers (fractions). The solution here is simple too: instead of each number being one big int, each number becomes two big ints, one for the numerator and one for the denominator, and then we do our four basic operations on fractions. This does have a problem, though, which Boehm points out in his paper: when you want to compute a/b + c/d, you get (bd)/(ad+bc), and if you don’t simplify the fraction (or it can’t be simplified), you’re effectively building arrays for ad, bc and bd that are twice as long as a, b, c and d. That means that with every addition, subtraction, multiplication or division, the amount of data you’re dealing with doubles, which isn’t scalable at all.

pub(crate) struct Num {
    // numinator holds the sign.
    numinator: BigInt,
    denuminator: BigUint,
}

On top of that, we still don’t support irrational numbers! The next solution is to look at every number as the root of a polynomial equation. For example, 2 is the root of x-2, and the square root of 2 is the root of x*x-2 when x is positive. As you can see, high school math finally paid off! (happy high school teacher noises!) But this representation has its own problems. For example, adding two numbers gives you a new equation whose root is the sum of the roots of the two equations, and multiplying two numbers turns into substituting one equation into the other!

struct Num {
    factors: Vec<i32>,
}

But there’s still a set of important numbers we can’t represent. For example, we have no way of representing pi, e, ln, sin and so on, which are useful values and probably count as part of a calculator’s use case.

To handle these, we define a concept called recursive real numbers: numbers for which, given an error value err, you can guarantee there’s a function f(err) whose output differs from the actual number by less than err. In other words, you can approximate these numbers to any precision you like with some sequence, or, to put it one last way, you can compute as many of their digits as you want.

The advantage of storing numbers this way over the previous approaches is that it’s lazy. That is, you don’t need to compute the value and allocate memory for it until the very last moment; knowing the function is enough! This saves you from all the error values that would otherwise pile up while evaluating a long mathematical expression; you just lazily chain functions together. The downside is that we’re back to square one! I can now compute pi-pi to the Nth digit, but I can’t be sure whether pi-pi is exactly 0 or just tends to 0! In other words, if a number isn’t zero, I know that somewhere in these recursive computations it will diverge from zero, the function will halt, and I’ll find out; but if the number really is 0, the function keeps going forever and never halts.

struct Num {
    recursive_real: fn(err: f64) -> f64,
}

impl Num {
    fn pi() -> Self {
        fn pi_estimator(err: f64) -> f64 {
            let mut sum = 0.0_f64;
            let mut term = 1.0_f64;
            let mut i = 0;
            while term > err {
                term = 1.0 / (2 * i + 1) as f64;
                sum += if i % 2 == 0 { term } else { term.neg() };
                i += 1;
            }
            sum * 4.0
        }
        Self {
            recursive_real: pi_estimator,
        }
    }
}

It’s easy to show that this problem is undecidable! To prove it, just map the number to a Turing machine program such that the i-th digit after the point (in base 2) is 1 if and only if our machine has definitely halted after i steps. If you could solve this, you’d have solved halting, so that’s a no-go!

From theory to engineering#

This is where we leave the world of theory and enter the world of engineering, and the innovations get beautiful! With math tying his hands at this point, Boehm is forced to shrink the set of numbers and operators he works with down to a subset in which this problem is decidable. Boehm realizes that, for operations, the four basic operations plus square root are enough, and for numbers, pi, e, sin, cos, asin, acos and ln, and that if he can make the problem decidable for this system, that’s good enough.

A long time ago, at the University of Bath in England (yes, Bath!), Richardson et al. proved in this paper that the problem really is decidable, unless the number is one of the counterexamples to Schanuel’s conjecture. And since nobody has ever heard anything about this conjecture or its counterexamples… we are good!

Richardson et al. even give an algorithm for answering the question in their paper, but unfortunately, even though the algorithm terminates, it isn’t practical: in cases like e^(-1000), it needs more steps than there are atoms in the universe to finish. (Boehm really loved this line! It’s in his paper and in his code comments!)

So here, another neat idea comes into play! Let’s go over the problem and the solutions one more time:

  1. Representing numbers as fractions gives us exact numbers, but doesn’t cover every number (e.g. pi, e, …).
  2. Recursive reals represent every number to whatever precision we want, but they aren’t exact, and you can’t necessarily compare any two of them.

So the solution is to use a combination of both! This is where Boehm comes in with the following structure:

struct Num {
    rational: Rational,
    real: Real,
}

pub(crate) struct Rational {
    numinator: BigInt,
    denuminator: BigUint,
}

pub(crate) enum Real {
    One,
    SQRT(Rational),
    Pi,
    Sin(Rational),
    .
    .
    .
    Other(Rational),
}

In this structure, every number is the product of a rational number and a real number. For integers, for example, we use Real::One, which is effectively a placeholder saying “this number is entirely rational”. This representation has some nice properties. For example, we now know that 2pi-pi-pi is exactly 0, because during the computation, when the real parts are equal we only touch the rational parts, and in the end we get 0*pi, which is exactly 0. Or when we want to display cos(pi), we know this number is exactly 0, so we don’t show an approximate 0. For the cases where there’s nothing more we can do, like e+pi, we use the last variant (Other), and that’s the only place where we’re effectively saying: from here on, all my computations are going to be approximate and I can’t give you an exact answer.

You can find the code for the library they wrote for their paper here.

And finally, all I can say is: pain and misery! That moment when you realize your entire programming skill set is only good enough for Apple, and nobody better will hire you!