Implement a Function to Return a Ratio

Implement a function to return a ratio from a double function (0.25 -> 1/4).
If the function tolerance is .01 then Find Ratio(.24, .01) -> 1/4

šŸ’”Strategies for Solving This Problem

Continued Fractions and Approximation

This appeared at a quant firm interview. It's about approximating decimals as fractions with tolerance. Tests understanding of numerical methods and algorithmic precision.

The Problem

Convert decimal to fraction: 0.25 → 1/4. With tolerance: 0.24 with tolerance 0.01 still gives 1/4 (since |0.25 - 0.24| < 0.01).

Naive Approach: Brute Force

Try all denominators from 1 to some limit. For each, find best numerator. Check if within tolerance.

O(n²) where n is denominator limit. Works but slow.

Better: Continued Fractions

Use Euclidean algorithm to find best rational approximation. Produces sequence of "convergents" that are optimal approximations.

For π = 3.14159...:

  • 3/1
  • 22/7 (error 0.0013)
  • 333/106
  • 355/113 (error 0.000000027!)

Each convergent is the best approximation for its denominator size.

Algorithm Steps

  1. Start with value v
  2. Integer part: floor(v)
  3. Fractional part: v - floor(v)
  4. Invert fractional part: 1 / frac
  5. Repeat until frac < tolerance or denominator too large

Key Insight

Each step of Euclidean algorithm gives next convergent. These are provably optimal approximations.

Scroll to Top