将浮点数转换为分数 [英] Converting float decimal to fraction
问题描述
我试图将用十进制结果键入的计算转换成分数。例如66.6666666667分成66 2/3。任何指针?
提前感谢
I am trying to convert calculations keyed in by users with decimal results into fractions. For e.g.; 66.6666666667 into 66 2/3. Any pointers? Thanx in advance
推荐答案
继续分数可以用来找到对严格意义上最好的实数的有理逼近。这里有一个PHP函数,它可以找到一个给定(正)浮点数的合理近似值,其相对误差小于 $ tolerance
:
Continued fractions can be used to find rational approximations to real numbers that are "best" in a strict sense. Here's a PHP function that finds a rational approximation to a given (positive) floating point number with a relative error less than $tolerance
:
<?php
function float2rat($n, $tolerance = 1.e-6) {
$h1=1; $h2=0;
$k1=0; $k2=1;
$b = 1/$n;
do {
$b = 1/$b;
$a = floor($b);
$aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux;
$aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux;
$b = $b-$a;
} while (abs($n-$h1/$k1) > $n*$tolerance);
return "$h1/$k1";
}
printf("%s\n", float2rat(66.66667)); # 200/3
printf("%s\n", float2rat(sqrt(2))); # 1393/985
printf("%s\n", float2rat(0.43212)); # 748/1731
我已经写了更多关于这个算法的原因,甚至是一个JavaScript演示这里: http://jonisalonen.com/2012/converting-decimal-numbers- to-ratios /
I have written more about this algorithm and why it works, and even a JavaScript demo here: http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/
这篇关于将浮点数转换为分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!