我怎样才能把一个浮点数到一个字节分子和分母psented最接近的分数再$ P $?分母、浮点、字节、最接近

2023-09-11 00:13:02 作者:Complete(完成)

如何可以编写给浮点数,并尝试重新present被尽可能准确地使用一个分子和分母的算法,这两个限制为一个Java字节的范围?

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 to the range of a Java byte?

这样做的原因是,一个I2C器件想要一个分子和分母,而​​这将是有意义的给它一个浮点数。

The reason for this is that an I2C device wants a numerator and denominator, while it would make sense to give it a float.

例如, 3.1415926535 ... 将导致七十八分之二百四十五,而不是百分之三百一十四 22/7

For example, 3.1415926535... would result in 245/78, rather than 314/100 or 22/7.

在效率方面,这将被要求各地三次在节目的开始,但之后不尽然。因此,一个缓慢的算法是不的太的不好。

In terms of efficiency, this would be called around three times at the start of the program, but after that not at all. So a slow algorithm isn't too bad.

推荐答案

我已经写了一些code(在Java中,偶数)做的只是你要求的事。就我而言,我需要显示的缩放因子既是一个百分比比率。这方面最熟悉的例子是缩放对话框中,在图像编辑器看到,如GIMP。

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.

您可以找到我的code 此处,在updateRatio()方法开始于行1161,您可以简单地使用它,只要LGPL许可为你工作。我基本上是做了如下什么在GIMP做---这是那些东西,其中有pretty的多只高效,明智的方式来做到这一点的。

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.

 
精彩推荐
图片推荐