0

我有一个笨拙的 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;
}
4

2 回答 2

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
于 2012-03-26T07:23:28.153 回答
0

有一个功能:老鼠

于 2012-03-26T21:29:19.540 回答