Fix this code: compound interest

In 1494, Luca Pacioli published his "Summa de arithmetica", widely regarded as the first accounting book in history, because it's the first known published description of Double-entry bookkeeping.

Pacioli's book also describes Compound interest, although it was known for a long time already. Compound interest is the aggregate addition of interest to an original sum, over multiple periods of time. For example, let's assume we start with an initial investment of $1,000, and a monthly interest rate of 10%. We'll deposit our money for 5 months. How much is the total at the end of those 5 months? You might be tempted to do: intial_investment + (interest * duration), which is $1,000 * (10% * 5 months) == $1,000 * 50% == $1,5000. But that would be incorrect: the correct result is $1,610.51. This is an example of compound interest.

To understand it, let's walk it step by step:

  • Month 0: Initial investment $1,000
  • Month 1: Starting with $1,000 (initial). Interest: 10% of $1,000 => $100. Total: $1,000 + $100 => $1,100
  • Month 2: Starting with $1,100 (prev month). Interest: 10% of $1,100 => $110. Total: $1,100 + $110 => $1,210
  • Month 3: Starting with $1,210 (prev month). Interest: 10% of $1,210 => $121. Total: $1,210 + $121 => $1,331
  • Month 4: Starting with $1,331 (prev month). Interest: 10% of $1,331 => $133.1. Total: $1,331 + $133.1 => $1,464.1
  • Month 5: Starting with $1,464.1 (prev month). Interest: 10% of $1,464.1 => $146.41. Total: $1,464.1 + $146.41 => $1,610.51

As you can see, the interest is building on top of the available investment + the profits generated by previous months interest.

Test Cases

test compound interest - Run Test

def test_compound_interest():
    assert round(compound_interest_result(1000, 10, 5), 2) == 1610.51

Solution 1

def compound_interest_result(initial_investment, interest_percentage, num_periods):
    return initial_investment * ((1 + interest_percentage / 100.0) ** num_periods)

Solution 2

def compound_interest_result(initial_investment, interest_percentage, num_periods):
    total = initial_investment
    count = 0
    while count < num_periods:
        total += total * .1
        count += 1
    return total
def compound_interest_result(initial_investment, interest_percentage, num_periods): total = initial_investment count = 0 while count < num_periods: total += initial_investment * .1 count += 1 return total # Use the "Run Code" button to try your code. This will not affect your solution or tests: print(round(compound_interest_result(1000, 10, 5), 2))