我有一个程序(futval.py),可以在10年后计算投资价值。我要修改程序,以便与其计算10年后的一次性投资价值,不如计算10年后的年度投资价值。我想这样做而不使用累加器变量。是否可以仅使用原始程序中存在的变量(投资,apr,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 - Python-年度投资的累计值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38275625/