Recovering Fractions from Floating-Point Values: Reverse Validation for Billing Data
This article shows how to recover a reduced fraction from a floating-point value using Stern-Brocot search, how reconstructed denominators can reveal billing-unit relationships, and how to build token-level cost models. It also covers prompt-cache break-even calculations and a practical method for comparing monthly subscriptions with pay-as-you-go pricing.
1. Background
When debugging APIs or checking invoices, developers often encounter numbers that should be simple fractions but appear as long decimal values. Floating-point values have limited precision, so an originally exact rational number is rounded to the nearest binary value and often ends with a seemingly random string of digits. This is common, but it also provides a technical clue: as long as the denominator is not too large, the original fraction can be recovered from the floating-point representation.
This article discusses three topics. First, how to recover a reduced fraction from a floating-point value. Second, how to interpret the recovered result as a proportional relationship between billing units. Third, how to estimate call costs under a token-based billing model and determine whether a monthly subscription or pay-as-you-go pricing is more cost-effective.
2. Why Floating-Point Values Leave Fraction Traces
Most computers store decimal values using the IEEE 754 double-precision format, with about 15 to 17 significant digits. The value 1/3 cannot be represented exactly in binary; the stored value is the floating-point number closest to 1/3, which usually prints as 0.3333333333333333. Similarly, 2/3 prints as 0.6666666666666666.
There is a key property here. If the true value is p/q and q is not large, then the floating-point value obtained by rounding p/q once differs from the true value by no more than half an ulp. Therefore, if dividing a candidate fraction p/q produces a floating-point value exactly equal to the observed value, that candidate can be considered the source of the observation. This criterion is stricter and more reliable than “error below some empirical threshold.”
3. Searching for Reduced Fractions with a Stern-Brocot Tree
The Stern-Brocot tree arranges all positive rational numbers uniquely in a binary tree. The search starts with the left boundary 0/1 and the right boundary 1/1, assuming the target value lies between 0 and 1. At each step, take the mediant of the two boundaries: a new fraction formed by adding the numerators and adding the denominators. If the mediant is less than the target, move the left boundary to it; if it is greater, move the right boundary to it. Continue until the floating-point value of the mediant exactly equals the target, or the denominator exceeds a configured limit.
Key implementation points:
function sb_search(x, max_den):ln, ld = 0, 1 # left boundaryrn, rd = 1, 1 # right boundaryloop:mn, md = ln + rn, ld + rd # mediant fractionif md > max_den:return NONEv = mn / md # true division; result is correctly roundedif v == x:return (mn, md)if v < x:ln, ld = mn, mdelse:rn, rd = mn, md
Several details in this code are worth noting. First, mn / md uses true division, and the result is the correctly rounded value of the exact fraction, so it can be compared directly with the observed value. Second, the first fraction found has the smallest denominator among all possible solutions, so it is the reduced fraction. Third, if the target is greater than 1, first extract the integer part and then search the fractional part. The subtraction used in splitting also introduces rounding error, so the decision should still be based on floating-point equality or a strict tolerance.
The number of Stern-Brocot search steps equals the sum of the partial quotients in the continued-fraction expansion. For common fractions with small denominators, the number of steps is small and the search completes instantly. If a partial quotient is very large, such as a value close to 1/100000, step-by-step search can be slow; in that case, use a run-length acceleration approach to skip consecutive steps in the same direction in one go. Another option is to call the rational approximation function in the standard library of most programming languages, which returns the best approximation with a denominator not exceeding the limit.
4. Deriving Billing Units from Recovered Results
When a system calculates a ratio as “count multiplied by weight, then divided by a fixed base,” the recovered denominator reflects that base. For example, if a ratio is recovered as a/b and b is exactly a multiple of some integer, this suggests that an internal measurement system based on that integer may exist.
Such inference requires cross-validation across multiple samples. The steps are:
- Recover each observed value and record the numerator and denominator.
- Observe whether the denominators share common factors or have integer-multiple relationships.
- Propose a candidate billing rule and use it to recalculate each sample.
- Compare the recalculated results with the original observations; deviations should fall within floating-point error.
Only rules that pass step 4 should be retained as hypotheses. Even then, the result is still an inference from data and should not be presented as a publicly stated fact. In addition, analysis should be limited to data you are authorized to access and should comply with the relevant terms of service.
5. A Cost Model for Usage-Based Billing
Many large language model APIs charge by token. Input tokens and output tokens usually have different unit prices, and output is generally more expensive. Cache reads and cache writes also have their own unit prices. Therefore, cost should be calculated separately by type and then summed:
cost = Σ (tokens_i × price_i) / 1,000,000
Below is an illustrative function. The unit prices are placeholders used only to show the calculation structure and do not represent any actual price:
function estimate_cost(in_tok, out_tok, cache_write_tok, cache_read_tok,price_in, price_out, w, r):# price_in and price_out are prices per million tokens# w is the cache-write multiplier and r is the cache-read multiplier,# both relative to the normal input pricecost = in_tok * price_in+ cache_write_tok * price_in * w+ cache_read_tok * price_in * r+ out_tok * price_outreturn cost / 1000000
The benefit of metering by type is that when a bill looks abnormal, the cause can be located quickly. For example, a sudden increase in output tokens usually means generated content has become longer; a drop in the cache-read ratio may mean the prefix was accidentally changed.
6. Calculating the Benefit of Prompt Caching
Prompt caching means the server stores intermediate computation results for an identical prefix, and subsequent requests with the same prefix can reuse them directly, reducing duplicate computation. From a cost perspective, the first write is usually more expensive than normal input, and each subsequent read is billed at a lower ratio.
Assume the write multiplier w is 1.25 and the read multiplier r is 0.1. These values are for demonstration only. If the same prefix is used k times, the total cache cost is w + (k − 1) × r, while the cost without caching is k. Setting the two equal gives the break-even point:
k > (w − r) / (1 − r)
Substituting the example values gives k greater than about 1.28, meaning that once the same prefix is reused at least once, caching starts to save money. For 20 calls, the total cache cost is 1.25 + 19 × 0.1 = 3.15, about 16% of the cost without caching.
To make caching effective, prefix design matters. A common practice is to place stable content, such as system instructions, tool definitions, and long documents, at the beginning of the request, and place changing user input at the end. If timestamps or random identifiers are inserted into the prefix, the hit rate will drop significantly. Before launch, use logs to measure the ratio of cache reads to writes and treat it as an ongoing monitoring metric.
7. Comparing Monthly Subscriptions with Pay-as-You-Go Pricing
The key to comparing the two payment methods is to calculate the equivalent pay-as-you-go amount for the same usage, then compare it with the subscription fee.
Equivalent amount = sum of monthly token usage of each type × corresponding unit price
A subscription is cost-effective when the equivalent amount is higher than the subscription fee. Conversely, the break-even usage can be estimated with the following function:
function breakeven_tokens(monthly_fee, price_per_million):return monthly_fee / price_per_million * 1000000
Comparing total volume alone is incomplete. Monthly plans usually also have usage caps or peak limits within a given time period. If the business has bursty traffic, rate limits may be hit even when the monthly total is sufficient. Therefore, evaluation should consider monthly total volume, peak load, and the time distribution of the business. Teams with stable and high usage tend to prefer monthly subscriptions; teams with volatile usage or small total volume usually find pay-as-you-go more flexible.
8. Engineering Practice Recommendations
- Record input, output, cache-write, and cache-read token counts for each request, and save them to logs or a metrics system.
- Break down costs by feature module, user, or environment instead of looking only at a single total.
- Set budget thresholds and alerts so that abnormal increases in daily cost or cost per request are reported promptly.
- Design stable prompt prefixes and regularly check the cache hit rate.
- Use the billing model in this article to reconcile invoices regularly. If actual amounts deviate significantly from estimates, first check whether the counting scope is consistent, then consider whether calling strategy needs adjustment.
9. Summary
Traces in floating-point values can be recovered as reduced fractions using Stern-Brocot search, which is a general numerical analysis method. Combined with a cost model, it allows unit prices and usage to be analyzed separately and verified item by item. Cache benefits can be judged with a break-even formula, and the choice between subscriptions and pay-as-you-go can be compared using equivalent amounts. With this framework, readers can independently evaluate the most suitable payment method and optimization direction for their own business workloads.
