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

后端 未结 6 1025
南旧
南旧 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:13

    How worried are you about efficiency? If you're not calling this conversion function 100s of times per second or more, then it probably wouldn't be all that hard to brute-force through every possible denominator (most likely only 255 of them) and find which one gives the closest approximation (computing the numerator to go with the denominator is constant time).

提交回复
热议问题