我怎样才能把一个浮点数到一个字节分子和分母psented最接近的分数再$ P $? [英] How can I turn a floating point number into the closest fraction represented by a byte numerator and denominator?

查看:169
本文介绍了我怎样才能把一个浮点数到一个字节分子和分母psented最接近的分数再$ P $?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何可以编写给浮点数,并尝试重新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 <一个href="http://sourceforge.net/p/vassalengine/svn/9019/tree/VASSAL-src/branches/3.1/src/VASSAL/build/module/map/Zoomer.java#1167"相对=nofollow>此处,在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.

这篇关于我怎样才能把一个浮点数到一个字节分子和分母psented最接近的分数再$ P $?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆