Python——年度投资累计值

标签 python python-2.3

我有一个程序 (futval.py),可以计算 10 年后的投资值(value)。我想修改程序,使其不再计算10年后的一次性投资的值(value),而是计算10年后每年投资的值(value)。我想在不使用累加器变量的情况下执行此操作。是否可以仅使用原始程序中存在的变量(投资、年利率、i)来执行此操作?

# futval.py
# A program to compute the value of an investment
# carried 10 years into the future

def main():
    print "This program calculates the future value",
    print "of a 10-year investment."

    investment = input("Enter the initial investment: ")
    apr = input("Enter the annual interest rate: ")

    for i in range(10):
        investment = investment * (1 + apr)

    print "The value in 10 years is:", investment

main()

如果不引入“futval”累加器变量,我无法完成程序修改。

# futval10.py
# A program to compute the value of an annual investment
# carried 10 years into the future

def main():
    print "This program calculates the future value",
    print "of a 10-year annual investment."

    investment = input("Enter the annual investment: ")
    apr = input("Enter the annual interest rate: ")

    futval = 0

    for i in range(10):
        futval = (futval + investment) * (1+apr)

    print "The value in 10 years is:", futval

main()

最佳答案

好吧,如果你尝试做一些数学计算,你就会自己找到解决方案。第一年我们有:

new_value = investment*(1 + apr)

对于第二个:

new_second_value = (new_value + investment)*(1+apr)

new_second_value = (investment*(1 + apr) + investment)*(1+apr)

等等。如果你真的尝试将这些东西相乘,你会发现 10 年后的最终值是

investment*((1+apr)**10) + investment*((1+apr)**9)+...   etc

所以你的问题的解决方案就是

print("The value in 10 years is:", sum([investment*((1+apr)**i) for i in range(1, 11)]))

编辑:不知怎的,我设法忽略了这样一个事实:我写的只是一个几何级数,所以答案更简单:

ten_years_annual_investment = investment*(apr+1)*((apr+1)**10 - 1)/apr

关于Python——年度投资累计值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275625/

相关文章:

python - 对为什么 PyGame 显示黑屏感到困惑

python - 在 Python 2.3 中按最后 N 个字符对字符串列表进行排序

python - 如何使用 python 2.3 rsh ssh

Python 2.4 subprocess.CalledProcessError 替代品

python - 以不一致的间隔切片 Python 列表

python - 查找已从 pcap 数据传输了多少数据

python - 使用 Python 2.3 通过 SSL 发送邮件

python - 如何根据具有相同列但顺序不同的另一个数据框对列重新排序

python - 在 Python 2.7 中获取(并附加)正确的文件路径