Compound interest is calculated using the formula:
A = P * (1 + r/n)^(nt)
where:
A
is the amount of money accumulated after n years, including interest.P
is the principal amount (the initial amount of money).r
is the annual interest rate (in decimal).n
is the number of times that interest is compounded per year.t
is the time the money is invested for in years.
Python Code Example
# Function to calculate compound interest
def calculate_compound_interest(principal, rate, times_compounded, years):
# Convert annual rate from percentage to decimal
rate_decimal = rate / 100
# Calculate compound interest
amount = principal * (1 + rate_decimal / times_compounded) ** (times_compounded * years)
return amount
# Example usage
principal = 1000 # Initial amount
annual_rate = 5 # Annual interest rate in percentage
times_compounded = 4 # Quarterly compounding
years = 10 # Investment duration in years
# Calculate the final amount
final_amount = calculate_compound_interest(principal, annual_rate, times_compounded, years)
# Output the result
print(f"The amount after {years} years is: ${final_amount:.2f}")
Explanation
In this code:
- The
calculate_compound_interest
function takes the principal, annual interest rate, number of times compounded per year, and number of years as parameters. - The annual interest rate is converted from a percentage to a decimal.
- The compound interest is calculated using the formula and returned.
- In the example, we calculate the amount for a principal of $1000 with an annual interest rate of 5%, compounded quarterly, over 10 years.
Conclusion
The provided Python program effectively calculates compound interest using a straightforward formula. You can adjust the principal, rate, compounding frequency, and duration to fit different scenarios.