编程怎么计算复利

时间:2025-01-22 20:36:05 游戏攻略

计算复利可以使用以下公式:

\[ A = P \times (1 + r)^n \]

其中:

\( A \) 是最终金额

\( P \) 是初始本金

\( r \) 是年利率(以小数形式表示)

\( n \) 是投资期数

下面是一个使用Python实现复利计算的示例代码:

```python

def compound_interest(principal, rate, years):

"""

计算复利收益

:param principal: 本金

:param rate: 年化收益率(如 0.05 表示 5%)

:param years: 投资年限

:return: 最终金额

"""

amount = principal * (1 + rate) years

return round(amount, 2)

示例:计算10万本金,年化5%,存3年的复利

principal = 100000

rate = 0.05

years = 3

result = compound_interest(principal, rate, years)

print(f"最终金额: {result}元")

```

如果你想要一个更复杂的复利计算器,可以考虑实现一个定投复利计算器,代码如下:

```python

def investment_calculator(initial, monthly, rate, years):

"""

计算定投复利

:param initial: 初始本金

:param monthly: 月投金额

:param rate: 年化收益率

:param years: 投资年限

:return: 最终金额

"""

转换为月化收益率

monthly_rate = rate / 12

total_months = years * 12

初始本金的复利

amount = initial * (1 + monthly_rate) total_months

每月定投的复利

for month in range(1, total_months + 1):

amount += monthly

return round(amount, 2)

示例:计算每月定投1000元,年化5%,存3年的复利

initial = 1000

monthly = 1000

rate = 0.05

years = 3

result = investment_calculator(initial, monthly, rate, years)

print(f"最终金额: {result}元")

```

这些代码示例展示了如何使用Python计算复利,你可以根据自己的需求进行调整和扩展。