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

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

    I've written some code (in Java, even) to do just the thing you're asking for. In my case, I needed to display a scaling factor as both a percentage and a ratio. The most familiar example of this is the zoom dialog you see in image editors, such as the GIMP.

    You can find my code here, in the updateRatio() method starting at line 1161. You can simply use it, so long as the LGPL license works for you. What I did essentially follows what's done in the GIMP---this is one of those things where there's pretty much only one efficient, sensible way to do it.

提交回复
热议问题