0

pi、phi、2 の平方根、3 などの無理数のおおよその分数を取得するために使用した不器用な PHP コードがあります。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 に答える