Suppose an interviewer asks you to split one dollar among three accounts. Returning 33 cents each loses a cent; returning a repeating decimal postpones the decision. The interesting engineering work starts when you explain who receives the remainder, how a retry behaves, and which invariant survives.
Numerical correctness is useful territory for senior and staff interview preparation because it connects local arithmetic to system behavior. A type choice affects database storage, API contracts, reconciliation, and migrations. This guide uses primary documentation to explain those connections, with illustrative calculations and a proposed practice rubric. The scenarios are exercises, not reports about an employer’s interview process.
1. Choose representations from invariants
Begin with a promise you can test. For a transfer, the debited and credited amounts must agree exactly. For a measurement, the result might need to stay within a stated error bound. For an identifier, preserving every digit matters more than supporting arithmetic. Ask about units, maximum magnitude, fractional resolution, accepted inputs, and whether replay must reproduce earlier outputs.
Define the quantity before its type
For an illustrative usage bill, propose an integer count of requests and a decimal price per request. Keep the price’s scale separate from the final invoice’s currency scale. A price of $0.0025 per request contains information that a two-decimal representation cannot preserve. “Use cents” is incomplete until you explain when fractional cents become a payable amount.
Binary floating point represents values with binary fractions; many decimal fractions, including 0.1, have no finite exact binary representation. The Python floating-point tutorial explains why a short printed decimal can conceal an approximation. This is a representation property, so formatting a value to two places does not repair arithmetic already performed on it.
Choose a bounded integer with an explicit scale for exact discrete quantities; consider decimal arithmetic for decimal business rules; use binary floating point when approximation suits the domain. These are design choices, not universal rankings. PostgreSQL’s numeric-type documentation distinguishes exact numeric from inexact floating types and documents their range and precision. Verify the actual database type rather than assuming application and storage types share semantics.
Write a compact contract aloud: “Amounts arrive as decimal strings, include a currency, have bounded precision, and cannot be non-finite. We preserve calculation precision until the specified posting boundary.” Add a failure response for violations. This gives later decisions a purpose and prevents “more precision” from becoming an unbounded input or resource policy.
Challenge that contract with one deliberately awkward input: a request count of “12.5.” Should the parser reject it, convert it, or change the unit? For this exercise, reject it because requests are discrete. Next try a negative count representing a correction. Decide whether corrections share the same field or use a separate operation. These questions show whether your representation preserves the meaning of the quantity, beyond merely accepting a string that a number parser understands.
2. Make rounding a product decision
A decimal type still needs a rounding policy. Specify the target scale, tie-breaking mode, rounding boundary, and treatment of negative adjustments. Python’s decimal documentation exposes precision, rounding modes, signals, and quantize(). It also shows that constructing a decimal from a binary float preserves that float’s value; parse an original decimal string when the string is authoritative.
Work through a half-cent
Here is an exact decimal exercise. Three separate items each incur a $0.005 fee. Under nearest rounding with ties away from zero, rounding each fee to cents gives $0.01 + $0.01 + $0.01 = $0.03. Adding first gives $0.015, which rounds to $0.02. Under ties-to-even, the individual fees become $0.00 while the total still becomes $0.02. Neither a decimal library nor a database can choose which business contract you intended.
Make the assumption explicit: “For this exercise, fees are summed before invoice-level rounding, with ties-to-even at two decimal places.” Then ask how refunds work. Reversing a recorded posting can preserve its exact amount; recalculating from today’s rates or policy may produce something different. Propose recording the inputs and policy version needed for the required audit or replay behavior.
Cross-layer agreement needs verification. PostgreSQL 17 documents numeric tie rounding away from zero, while its floating types usually round ties to even. A database default can therefore disagree with an application’s chosen decimal context. Put the explicit rule in the contract and verify positive and negative ties through the complete write-and-read path.
Allocate remainders deterministically
Return to the dollar split. In integer cents, 100 divided by 3 gives quotient 33 and remainder 1. An illustrative allocation is 34, 33, and 33 cents, assigning leftover cents by a stable account ordering. The sum is exactly 100. Define whether repeated allocations should rotate the beneficiary for fairness, and persist that decision if retries must reproduce it. Conservation and fairness are separate requirements.
3. Check overflow and transport boundaries
Exact integers are exact only within their supported range. Establish a bound for every intermediate expression, including multiplication before division. In an illustrative signed 64-bit calculation, let a nonnegative amount be 1,000,000,000,000,000 minor units and a rate be 10,000 basis points. Their product is 10,000,000,000,000,000,000, above the signed 64-bit maximum of 9,223,372,036,854,775,807, even though dividing the mathematical product by 10,000 returns the original amount.
Widening the destination after multiplication cannot recover lost information. Use a sufficiently wide intermediate, arbitrary precision with bounds, or an algebraic transformation whose rounding behavior you prove. For nonnegative bounded operands, a multiplication precondition is b == 0 or a <= MAX / b. Signed operands need additional cases; do not present that guard as a complete signed-arithmetic implementation.
Language behavior is part of the explanation. The Go specification permits signed integer overflow and says it does not cause a runtime panic. Java’s Math.multiplyExact instead offers an operation that throws when the product overflows. State which operation your design uses and how the service handles its failure.
Follow one value into the browser
A valid database integer can lose its identity during JSON consumption. RFC 8259 identifies integers between −(253−1) and 253−1 as exactly interoperable with commonly used binary64 implementations. JSON syntax itself does not impose that maximum; the receiving implementation matters.
The ECMAScript specification illustrates the problem: 9007199254740992 and 9007199254740993 evaluate to the same Number value. Propose decimal strings for large identifiers or exact amounts, with a documented grammar and explicit consumer parsing. Test producer, serializer, client, and subsequent submission together. Converting an already rounded number to a string cannot restore its original digits.
4. Budget approximation and aggregation error
For approximate measurements, define what agreement means rather than choosing an arbitrary epsilon. Python’s math.isclose documentation combines relative and absolute tolerance with this comparison:
abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
As an illustrative requirement, choose rel_tol = 0.000001 and abs_tol = 0.000000001. Values 1,000,000 and 1,000,000.5 differ by 0.5 and pass because the relative allowance is about 1. Near zero, 0 and 0.0000000005 pass because the absolute allowance dominates. These are worked examples, not recommended defaults. Derive tolerances from measurement resolution and acceptable downstream harm.
Define non-finite handling before applying the comparison. Python documents that NaN is not close to anything, including itself, and infinities are close only to themselves. For an API expecting finite sensor readings, propose rejecting non-finite inputs. Avoid approximate equality for identifiers, ledger conservation, or deciding whether an exact credit limit has been exceeded.
Aggregation order becomes a system decision
In binary64 round-to-nearest, consider (1e16 + 1.0) - 1e16: the intermediate addition loses the unit, yielding 0. Reordering as (1e16 - 1e16) + 1.0 yields 1. The mathematical inputs are unchanged. Goldberg’s floating-point arithmetic paper explains rounding error and compensated summation, including Kahan’s algorithm.
That example gives you a concrete follow-up: what happens when worker counts or partition boundaries change the reduction order? If exact reproducibility is required, propose a defined reduction strategy and execution assumptions, then verify them. If bounded error is sufficient, compare candidate summation methods against a higher-precision reference on adversarial inputs. Compensated summation can reduce error; it does not make every floating-point calculation exact or guarantee identical results under arbitrary regrouping.
5. Test, migrate, and rehearse the contract
Build tests around the invariant you started with. Include zero, negative adjustments, maximum supported values, values immediately around rounding ties, excessive precision, and invalid encodings. For approximate arithmetic, add cancellation and mixed-magnitude cases. For transport, include both sides of the consumer’s safe-integer boundary. These cases should exercise production parsing and storage, not only an isolated arithmetic helper.
Distinguish a calculation test from a workflow test. For the dollar allocation, a calculation test checks that the outputs sum to 100 cents. A workflow test submits the same operation identifier twice and checks that the chosen allocation is posted once. Then simulate failure after calculation but before the response reaches the caller. Decide which durable record lets the retry recover the original outcome. This proposed exercise connects numerical conservation to the system that owns it.
Property-based testing can explore combinations beyond a handwritten list. The Hypothesis introduction describes generating inputs from declared strategies. Useful proposed properties include allocation totals equaling the original amount, parse/serialize round trips preserving accepted values, and exact reversals cancelling recorded postings. State each property’s preconditions; floating addition is not generally associative.
Treat a representation change as a contract migration
For an illustrative float-to-decimal migration, inventory readers and writers before converting rows. Decide whether historical source strings or recorded postings are authoritative. A cast from stored float to decimal cannot recreate decimal information that was discarded earlier. Separate preservation of historical outcomes from correcting future calculations, and agree on any reconciliation policy before changing balances.
Propose shadow calculations using the new policy, compare differences by magnitude and cause, and review boundary cases before switching authoritative writes. Version the API encoding and calculation rule when compatibility requires it. Define rollback around a durable source of truth: switching code back is insufficient if newly written values cannot be represented by the old format. These are migration design recommendations, not a claim that one deployment sequence fits every system.
Make the comparison report specific. In an illustrative shadow run, one account changes by +1 cent and another by −1 cent. The net difference is zero, but two customers have different outcomes. Report affected records and absolute differences alongside signed totals, and separate expected policy changes from unexplained discrepancies. Define the acceptable result before reviewing the report; a small global total should not silently become permission to alter individual postings.
A proposed mock-interview rubric
Use a 20-minute practice session: spend four minutes stating invariants and bounds, six working the fee and overflow examples, five tracing storage and JSON, and five defending testing and migration. Score each of the following from zero to two: absent, asserted, or demonstrated with a concrete counterexample:
- Contract: units, range, scale, and permitted error are explicit.
- Arithmetic: rounding boundaries and intermediate overflow are handled.
- Interfaces: serialization preserves the consumer’s required meaning.
- Operations: tests, reconciliation, replay, and rollback support the contract.
This eight-point rubric is a preparation aid, not a hiring prediction. A useful answer makes correctness observable: show the cent that would disappear, the multiplication that exceeds its range, and the identifier that changes in transit. Then explain the policy and evidence that prevent each failure. Carry that habit into your next mock interview and ask your practice partner to challenge one boundary you have not yet defended.
Sources & References
- Python: Floating-Point Arithmetic, Issues and Limitations — Binary fractions and decimal representation.
- PostgreSQL 17: Numeric Types — Exactness, ranges, precision, and rounding ties.
- Python: Decimal Arithmetic — Construction, contexts, rounding modes, and quantization.
- Go Language Specification: Integer Overflow — Defined integer overflow behavior.
- Java SE 25: Math.multiplyExact — Checked multiplication.
- IETF RFC 8259, Section 6: Numbers — JSON precision and interoperability.
- ECMAScript: Number.MAX_SAFE_INTEGER — Safe integer limits and indistinguishable values.
- Python: math.isclose — Tolerances and non-finite comparisons.
- David Goldberg: What Every Computer Scientist Should Know About Floating-Point Arithmetic — Rounding and compensated summation.
- Hypothesis: Introduction — Generated tests from input strategies.