如何从MatLab上的无理数生成近似分数?

时间:2012-03-26 03:15:27

标签: php matlab fractions

我有一个笨拙的PHP代码,我用它来获得无理数的近似分数,如pi,phi,2,3的平方根等等。我想得到一个我可以在MatLab上使用的公式,并获得数据表并根据近似分数绘制一个图。也许某人已经可以从中获取但我会提供PHP代码来补充案例:

$n = phi(); # irrational number (imaginary/complex number?)
$x = 500; # how many numbers to check
$max = 50; # how many instances to show
$precision = 0.0001;

# check every i against every j and make a comparison how near their values are to each other
for ($i=1; $i<$x; $i++) {
    for ($j=1; $j<$x; $j++) {
        # compared value is stored on array. very distant numbers needs to be discarded ($precision) or array gets easily too big, limit 64k
        if (($d = abs(($n - ($i/$j)))) && $d > $precision) continue;
        $c[] = array($i, $j, $d);
    }
}

# sort comparison chart by third index (2)
array_qsort($c, 2);

# print max best values from the sorted comparison chart
$count = count($c);
echo "closest fraction numbers for $n from $count calculated values are:<br />\n<br />\n";
$r = 0;
foreach ($c as $abc) {
    $r++;
    $d = $abc[0]/$abc[1];
    echo $abc[0] . '/' . $abc[1] . ' = ' . $d . ' (' . round($abc[2]*(1/$precision), 10) . ')' . "<br />\n";
    if ($r > $max) break;
}

2 个答案:

答案 0 :(得分:1)

有更高效的算法,这里有一个:

function [a, b, c] = approxfrac( r, precision )
a = floor(r);
r = r - a;
if r==0,
    b=0;
    c=1;
    return
end
p1 = 0; q1 = 1;
p2 = 1; q2 = 1;
b = p1+p2;
c = q1+q2;
while abs(r-b/c) > precision,
    if r>b/c,
        p1 = b; q1 = c;
    else
        p2 = b; q2 = c;
    end
    b = p1+p2;
    c = q1+q2;
end
end

答案 1 :(得分:0)

有一个功能:rat