Eri*_*ric 5 java algorithm math floating-point fractions
如何编写一个算法,给定一个浮点数,并尝试使用分子和分母(两者都限制在 Java 字节的范围内)尽可能准确地表示?
原因是 I2C 设备需要分子和分母,而给它一个浮点数是有意义的。
例如,3.1415926535...将导致245/78, 而不是314/100或22/7。
就效率而言,在程序开始时会调用大约三次,但之后就不再调用了。所以慢的算法也不算太糟糕。
这是我最终使用的代码(基于uckelman的代码)
public static int[] GetFraction(double input)
{
int p0 = 1;
int q0 = 0;
int p1 = (int) Math.floor(input);
int q1 = 1;
int p2;
int q2;
double r = input - p1;
double next_cf;
while(true)
{
r = 1.0 / r;
next_cf = Math.floor(r);
p2 = (int) (next_cf * p1 + p0);
q2 = (int) (next_cf * q1 + q0);
// Limit the numerator and denominator to be 256 or less
if(p2 > 256 || q2 > 256)
break;
// remember the last two fractions
p0 = p1;
p1 = p2;
q0 = q1;
q1 = q2;
r -= next_cf;
}
input = (double) p1 / q1;
// hard upper and lower bounds for ratio
if(input > 256.0)
{
p1 = 256;
q1 = 1;
}
else if(input < 1.0 / 256.0)
{
p1 = 1;
q1 = 256;
}
return new int[] {p1, q1};
}
Run Code Online (Sandbox Code Playgroud)
感谢那些帮助过的人