How can I turn a floating point number into the closest fraction represented by a byte numerator and denominator?

后端 未结 6 996
南旧
南旧 2021-01-06 23:44

How can I write an algorithm that given a floating point number, and attempts to represent is as accurately as possible using a numerator and a denominator, both restricted

6条回答
  •  天涯浪人
    2021-01-07 00:00

    You should look at the Farey Sequence.
    Given a limit on the denominator d, the Farey Sequence is every fraction having denominator <= d.

    Then, you would simply take your float and compare it to the resolved value of the Farey fraction. This will allow you to represent your float in terms of repeating-decimal reals.

    Here is a page on its implementation in java:
    http://www.merriampark.com/fractions.htm

    Here is a good demonstration of their use:
    http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/fareySB.html

提交回复
热议问题