沃梦达 / 编程问答 / php问题 / 正文

将浮点小数转换为分数

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
", float2rat(66.66667)); # 200/3
printf("%s
", float2rat(sqrt(2)));  # 1393/985
printf("%s
", float2rat(0.43212));  # 748/1731

我已经写了更多关于这个算法及其工作原理的文章,甚至还有一个 JavaScript 演示:https://web.archive.org/web/20180731235708/http://jonisalonen.com/2012/converting-decimal-numbers-to-比率/

I have written more about this algorithm and why it works, and even a JavaScript demo here: https://web.archive.org/web/20180731235708/http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/

这篇关于将浮点小数转换为分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将浮点小数转换为分数

基础教程推荐