C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The compoundInterest method here returns the same results from the University page. So it is correct at least in that situation.
Compound Interest Formula: DePaul.eduDouble: The method returns a double. This is important because the result almost always has a fractional part.
Java program that compounds interest
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));
}
}
Output
1938.8368221341054
6191.7364223999975
7039.988712124658
7268.254992160187
And: A HashMap or array could be used. We can store either the entire result of compoundInterest or parts of it.
HashMapYearly: With interest just once a year, the money grows from 1,000 to 6,191. This is not as a high as quarterly or monthly.
Quarterly: Here the money grows to 7,039, which is nearly 1,000 more than yearly interest. You are on your way to riches.
Monthly: Here the results are even better. We end up with 7,268. But the difference is lessening.
Tip: This experiment can be applied in investing. A fund with quarterly interest (or dividends) may give a greater total return.