0
我有一個笨拙的PHP代碼,我用它來得到無理數的近似分數,如pi,phi,2,3的平方根等等。我想獲得一個公式,我可以在MatLab上使用該公式,並獲取數據表並根據近似分數繪製一個圖。也許有人已經可以從這個搶,但我會提供的PHP代碼爲補充的情況下:如何從MatLab上的無理數產生近似分數?
$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;
}
太棒了!我修改了一下得到第四個返回值: 'd =(a * c)+ b;)'所以我稱'[a,b,c,d] = approxfrac(pi,0.01);' - > '3,1,7,22'其中分數是'22/7'或'3 1/7' 我會接受作爲一個部分解決方案,因爲我仍然想獲得一個n個最好的解決方案PHP代碼。這個功能可以通過改變精度來使用嗎? – MarkokraM 2012-03-26 10:10:42
然後,您可以通過將它們添加到數組並將這些數組返回給b和c來跟蹤while循環中的所有b和c值。在每次迭代中,b/c比率比先前的迭代更接近期望的數量(r-a),因此它們已經被排序。 – 2012-03-28 14:02:21