如何在php中解决这个数学方程式

时间:2014-09-02 03:28:18

标签: php algorithm math equation

我只能在数组中保存第一个值。 我需要将值保存到数组$S$D

数学计算:

S1 = O*P*M1/Y1
D1 = N-S1

S2 = (O-D1)*P*M2/Y2
D2 = N-S2

S3 = (O-D1-D2)*P*M3/Y3
D3 = N-S3
...

解决方案:

$S = array();
$D = array();
$M = array("1"=>30,"2"=>31,"3"=>30);
$Y = array("1"=>360,"2"=>360,"3"=>360);
$O = 30000;
$P = 0.3;
$N = 10509.74;

for($i=1; $i<=count($M); $i++){
    if($i==1){
        $S[1] = $O*$P*$M[1]/$Y[1];
        $D[1] = $N - $S[1];
    }
    else{

    }       
}

print_r($S);
echo "<br /><br />";
print_r($D);

Array ( [1] => 750 ) 
Array ( [1] => 9759.74 )

输出必须是:

Array ( [1] => 750, [2] =>522,87 , [3] =>256,34 ) 

Array ( [1] => 9759.74, [2] =>9986,86 , [3] =>10253,40  )

1 个答案:

答案 0 :(得分:0)

首先将D组分组,不要对索引进行硬编码,使用$i

$S = array();
$D = array();
$M = array("1"=>30,"2"=>31,"3"=>30);
$Y = array("1"=>360,"2"=>360,"3"=>360);
$O = 30000;
$P = 0.3;
$N = 10509.74;

for($i = 1, $size = count($M); $i <= $size; $i++){
    $final_D = 0;
    // group the D's first (O-D1), (O-D1-D2), ... and so on
    $temp = array_slice($D, 0, $i);
    foreach ($temp as $key => $value) {
        $final_D += $value;
    }

    $S[$i] = ($O-$final_D)*$P*$M[$i]/$Y[$i];
    $D[$i] = $N - $S[$i];
}

print_r($S); // Array ( [1] => 750 [2] => 522.87338333333 [3] => 256.33483458333 ) 
echo '<br/>';
print_r($D); // Array ( [1] => 9759.74 [2] => 9986.8666166667 [3] => 10253.405165417 )