How to solve equation in php

半腔热情 提交于 2019-12-14 03:27:46

问题


I have an equation getting trouble while solving it. My equation:

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
...

What I've done:

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

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

print_r($S);

No idea where i did wrong or I'm doing on wrong way.


回答1:


I'm pretty sure this is right. If not, please update your question to include the expected output for your sample input. (Doing this anyway probably isn't a bad idea.)


Implementation:

// Set up things that don't change as constants.
define('P', 0.3);
define('N', 10509.74);

// O doesn't change, but it's only used once on
// its own. We'll reuse it to store the ongoing
// value of (O-D1), (O-D1-D2), etc.
$O = 30000;

$M = array(30, 31, 30);
$Y = array(360, 360, 360);

$S = array();
$D = array();

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

print_r($S);

Output:

Array
(
    [0] => 750
    [1] => 522.87338333333
    [2] => 256.33483458333
)

If you don't need the complete $D array at the end of this you can cut it out entirely and just use $O -= N - $S[$i];. It's not exactly clear from the question so I left it in.

Precision may be an issue, though the degree of precision needed was left out so I didn't bother tackling it at all.



来源:https://stackoverflow.com/questions/25614044/how-to-solve-equation-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!