Recovering Fractions from Floating-Point Values: A Numerical Forensics Case Study
A high-precision decimal in an API response can reveal clues about the calculation behind it. This article explains how to recover candidate fractions with Python, validate them across multiple samples, and reduce unintended information exposure through deliberate API precision choices—all within authorized analysis.
1. A Decimal Worth Investigating
While inspecting usage data returned by an API, one field stood out: 0.16327272727272726, with 17 digits after the decimal point. That was far more precision than the interface needed, suggesting that the value had come directly from a division operation without display formatting.
User interfaces typically show only one or two decimal places. When a raw floating-point value appears in a response, the backend may be serializing an intermediate calculation directly. Such values can be useful to an analyst, but they can also expose information the provider did not intend to disclose.
This article uses that decimal to explain how to recover candidate fractions from floating-point values and how API designers can limit this kind of exposure.
These methods are intended only for data from your own account, authorized test environments, or publicly available sources. They must not be used to bypass quotas, evade billing, or interfere with other users.
2. From a Floating-Point Value to a Fraction
2.1 Why Floating-Point Values Retain Clues About Fractions
IEEE 754 double-precision floating-point numbers retain approximately 15–17 significant decimal digits. A ratio such as used / total is generally stored as the nearest representable binary floating-point value. Serialization commonly produces enough decimal digits to preserve that value, sometimes around 17 significant digits.
Although the decimal representation reflects rounding, it can still retain enough information to identify a plausible underlying fraction.
Suppose a server performs this calculation:
used = 1796total = 11000ratio = used / totalprint(ratio) # Approximately 0.16327272727272727
The fraction 1796/11000 reduces to 449/2750. Both represent the same ratio.
That reduction creates an important limitation: a single sample cannot establish the original total quota. The total could be 2750, 5500, 11000, or another integer multiple of 2750. Recovering a reduced fraction identifies a ratio, not necessarily the original numerator and denominator.
Multiple samples are therefore needed for cross-validation, as discussed in Section 3.
2.2 Finding a Rational Approximation with Fraction
Python’s standard-library fractions.Fraction class provides limit_denominator(), which finds the closest rational approximation whose denominator does not exceed a specified limit:
from fractions import Fractionx = 0.16327272727272726print(Fraction(x).limit_denominator(10_000)) # 449/2750
In CPython, limit_denominator() uses continued fractions. Continued-fraction convergents are closely related to paths through the Stern–Brocot tree; both structures are useful for finding rational approximations.
The denominator limit matters. Two distinct reduced fractions with denominators no greater than N differ by at least 1/N². When the denominator bound is sufficiently small relative to floating-point uncertainty, a matching fraction is often unique and stable.
For values at the scale of this example, bounds below roughly 10⁸ can be useful, but that is not a universal uniqueness guarantee. If the bound becomes too large—for example, above 10¹²—the result may instead be a fraction with a large denominator that happens to fit the rounded floating-point value more closely, rather than the original calculation.
2.3 Bounded Search: Denominator Limits and Error Tolerance
To enumerate candidates, search denominators one at a time. For each denominator q, choose the integer p nearest to x * q, then check whether p / q differs from x by no more than a tolerance, eps.
The stopping condition is explicit: the search ends at the maximum denominator.
Choosing eps involves two considerations:
- It must comfortably exceed floating-point rounding error. Otherwise, a valid underlying fraction may be rejected. For values near
0.16, double-precision rounding error is on the order of10⁻¹⁷. - It should be much smaller than
1 / max_den². Otherwise, distinct candidate fractions become difficult to distinguish. Withmax_den = 10⁵, this spacing bound is approximately10⁻¹⁰, makingeps = 10⁻¹²a reasonable choice for this example.
A Stern–Brocot tree search can locate fractions within an interval more efficiently, but denominator enumeration is straightforward to understand and verify.
2.4 Complete Implementation and Test
from fractions import Fractiondef candidates(x, max_den=100_000, eps=1e-12):"""Yield reduced fractions within eps of x, with denominator <= max_den."""seen = set()for q in range(1, max_den + 1): # The denominator bound guarantees terminationp = round(x * q)if abs(p / q - x) <= eps:f = Fraction(p, q) # Automatic reduction makes deduplication easyif f not in seen:seen.add(f)yield fdef test_candidates():result = list(candidates(0.16327272727272726, max_den=10_000))assert result == [Fraction(449, 2750)], resultif __name__ == "__main__":test_candidates()print("ok")
Candidate fractions still need interpretation. Could the reduced denominator scale to a plausible quota, such as a round hundred or thousand, or a quantity divisible by a familiar billing unit? Across samples from the same account, do inferred numerator increases match actual activity?
These are domain-specific checks. Mathematics alone cannot answer them.
3. Cross-Validating Multiple Samples
One observation is not enough to establish the original calculation. Reliable analysis depends on consistency across multiple samples.
| Check | Input | Expected result | If the check fails |
|---|---|---|---|
| Denominator consistency | At least three samples from the same account at different times | Recovered fractions are compatible with a common underlying total, allowing for reduction | Collect more samples and confirm that they belong to the same billing period |
| Unit conversion | The inferred total quota and common billing units | The quota falls within a plausible range for the relevant unit | Verify unit definitions, such as the relationship between tokens and characters |
| Growth rate | Numerator changes between adjacent samples and activity records | Increases are reasonably proportional to actual operations | Account for additional consumption from caching behavior, retries, or background tasks |
The principle is simple: use mathematical structure to constrain the search space, then use consistency across observations to rule out coincidence.
If any check fails, reject or suspend the conclusion. A result should not be retained merely because it looks plausible.
4. Authorization and Compliance Boundaries
Reverse-engineering findings may involve terms of service and billing rules. Before starting, confirm three points:
- The data comes from your own account or falls within an explicitly authorized scope.
- The purpose is to understand your usage, perform an authorized security assessment, or improve an API—not to obtain additional quota.
- Any discovered issue will be reported through the provider’s vulnerability disclosure process rather than publicly distributed or exploited.
5. Recommendations for API Designers
This example illustrates why API output precision should be an intentional design choice.
Format values on the server. Avoid passing internal floating-point intermediates directly into responses. Apply an appropriate precision policy, such as
round(x, 4), or return a display-ready string.Include numeric precision in security reviews. JSON serialization libraries commonly preserve enough precision to reproduce a floating-point value. Exposed debug or logging fields can therefore provide clues about internal calculations.
Use integer representations for billing quantities. Store and transmit quotas and billing amounts in their smallest defined units. Where a ratio is needed, a fixed-scale integer representation—such as ten-thousandths—can make precision explicit, with conversion handled at the display layer. This also avoids accumulated floating-point rounding errors. Information exposure still depends on which values and precision the API reveals.
Return only the fields clients need. When providing structured numeric output, avoid including internal numerators, denominators, or other intermediate values unless they are required.
For analysts, a floating-point sample can narrow the possibilities to a finite set of candidate fractions under chosen bounds. Establishing the original numerator and denominator requires multiple samples, consistency checks, and domain knowledge. One number alone is not enough.
6. Frequently Asked Questions
Why can a floating-point value reveal an underlying fraction?
Division generally produces a value that is rounded to the nearest representable binary floating-point number. Its serialized decimal representation can still preserve enough precision to identify a plausible reduced fraction within a bounded search space.
That does not necessarily reveal the original numerator and denominator: integer multiples of the reduced fraction remain possible.
How should I choose the denominator limit for limit_denominator()?
Choose a limit above the denominator you consider plausible, but keep it conservative relative to the uncertainty in the observed value. A range from 10⁴ to 10⁶ can be a practical starting point for this type of example.
A limit that is too small can exclude the underlying fraction. One that is too large can produce a fraction that fits floating-point rounding artifacts instead. Treat roughly 10⁸ as a cautionary scale for this example, not a universal cutoff, and validate results against multiple samples.
How can I rule out false positives?
Test each candidate against multiple observations and retain only interpretations that remain consistent across them. Check that the inferred total is plausible for the service and that your calculation matches the server’s processing, including rounding and unit conversion.
Remember that fraction reduction hides the original scale, so a recovered denominator is not automatically the account’s total quota.
Conclusion
The digits in a floating-point value can carry clues about the calculation that produced it. Developers should therefore control API output precision deliberately. Analysts should treat recovered fractions as hypotheses that require validation—and keep all investigation within an authorized scope.
