From Floating-Point Residues to Billing Rules: A Technical Guide to Usage Metering
This article explains why usage metering systems often produce long floating-point tails, how to recover plausible rational fractions with continued fractions and Stern-Brocot trees, and how to validate inferred rules through cross-checking. It then covers weighted cost modeling, integer storage for metering data, conversion between usage and cost, evaluation of subscription plans, engineering practices, and the boundaries and compliance requirements of this type of analysis.
From Floating-Point Residues to Billing Rules: A Technical Guide to Usage Metering
1. Starting Point: Why Numeric Values Look “Untidy”
Metering systems typically record usage as integers or fixed-point values, then convert them by ratio into displayed values or fees. When intermediate results pass through division, multiplication, and unit conversion, the final value is often stored as a binary floating-point number. Many decimal fractions cannot be represented exactly in binary, so the computer stores the closest approximation. As a result, the output may contain a long mantissa tail.
Such a tail is not an error by itself, but it carries information. If the decimal representation of a floating-point number is close to a fraction with a small denominator, it most likely comes from a rational arithmetic operation rather than a random measurement. Recognizing this is the prerequisite for further inference. For example, a value such as 0.16327272727272726, with a repeating pattern near the end, suggests that it is likely the result of a fraction stored as a floating-point value.
It is important to note that mantissa patterns only indicate that a value comes from fractional arithmetic; they do not directly reveal business rules. Converting a value back into a fraction is only the first step of inference.
2. Recovering Fractions with Rational Approximation
2.1 Continued Fraction Expansion
The continued fraction method expands any real number step by step into an integer part and the reciprocal of a fractional part. At each step, the integer part is taken, producing a sequence of convergents whose approximation improves as the number of steps increases. The process can stop when the error between a convergent and the original value falls below a configured threshold.
The following pseudocode illustrates the approach only:
Function recover_fraction(x, tolerance, max_denominator):p_prev2, q_prev2 = 0, 1p_prev1, q_prev1 = 1, 0residual = xloop:a = floor(residual)p = a * p_prev1 + p_prev2q = a * q_prev1 + q_prev2if q > max_denominator: return (p_prev1, q_prev1)if abs(x - p / q) < tolerance: return (p, q)p_prev2, q_prev2 = p_prev1, q_prev1p_prev1, q_prev1 = p, qresidual = 1 / (residual - a)
The denominator limit is a necessary safeguard. Without it, the algorithm may return a fraction with an extremely large denominator. Such a fraction may be mathematically valid but has little practical explanatory value.
2.2 Stern-Brocot Tree Method
The Stern-Brocot tree is a binary tree structure that enumerates all positive rational numbers in order. The root node is 1/1, and each node has left and right boundaries represented by two known fractions. A new node takes the mediant of the two boundaries, that is, the sum of the numerators over the sum of the denominators.
During search, start from the root node, compare the target value with the current node, and decide whether to move left or right. Each step yields a more precise candidate fraction. When a candidate falls within the error range and its denominator is already minimal, it is the simplest rational approximation of the target.
This method produces the same set of best rational approximations as the continued fraction method; the difference lies in representation. Tree search is more intuitive and easier to reason through by hand, while continued fractions are better suited to programmatic implementation.
2.3 Implementation Considerations
- The error tolerance should match floating-point precision. A double-precision floating-point number has about 15 to 17 significant digits. If the tolerance is set too small, floating-point rounding noise may be mistaken for a valid signal.
- The denominator limit determines how interpretable the result is. The larger the denominator, the easier it is to fit arbitrary values, and the less reliable the conclusion becomes.
- Metering data may be rounded before storage. Recovered results should be compared across multiple samples rather than relying on a single value.
3. From Single Data Points to Rules: Cross-Validation
A single sample cannot determine a rule. One fraction can explain multiple ratio relationships, and a conclusion drawn from only one value is easily distorted. Inference should follow this process:
- Collect data with controlled variables. Under the same input conditions, change one factor at a time, such as input length, output length, or feature type, and record the usage value returned each time.
- Calculate ratios. Compare usage under different conditions and check whether the ratios are stable. If the ratio remains consistent across multiple samples, a fixed conversion coefficient likely exists.
- Check consistency. The same set of coefficients should explain all samples. If a group of samples cannot be explained, check for interference such as caching, truncation, rounding, or billing windows that cross periods.
- Record uncertainty. Mark inferred results as estimates and note the sample count, sampling time, and error range.
The core of cross-validation is that a conclusion must be independently reproducible across different datasets. If it holds for only one dataset, it should be treated with caution.
4. Metering Models and Cost Modeling
4.1 Basic Structure of Weighted Metering
Many services charge by consumption, but different types of consumption are assigned different weights. Common cases include different unit prices for input and output, different processing-unit consumption rates across capability tiers, and additional resource use by certain features. Therefore, the cost of a single request can usually be written as a weighted sum.
Illustrative code:
Function estimate_cost(input_volume, output_volume, rate_table):cost = input_volume * rate_table["input_unit_price"] + output_volume * rate_table["output_unit_price"]return cost
The rate table should be based on the prices published by the service provider. Inferred coefficients can serve only as a reference for comparative analysis and cannot replace official pricing.
4.2 Storing Metering Data as Integers
Floating-point arithmetic accumulates errors. If amounts or quotas are summed directly with floating-point numbers, small discrepancies may appear after long-running operation and affect reconciliation results. A common practice is to choose the smallest metering unit, such as cents, milliseconds, or the smallest token unit, perform all accumulation with integers, and apply division and formatting only at the display layer.
Function accumulate_usage(records):total = 0 // accumulate using integersfor each record r in records:total = total + r.min_unit_countreturn total
This approach avoids rounding errors and also makes auditing and replay easier.
4.3 Converting Between Cost and Usage
In engineering practice, it is often necessary to convert usage into cost or to infer available usage from a budget. Both conversions depend on stable coefficients. Before conversion, confirm three things: the definition of the metering unit, whether the coefficients change over time, and whether there are caps calculated by period or rolling window. Ignoring any of these can lead to estimation bias.
5. General Method for Evaluating Subscription Plans
The value of a subscription plan depends on actual usage patterns, not on the headline price alone. Evaluation can proceed as follows.
5.1 Map Usage Distribution
Collect request volume over a period and distinguish short-term peaks from long-term totals. If peaks frequently reach the cap, a higher short-term quota is needed. If the total volume is far below the cap, a lower-tier plan may be sufficient. The optimal choice differs between these two cases.
5.2 Calculate Effective Unit Price
Effective unit price equals the plan fee divided by the actual usable quota. This metric allows different plans to be compared on a common basis and avoids misjudgment caused by different marketing conventions. Use actual usable quota rather than advertised multipliers, because quota caps, window lengths, and metering rules can all affect the result.
5.3 Consider Quota Windows
Many services set both short-period and long-period caps. The short-period quota determines whether burst requests can be satisfied, while the long-period quota determines whether the total volume is sufficient. Both should be checked separately, because exceeding either one affects usage.
5.4 Form a Decision Basis
Organize the results into a decision table: monthly actual usage, peak demand, effective unit price, and over-limit risk. If most indicators point to the same tier, that tier can serve as the basis for selection. If the indicators diverge significantly, consider pay-as-you-go billing or phased adjustment.
6. Engineering Practice Recommendations
- Build a usage dashboard. Record the input volume, output volume, timestamp, and feature type of each request, store them in a logging service, and aggregate by time dimension.
- Set budget alerts. Define thresholds for daily, weekly, and monthly consumption, connect them to monitoring and alerting, and notify the responsible person promptly when a threshold is exceeded.
- Standardize metering conventions. Teams should agree on the same units and conversion rules, and document the source and update date of coefficients.
- Review regularly. Service provider rules may change. Revalidate the cost model with a fixed test set every quarter.
- Keep audit records. Every estimate should include the data range, calculation method, and assumptions so that later reviews are possible.
7. Method Boundaries and Compliance Requirements
First, numerical reverse inference can produce only estimated conclusions and cannot replace official explanations from the service provider. Inferred results should be labeled as estimates and must not be used as external commitments or financial basis.
Second, analysis should be based on data legally obtained from your own account. Do not bypass access controls, scrape other people’s data in bulk, or violate service terms. If large-scale sampling is needed, confirm the scope of authorization first.
Third, rules may change over time. Any model based on historical data needs periodic updates and version records.
Fourth, the value of technical analysis lies in the method itself. Mastering rational recovery, cross-validation, integer metering, and cost modeling can be transferred to the evaluation of most usage-based technical services, rather than being limited to one specific product.
8. Summary
Floating-point mantissa tails can reveal the computational origin of a value, but conclusions must be validated across multiple datasets and checked against official rules. In metering and cost analysis, integer storage, explicit units, cross-validation, and awareness of boundaries are more reliable safeguards than a one-off inference.
