1

The question is simple to understand, but for the life of me, I can't figure out how to go about implementing it:

How do I get from a decimal fraction approximation to an actual fraction (i.e. to two integers)? e.g. given 0.666666666667, how can I get 2/3 (using some defined precision)?

I know that I can convert 0.666666666667 to 666666666667/10000000..., and I know that I can reduce a fraction using the GCD but those methods don't solve the problem because 6667/10000 doesn't reduce to 2/3.

What I want to know is how to take some decimal like 0.6666667 and say, "that's probably 2/3".

Any ideas?

I have some code working for reducing the fractions but again, not for the task above:

public class Fraction implements Comparable<Fraction> {
    private static Map<Fraction, Long> gcdMemo = new HashMap<>();
    public final long n;
    public final long d;

    public Fraction(long n, long d) {
        this.n = n; this.d = d;
    }

    public Fraction multiply(Fraction f) {
        return new Fraction(f.n * this.n, f.d * this.d).reduced();
    }

    public Fraction subtract(Fraction f) {
        return this.add(new Fraction(-f.n, f.d));
    }

    public Fraction abs() {
        return new Fraction(Math.abs(n), Math.abs(d));
    }

    public Fraction add(Fraction f) {
        long newN0 = this.n * f.d;
        long newD0 = this.d * f.d;
        long newN1 = f.n * this.d;
        return new Fraction(newN0 + newN1, newD0).reduced();
    }

    public static long gcd(long a, long b) {
        if (gcdMemo.containsKey(new Fraction(a, b))) {
            return gcdMemo.get(new Fraction(a, b));
        }
        if(a == 0 || b == 0) return a + b; // base case
        long result = gcd(b, a % b);

        Fraction f = new Fraction(a, b);
        if (!gcdMemo.containsKey(f)) {
            gcdMemo.put(f, result);
        }
        return result;
    }

    public Fraction reduced() {
        long gcd = gcd(n, d);
        return new Fraction(n / gcd, d /gcd);
    }

    public int compareTo(Fraction f) { /*...*/ }
    public int hashCode() { /**/ }
    public boolean equals(Object obj) { /*...*/ }
    public String toString() { /*...*/ }

}

Also, I know this is possible because my TI-84 can do it :D

Rico Kahler
  • 17,616
  • 11
  • 59
  • 85

0 Answers0