If you invest $2000 at 6% compounded monthly, how long will it take the account to double in value?
# Ch 9.9 - solving for TIME. Each of the three formulas has the unknown stuck in
# an exponent, so each one ends with a logarithm.
from math import log10
K = 12
def years_to_grow(P0, goal, r, k=K): # compound interest
return log10(goal / P0) / (k * log10(1 + r / k))
def years_to_save(d, goal, r, k=K): # savings annuity
return log10(goal * (r / k) / d + 1) / (k * log10(1 + r / k))
def years_to_repay(P0, d, r, k=K): # loan or credit card
i = r / k
if d <= P0 * i:
return None # the payment never touches the balance
return -log10(1 - P0 * i / d) / (k * log10(1 + i))
P0, APR, GOAL = 2000, 0.06, 4000 # TRY IT: GOAL = 8000 (quadruple)
n = years_to_grow(P0, GOAL, APR)
print(f"1) ${P0:,} at {100 * APR:g}% compounded monthly reaches ${GOAL:,}")
print(f" {GOAL} = {P0}(1 + {APR}/{K})^({K}N) -> {GOAL / P0:g} = {1 + APR / K:.6g}^({K}N)")
print(f" N = log({GOAL / P0:g}) / ({K} log({1 + APR / K:.6g})) = {n:.3f} years")
print(f" and quadrupling takes {years_to_grow(P0, 4 * P0, APR):.3f} years, "
"exactly twice as long - doublings stack\n")
D, S_APR, S_GOAL = 100, 0.03, 10000
print(f"2) saving ${D}/month at {100 * S_APR:g}% reaches ${S_GOAL:,} in "
f"{years_to_save(D, S_GOAL, S_APR):.3f} years")
for goal in (5000, 10000, 20000, 40000):
print(f" ${goal:>6,} takes {years_to_save(D, goal, S_APR):>6.2f} years")
print(" Doubling the goal takes LESS than twice as long: the interest is")
print(" compounding the whole time you save.\n")
LOAN, C_APR = 1000, 0.12
print(f"3) a ${LOAN:,} laptop on a credit card at {100 * C_APR:g}%:")
print(" monthly payment time to clear it total paid total interest")
for pay in (10, 15, 20, 25, 30, 50, 100):
t = years_to_repay(LOAN, pay, C_APR)
if t is None:
owed = LOAN * C_APR / K
print(f" ${pay:>14} never - the interest alone is ${owed:,.2f} a month")
else:
total = pay * K * t
print(f" ${pay:>14} {t:>13.2f} yr {total:>10,.2f} {total - LOAN:>13,.2f}")
print(f"\n The book's case, $30 a month, takes "
f"{years_to_repay(LOAN, 30, C_APR):.3f} years.")
print(" Look at the $10 row. Below the interest line, time to repay is INFINITE.")