from dascore.utils.time import to_exact_fraction
to_exact_fraction(1024.0)
to_exact_fraction(1 / 3000)
to_exact_fraction(0.00033333333, rel_tol=1e-7, max_term=10_000)
to_exact_fraction(0.1234567891234) is NoneTrue
| function of dascore.utils.time | source |
to_exact_fraction(
value ,
max_term: int = 100000,
rel_tol: float = 0.0,
)-> ‘Fraction | None’
Recover the simple fraction a float was rounded from, or None.
A stored rate of 1024.0 or an interval computed as 1 / 3000 is the nearest double to a ratio of small integers. This returns that ratio when one whose numerator and denominator are both at most max_term rounds to the very same double; otherwise None, and the caller should keep the value as given. Exact agreement between small terms is what makes the guess safe: an arbitrary double has about a one-in-a-million chance of matching such a fraction.
A value stored with fewer digits than a double holds (0.00033333333, or a float32) never matches exactly. rel_tol admits such a value, but loosely: every real number is within a part in a billion of some fraction with terms below a million (pi is 3126535/995207), so pair a tolerance with a small max_term. Never apply this to a derived quantity.
| Parameter | Description |
|---|---|
| value | A finite number (int, float, numpy scalar, or Fraction). |
| max_term | The largest numerator or denominator considered. |
| rel_tol |
The relative error allowed between the fraction and value;zero (the default) requires the same double. |