[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Calculate compound interest over time in Python

[This program calculates simple compound interest over time in Python]

This example shows how to calculate compound interest over a time period. The following calculate_compound_interest function does all of the real work.

def calculate_compound_interest(principle, interest_rate, num_years): '''Calculate compound interest over multiple years.''' results = [] for i in range(num_years + 1): results.append(principle * (1 + interest_rate) ** i); return results

This code simply loops through the years, evaluating the following compound interest formula:

balance = principle * Math.Pow(1 + interestRate, i)

This is the simple compound interest formula so interest is calculated only once per year.

Interesting tidbit: To estimate how long it will take to double your money, you can use the "Rule of 72." Divide the interest rate into 72 and the result tells you roughly how many years it will take to double your money. For example, at 7.2% it'll take about 10 years. It's a pretty decent estimate.

The following code shows how the example demonstrates the calculate_compound_interest function.

import math principle = 10_000 interest_rate = 0.05 num_years = math.ceil(72 / (interest_rate * 100)) amounts = calculate_compound_interest(principle, interest_rate, num_years) for i in range(len(amounts)): print(f'{i:<2}: ${amounts[i]:,.2f}')

This code uses the rule of 72 to calculate roughly how many years it will take to double an investment at 5% interesting. It then calls calculate_compound_interest to calculate the results over that many years. It loops through the results and displays each as a currency value.

Download the example to see all of the details.

© 2024 Rocky Mountain Computer Consulting, Inc. All rights reserved.