年度投资的未来价值

2024-04-20 14:46:27 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你有一个投资计划,你在每年年初投资一定的固定金额。计算上年末投资总额。投入将是每年的投资额、利率和投资年限。

这个程序计算未来的价值 每年固定的投资。 输入年投资:200 输入年利率:.06 输入年份:12 12年价值:3576.427533818945

我试过一些不同的东西,比如下面,但它没有给我3576.42,它只给了我400美元。有什么想法吗?

principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
    principal = principal * (1+apr)
print("The value in 12 years is: ", principal)

Tags: theinprincipalinputeval金额apr计划
3条回答

如果是年度投资,你应该每年加上:

yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))

total = 0
for i in range(years):
    total += yearly
    total *= 1 + apr

print("The value in 12 years is: ", total)

通过你的输入,这个输出

('The value in 12 years is: ', 3576.427533818945)

更新:回答评论中的问题,以澄清发生了什么:

1)你可以用int()来表示yearly,得到同样的答案,如果你总是投资一整笔货币,那就没问题了。例如,使用float也同样有效,但也允许数量为199.99

2)+=*=是方便的简写:total += yearly表示total = total + yearly。它有点容易打字,但更重要的是,它更清楚地表达了意义。我是这样读的

for i in range(years): # For each year
    total += yearly    # Grow the total by adding the yearly investment to it
    total *= 1 + apr   # Grow the total by multiplying it by (1 + apr)

更长的形式只是不太清楚:

for i in range(years):        # For each year
    total = total + yearly    # Add total and yearly and assign that to total
    total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total

正如评论中所建议的,您不应该在这里使用eval()。(有关eval的更多信息,请参见in the Python Docs)。--相反,在适用的情况下,将代码更改为使用float()int(),如下所示。

另外,您的print()语句打印出了括号和逗号,我想您不需要。我在下面的代码中清理了它,但是如果你想要的是你可以随意放回去的东西。

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

# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))

for i in range(years):
    principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal

它可以通过分析来实现:

&13;
&13;
"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)

类似地,如果你试图计算出你需要投资的金额,从而得到某个数字,你可以:

&13;
&13;
pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1) 
pmt(1000000, 0.09, 20, 0)

相关问题 更多 >