Home
Map
Compound InterestImplement the compound interest formula, which tells how money compounds as time passes.
Java
This page was last reviewed on May 23, 2023.
Compound interest. Because of interest money compounds as time passes—we start earning interest on our interest. This can be computed with a Java method.
Monthly, quarterly, yearly. We can compound interest based on different schedules. And with a compound interest method, we can see the difference between these schedules.
A method. In researching compound interest, I found the formula on a university's page. I translated the formula into a Java method. We use addition, division, multiplication, and Math.pow.
Math
Result The compoundInterest method here returns the same results from the university page. So it is correct at least in that situation.
Tip The compoundInterest method returns a double. This is important because the result almost always has a fractional part.
public class Program { static double compoundInterest(double principal, double interestRate, int timesPerYear, double years) { // (1 + r/n) double body = 1 + (interestRate / timesPerYear); // nt double exponent = timesPerYear * years; // P(1 + r/n)^nt return principal * Math.pow(body, exponent); } public static void main(String[] args) { // Compound interest for four years quarterly. System.out.println(compoundInterest(1500, 0.043, 4, 6)); System.out.println(); // Compare monthly, quarterly, and yearly interest for 10 years. System.out.println(compoundInterest(1000, 0.2, 1, 10)); System.out.println(compoundInterest(1000, 0.2, 4, 10)); System.out.println(compoundInterest(1000, 0.2, 12, 10)); } }
1938.8368221341054 6191.7364223999975 7039.988712124658 7268.254992160187
Memoization. As with other mathematical computations, compound interest is a good opportunity to store and reuse results. This is called memoization.
And A HashMap or array could be used. We can store either the entire result of compoundInterest or parts of it.
HashMap
Computing interest. In volatile markets, interest rates may seem less important. But the fundamental way interest compounds upon itself is core to all simulations.
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.