Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在MatLab上由无理数生成近似分数?_Php_Matlab_Fractions - Fatal编程技术网

Php 如何在MatLab上由无理数生成近似分数?

Php 如何在MatLab上由无理数生成近似分数?,php,matlab,fractions,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 instanc

我有一个笨拙的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;
}
$n=phi()#无理数(虚数/复数?)
$x=500;#要查多少号码
$max=50;#要显示多少个实例
$precision=0.0001;
#检查每个i和每个j,并比较它们的值彼此之间的接近程度
对于($i=1;$i$max)中断;
}

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

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

这有一个函数:

太好了!我对它进行了一些修改,以获得第四个返回值:
d=(a*c)+b;)[a,b,c,d]=approxfrac(pi,0.01)
->
3,1,7,22
其中分数是
22/7
3 1/7
我会接受这作为部分解决方案,因为我仍然希望得到一个由n个最佳解决方案组成的数组,就像我的PHP代码一样。这个函数可以通过改变精度来使用吗?然后,您可以通过将它们添加到数组中并返回这些数组中的b和c值来跟踪while循环中的所有b和c值。在每次迭代中,b/c比上一次迭代更接近所需的数字(r-a),因此它们已经被排序。