Solve a linear equation with PHP

时间:2018-02-15 12:31:23

标签: php

The situation is:

GIVEN: 3 products units (quantity, fixed), per unit price range, interval of price change and total of 3 products price.

TARGET: Find out the unit prices of each product to match the total price at given quantity.

The following script I wrote in PHP, but it's showing "HTTP ERROR 500". What's the mistake I've done here, can you please advise me?

<?php

$qty1 = 1500000;
$qty2 = 300000;
$qty3 = 500;

$minRate = 125.000;
$maxRate = 160.000;

$gTotal = 255050000.000;

for ($i=$minRate; $i <= $maxRate; $i=$i+0.001) { 
    $item1Total = $i * $qty1;

    for ($j=$minRate; $j <= $maxRate; $j=$j+0.001) {
        $item2Total = $j * $qty2;
        $twoItemTotal = $item1Total + $item2Total;
        if ($twoItemTotal < $gTotal) {
            for ($k=$minRate; $k <= $maxRate; $k=$k+0.001) { 
                $item3Total = $j * $qty3;
                $allItemTotal = $twoItemTotal + $item3Total;
                if($allItemTotal == $gTotal){
                    echo $i . "<br>" . $j . "<br>" . $k;
                    echo "<br>-";
                }
            }       
        }
    }
}
?>

1 个答案:

答案 0 :(得分:0)

(我尝试在stackoverflow上使用Latex,但它不起作用!)

所以问题是:

  

求X,Y和Y满足方程1500000 * X + 3300000 * Y + 500 * Z = 255050000.000,X,Y和Z必须在此区间[125.000,160.000]?

那么让X和Y为[125.000,160.000]中的任何数字,并找到Z?

使用简单的数学我们发现:

Z =(255050000.000 - 3300000 * Y - 1500000 * X)/ 500

Z应大于或等于125.000,且小于或等于160.000。

意思是:

125.000≤(255050000.000 - 3300000 * Y - 1500000 * X)/500≤160.000

然后

(255050000.000 - 500 * 160.000 - 1500000 * X)/3300000≤Y≤(255050000.000 - 500 * 125.000 - 1500000 * X)/ 3300000

让Ymin =(255050000.000 - 500 * 160.000 - 1500000 * X)/ 3300000

和Ymax =(255050000.000 - 500 * 125.000 - 1500000 * X)/ 3300000

Y也应大于或等于125.000,且小于或等于160.000

因此Ymin≥125.000且Ymax≤160.000

<?php
$qty1 = 1500000;
$qty2 = 300000;
$qty3 = 500;
$minRate = 125.000;
$maxRate = 160.000;
$gTotal = 255050000.000;
$solutions = array();
$N = 0;
$t_start = microtime(true);
for( $i = $minRate; $i <= $maxRate; $i += 0.001 ){
    $j_min = ( $gTotal - $qty3 * $maxRate - $i * $qty1 ) / $qty2;
    $j_max = ( $gTotal - $qty3 * $minRate - $i * $qty1 ) / $qty2;

    if( $j_min < $minRate || $j_max > $maxRate ) continue;

    for( $j = $j_min; $j <= $j_max; $j += 0.001 ){
        //
        $k = ( $gTotal - $j * $qty2 - $i * $qty1 ) / $qty3;
        $solutions[] = [ 'i'=>$i, 'j'=>$j, 'k'=>$k ];
        $N++;
        if( !($N % 10000) ){
            // Write into a csv file then reset, (because of memory limit)
            $solutions = array();
        }
    }
}
printf( '%d solutions found after %f seconds%s', $N, (microtime(true) - $t_start), PHP_EOL );

我在笔记本电脑上运行了这个脚本,这就是我得到的:412292 solutions found after 0.166070 seconds

如果您想获得高精度结果,请尝试BCMath