用PHP创建一个通胀计算器

时间:2012-09-17 13:13:11

标签: php cumulative-sum

这是我现在的代码,它的全部按预期工作,然而,累计总数不起作用,我很肯定我做的事情绝对愚蠢。

assume period = 20
assume inflation = 3
assume nightlycost = 100
assume nights = 7

$yearlycost = $nightlycost*$nights;
while ($period > 0) {
    $period = $period-1;
    $yearlyincrease = ($inflation / 100) * $yearlycost;
    $nightlyincrease = ($inflation / 100) * $nightlycost;
    $nightlycost = $nightlycost + $nightlyincrease;
    $yearlycost = ($yearlycost + $yearlyincrease) + $yearlycost;
}

Result:
Nightly Hotel Rate in 20 years: $180.61 - <?php echo round($nightlycost, 2); ?> correct

Weekly Hotel Rate in 20 years: $1264.27 - <?php echo round($nightlycost, 2) * 7; ?> correct

Total cost to you over 20 years: $988595884.74 - <?php echo round($yearlycost, 2); ?> incorrect

除了年度累计费用外,所有内容均按预期正确输出。它应该花费以前的年度成本,并加上成本+通货膨胀。

例如:第一年是700,所以第二年应该是700 + 700 + 21(21是3%,那一年的通货膨胀率)。因此,第二年累计总数为:1421。第三年将是1421 + 721(去年总数)+ 721的3%。

希望这很清楚,你可以看到我出错的地方。谢谢!

1 个答案:

答案 0 :(得分:1)

我发现很难理解代码出错的地方,但我的直觉是循环体中的最后一行应该有乘法。

基本上,你有一个0期的基本成本。然后你想计算X年后给定通货膨胀的累积成本。这个成本是(伪代码)

base = nightlycost + nights
infl = 1.03
cumulative = base + base*infl + base*infl^2 + base*infl^3 + ... + base*infl^periods

最后一个表达式可以简化为

cumulative = base*((1-infl^periods)/(1-infl))

(根据这里的公式4:http://mathworld.wolfram.com/ExponentialSumFormulas.html

示例:

$base = 100*7;
$infl = 1.03; // 3% of inflation/year

$periods = 2;
$cumulative = $base * (1-pow($infl, $periods))/(1-$infl);
print "Cumulative cost after $periods is $cumulative\n";

// Let's try with three periods.
$periods = 3;
$cumulative = $base * (1-pow($infl, $periods))/(1-$infl);
print "Cumulative cost after $periods is $cumulative\n";

输出:

Cumulative cost after 2 is 1421
Cumulative cost after 3 is 2163.63