Home
Map
Compound InterestCompute compound interest using a formula. Compound on different time schedules.
Python
This page was last reviewed on May 23, 2023.
Compound interest. There is a time value of money. This is interest. In compound interest, an investor earns interest on top of the interest already earned.
The compound interest formula is well-known—it is an exponential function. In Python the pow method is needed. We translate this formula into a Python def.
Numbers
Our program. The compound_interest method computes the total value of the money (principal) after interest is paid. We specify the rate (the interest rate, expressed as a percentage).
Argument 1 The principal argument is the amount of money we begin with. Here we have 1500 money units (such as dollars).
Argument 2 This is the interest rate. For an interest rate of 4.3%, we can pass 0.043.
Argument 3 The times_per_year argument indicates yearly (1), quarterly (4) or monthly (12) interest.
Argument 4 This final argument to compound_interest tells us how many years we compound interest. Thinking long-term is important.
def compound_interest(principal, rate, times_per_year, years): # (1 + r/n) body = 1 + (rate / times_per_year) # nt exponent = times_per_year * years # P(1 + r/n)^nt return principal * pow(body, exponent) # Compute 0.43% quarterly compound interest for 6 years. result = compound_interest(1500, 0.043, 4, 6) # Write result. print(result) print() # Compute 20% compound interest yearly, quarterly and monthly. print(compound_interest(1000, 0.2, 1, 10)) print(compound_interest(1000, 0.2, 4, 10)) print(compound_interest(1000, 0.2, 12, 10))
1938.8368221341054 6191.7364223999975 7039.988712124658 7268.254992160187
Verification. I could write all sorts of incorrect code on this website, but this would not do anyone any good. The result to the first call (above) matches Wikipedia's example.
Yearly, quarterly, monthly. In the last three calls to compound_interest above, we compare how the final amount of money changes based on how often interest is paid.
And Monthly and quarterly interest accumulates much faster than yearly interest. So this metric is important in an investment.
Tip This comparison can help us judge certain investments. For example, bonds may pay monthly, but dividend stocks quarterly.
The concept of compound interest is behind much of the world's capital markets. It motivates investment. Compound interest is a powerful generator of wealth.
C#VB.NETPythonGoJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 23, 2023 (edit).
Home
Changes
© 2007-2023 Sam Allen.