需求
本金principal = 10000
利息intrest = 0.0325
目标2 * principal
多长时间可以本金翻倍(即本金达到目标值)
循环法算利息
代码如下:
import math
principal = 10000
INTEREST = 0.0325
TARGET = 2 * principal # 20000
# 循环法
year = 0
while principal < TARGET:
year += 1
principal *= (1 + INTEREST)
print(f"*** loop *** year: {year}, principal: {principal}")
运行结果如下:
*** loop *** year: 22, principal: 20210.698678761946
对数法算利息
计算过程如下:
# 对数法
'''
A: TARGET
r: INTEREST
P: principal
当前本金 + 利息 = P * ((1 + INTEREST) ** year)
A = 2 * P
2 * P = P * ((1 + INTEREST) ** year)
2 = (1 + INTEREST) ** year
ln(2) = ln((1 + INTEREST) ** year)
= year * ln((1 + INTEREST))
year = ln(2) / ln(1 + INTEREST)
'''
代码如下:
import math
principal = 10000
INTEREST = 0.0325
TARGET = 2 * principal # 20000
# 对数法
year = math.log(2) / math.log(1 + INTEREST) # 需要 import math
print(f"*** log *** year:{year:.3f}")
运行结果如下:
*** log *** year:21.672
感谢浏览,一起学习!