Recovering Original Ratios from Floating-Point Metering Data: Reverse-Engineering Rational Numbers
This article explains why floating-point outputs in metering systems can reveal the fractions behind them. It covers the IEEE 754 binary64 representation error, continued fraction and Stern-Brocot methods for recovering the original fraction, and how to validate the results. It also offers design guidance on rounding, precision layers, and access control for metering interfaces.
1. Background: Where Long Decimal Tails Come From
Many metering systems store and return usage, cost, or ratio values as floating-point numbers. When the underlying value is a rational number, such as 1/3 or 7/11, a computer can only represent it with a finite number of binary digits. The decimal output often shows a long run of repeating digits or trailing noise.
This behavior is not a defect. It is a normal result of floating-point arithmetic. However, it leaves a clue. If a value was produced by dividing two integers, its decimal expansion contains information about the numerator and denominator. Recovering that clue makes it possible to reconstruct the original fraction.
This article covers this general technical problem. It applies to any data you are authorized to analyze, such as metrics from your own systems, results from test environments, or public mathematical samples.
2. Floating-Point Representation and Error
Most current systems use the double-precision floating-point format (binary64) defined by IEEE 754. It stores a value in 64 bits and provides about 15 to 17 significant decimal digits. The key points are:
- Only rational numbers whose denominators are powers of 2 can be represented exactly. For example, 0.5 and 0.25 have no error.
- Fractions such as 1/3 must be truncated to a finite number of bits, so the stored value deviates slightly from the true value.
- When a value is printed in decimal, the language runtime selects the shortest decimal string that uniquely identifies the binary value. As a result, 1/3 typically prints as 0.3333333333333333, which has 16 threes.
This means that for a floating-point value $x$ computed from $p/q$, $|x - p/q|$ usually falls within the floating-point precision range. As long as the denominator is not too large, few fractions fall within the same error interval. This is the theoretical basis for the reconstruction.
3. Mathematical Tools for Recovering Fractions from Floats
3.1 Continued Fraction Approximation
Any real number $x$ can be expanded as a continued fraction $[a_0; a_1, a_2, \dots]$. Truncating this expansion produces fractions called convergents. Convergents have two properties:
- Among fractions with a bounded denominator, convergents are among the closest approximations to $x$.
- Consecutive convergents can be computed with integer arithmetic. High-precision floating-point is not required.
The recurrence relations are:
- $pn = a_n p{n-1} + p_{n-2}$
- $qn = a_n q{n-1} + q_{n-2}$
The initial values are $p{-2}=0,\ p{-1}=1,\ q{-2}=1,\ q{-1}=0$.
3.2 The Stern-Brocot Tree
The Stern-Brocot tree is a binary search tree that contains every positive rational number. Each rational appears exactly once, in lowest terms. Starting from the root 1/1, each step takes the mediant of the two current bounds, $(a+c)/(b+d)$, and narrows the search toward the target value.
The Stern-Brocot tree and continued fraction approximation solve the same problem from two perspectives. The tree describes the search as a path. The continued fraction method implements the same search with a recurrence. In engineering practice, the continued fraction form is shorter and runs more predictably.
4. Algorithm Implementation (Pseudocode)
The following language-neutral pseudocode takes a floating-point number and a maximum denominator, and returns a candidate fraction in lowest terms.
function ContinuedFractionApprox(x, max_denominator, tolerance):p_prev, p_curr = 0, 1q_prev, q_curr = 1, 0r = xloop:a = floor(r)p_prev, p_curr = p_curr, a * p_curr + p_prevq_prev, q_curr = q_curr, a * q_curr + q_previf q_curr > max_denominator: return (p_prev, q_prev)if |p_curr / q_curr - x| < tolerance: return (p_curr, q_curr)r = r - aif r == 0: return (p_curr, q_curr)r = 1 / r
Keep three points in mind when using this algorithm:
- The tolerance should be slightly larger than the floating-point precision, for example, a few multiples of the relative error. If the tolerance is too small, rounding effects can cause the correct result to be missed.
- The maximum denominator sets the search range. A larger limit produces more candidates, and the result becomes less unique.
- Validate the returned result, as described in the next section.
5. Result Validation
An algorithm’s output is not enough to support a conclusion on its own. The result must be validated. Recommended checks include:
- Back-substitution check: Convert the candidate fraction $p/q$ to a floating-point number and compare it with the original value. The two must match exactly. This step eliminates most coincidental matches.
- Cross-sample verification: Solve several data sets generated by the same rule separately. If the same denominator factors appear consistently across samples, the inference is more reliable.
- Error interval check: Record the error interval permitted for each sample, and confirm that the candidate fraction falls within it.
- Boundary testing: Build test cases from known fractions, such as 1/7 and 5/13, and confirm that the algorithm recovers them correctly. This is the most direct way to verify the implementation.
Treat the algorithm’s output as a reliable conclusion only after it passes these checks. Otherwise, treat it as an unverified candidate.
6. Implications for Metering System Design
This analysis also offers several guidelines for system designers.
6.1 Define Rounding Rules Clearly
Before storing or returning metering data, define a consistent rounding position and method. For example, keep a fixed number of decimal places, or store values as integers in the smallest unit. Fixed precision removes trailing noise and reduces ambiguity caused by inconsistent formatting on the front end.
6.2 Separate Display Precision from Internal Precision
Internal calculations can keep high precision, while external output shows only the digits the business needs. With these layers separated, API responses do not expose unnecessary calculation details.
6.3 Control Information Exposure in Interfaces
Metering data is often linked to pricing, quotas, or resource policies. If raw values returned by an interface allow internal parameters to be inferred, that is an information leak. Safer practices include:
- Return rounded or bucketed values externally.
- Apply access control to internal metrics.
- Monitor for unusually precise outputs, which can reveal configuration changes.
6.4 Boundaries of Permitted Use
Fraction recovery should only be applied to data you are authorized to access. For internal data from third-party services, do not collect, analyze, or publish inferred internal parameters without authorization, even if it is technically possible. This is both a compliance requirement and a basic professional obligation for engineers.
7. Summary
Floating-point representation error leaves traces in metering output that can be analyzed. Continued fraction methods and the Stern-Brocot tree can convert these traces back into fractions in lowest terms. The approach works when the algorithm parameters are sound and the results are verified through back-substitution and cross-sample checks. For developers, the more valuable takeaway is understanding what causes floating-point error. That understanding supports clear rounding strategies, precision layering, and access control, so metering systems stay accurate without exposing unnecessary information.
