📚 Encyclopedia

Science & Math · updated 2026-11-30

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

When a function forces a float

Trig, logs, non-perfect roots and fractional powers go through a double. Two rules hide the damage:

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

Showing the exact answer

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

See also

Sources: calc memory (android-app, scientific-functions, desktop-app), tldr posts #1842, #1915, calc memory (cursor-editing), tldr post #1926