Below is the syntax highlighted version of CompoundInterest.java
from §9.1 Scientific Computation.
/****************************************************************************** * Compilation: javac CompountInterest.java * Execution: java CompoundInterest a r n * * Invest a pennies at annual interest rate r%, where interest * is compounded n times per tear. * * % java CompoundInterest 100000 5 365 * Exact: 105126.74964674473 * Round to nearest penny: 105110 * Round down to nearest penny: 104940 * ******************************************************************************/ public class CompoundInterest { public static void main(String[] args) { int a = Integer.parseInt(args[0]); // amount in pennies int r = Integer.parseInt(args[1]); // annual interest rate in percent int n = Integer.parseInt(args[2]); // compounding periods per year // compute using double precision arithmetic double amount1 = a * Math.pow(1 + r / 100.0 / n, n); // round to nearest penny long amount2 = a; for (int i = 0; i < n; i++) amount2 = Math.round(amount2 * (1 + r / 100.0 / n)); // round down to nearest penny long amount3 = a; for (int i = 0; i < n; i++) amount3 = (long) (amount3 * (1 + r / 100.0 / n)); StdOut.println("Exact: " + amount1); StdOut.println("Round to nearest penny: " + amount2); StdOut.println("Round down to nearest penny: " + amount3); } }