A calculator engine that gets 0.1 + 0.2 and sin(30) right
calculatorfractionsfloating-pointtrigonometryroundingparsingkotlinpython
A calculator that evaluates in binary floating point shows 0.1 + 0.2 = 0.30000000000000004 and sin(180°) = 1.22e-16. The fix is to keep numbers as exact fractions for as long as possible and to be deliberate at the few points where an irrational function forces an approximation. These are the rules a small calculator (one engine in Python for the desktop, the same engine ported to Kotlin for Android) settled on.
Exact where possible
- Every number is a fraction of two big integers. Typed decimals are exact (
0.1is 1/10), and+ − × ÷and whole-number powers never round. Only display rounds: 12 significant digits, switching to scientific notation outside about 1e-6 to 1e15. - Square root of a perfect-square fraction is exact (
√2.25 = 1.5): take integer square roots of numerator and denominator and check they square back. - Factorial is exact, with a size limit (1000!) and its own error for
2.5!or a negative ("Not a whole number"). - Limit by digit count before formatting, and measure it with the integer's bit length. Python refuses to convert an integer of more than 4300 digits to a string by default, so checking the size with
len(str(n))crashes on exactly the numbers the check exists for (7^6000).
When a function forces a float
Trig, logs, non-perfect roots and fractional powers go through a double. Two rules hide the damage:
- Round the result to 15 significant digits before turning it back into a fraction. A double carries 15 to 17, and the last one or two hold the error, so
sin(30°)becomes exactly 0.5. - Reduce the argument exactly first. In degree mode, take the angle mod 360 as a fraction before converting to radians, so
sin(36000030°)is as good assin(30°). - Snap near-zero to zero. A sine or cosine within about 1e-15 times the size of the argument is 0, which gives
sin(π) = 0andcos(90°) = 0. Thentanwhere the cosine snapped to zero is "Undefined", not 1.6e16. - π and e are stored as fractions good to 30 digits, more than any result can show.
Domain errors get distinct messages: "Undefined" (tan 90°, log 0), "Not a real number" (ln of a negative, √ of a negative, asin 2), "Can't divide by zero" (including 0 to a negative power, which is easy to miss when the exponent is fractional). A power too big to hold exactly (e^200) falls back to the rounded double instead of an error.
Syntax decisions
- Implicit multiplication around functions, constants and parentheses:
2π,2sin(30)cos(60),5!2,πe. - Functions are always written with their parenthesis (
sin(), and backspace removes the wholesin(in one press. - A constant named
ecollides with scientific notation. Onceeis Euler's number,1e20is no longer a number the user can type, so a result displayed as1e20cannot be continued from as text. Continue from the expression in parentheses instead, and convert pasted text such as1.5e-7to(1.5×10^−7). - Percent has two reasonable meanings. Binding it to the value just before it gives
2 ÷ 50% = 4; substituting text gives 0.0004. Pick the first. - A function key pressed right after
=applies to the result (25 =then√gives√(25).
Showing the exact answer
- After
=, when the result is a fraction whose decimal never ends (the denominator has a prime factor other than 2 or 5) andnum/denis short (15 characters or fewer), show it as well:1 ÷ 3displays0.333333333333with= 1/3on the preview line. A rounded irrational result never qualifies, because its denominator is a power of 10. - Continue from the exact value, not the displayed text. Re-entering the 12-digit decimal makes
1 ÷ 3 = × 3 =come out as 0.999999999999. Carrying the result forward as(1÷3)gives 1. - Group digits while typing (
1,234,567.8901 × 1,000), but keep the separators out of the stored expression: they exist only in the displayed string, and screen offsets map to expression offsets by counting the characters that are not separators.
A cursor in a keypad calculator
Letting the user tap into the middle of an expression changes every key rule from "look at the end" to "look at the text left of the cursor":
- Keep cursor as an index into the expression; every key edits the left part and re-attaches the right part.
- One decimal point per number has to count digits on both sides of the cursor. A closing parenthesis is allowed only if a group is open at the cursor and the whole expression is unbalanced. An operator typed at position 0 with text after it is ignored (except minus).
- Multi-character tokens are atomic. The cursor never rests inside sin(: a tap snaps to the nearer end, arrow keys step over the whole token, and backspace removes it whole.
- Tapping a result leaves result mode and edits that number; tapping an error returns to the expression.
- A history entry tapped right after an operator or ( is inserted at the cursor (a negative one wrapped in parentheses); anywhere else it replaces the expression.
- On Android with Compose, do not use a text field, which brings the soft keyboard with it. Keep the display as a Text, save its TextLayoutResult, map taps with getOffsetForPosition, and draw a blinking bar at getCursorRect in drawWithContent. Restart the blink on every change so the cursor is solid while typing.
- Give a hardware keyboard the same reach: left, right, Home, End, forward Delete, copy and paste.
Two front ends, one behavior
- Keep the engine free of UI code and keep the keypad logic (what each key does to the expression) as a second pure layer, so both are unit-tested without a screen.
- When the engine exists in two languages, use the same list of test cases on both sides (expression, expected text). Drift shows up as one failing row.
- The Python engine can lean on the
astmodule with an allowlist of node types and names, after rewriting the calculator's symbols to Python (×, postfix!,π). Neverevalthe text. - Android gaps met in the port:
BigInteger.sqrtneeds a newer API level than a low minSdk allows, so write the integer square root by hand; and named regex groups proved unreliable, so use numbered groups.