How to convert decimal to fractions?

前端 未结 10 2190
心在旅途
心在旅途 2020-12-06 06:26

What I need to convert decimal to fractions. It is easy to convert to 10\'s feet.

1.5 => 15/10

This can do via this code:



        
10条回答
  •  借酒劲吻你
    2020-12-06 07:22

    Given double x >= 0, int p, int q, find p/q as closest approximation:

    • iterate on q from 1 upwards, determine p above and below; check deviations

    So (not tested):

    public static Rational toFraction(double x) {
        // Approximate x with p/q.
        final double eps = 0.000_001;
        int pfound = (int) Math.round(x);
        int qfound = 1;
        double errorfound = Math.abs(x - pfound);
        for (int q = 2; q < 100 && error > eps; ++q) {
            int p = (int) (x * q);
            for (int i = 0; i < 2; ++i) { // below and above x
                double error = Math.abs(x - ((double) p / q));
                if (error < errorfound) {
                    pfound = p;
                    qfound = q;
                    errorfound = error;
                }
                ++p;
            }
        }
        return new Rational(pfound, qfound);
    }
    

    You could try it for Math.PI and E.

提交回复
热议问题