Below is the syntax highlighted version of Exponential.java
from §9.1 Scientific Computation.
/****************************************************************************** * Compilation: javac Exponential.java * Execution: java Exponential N * * Compute the e^x using the Taylor series: * e^x = 1 + x + x^2/2! + x^3/3! + ... * and also using Math.exp. Catastrophic cancelation * occurs if x is a large negative number. * * % java Exponential 0 * 1.0 * 1.0 * * % java Exponential 1 * 2.7182818284590455 * 2.7182818284590455 * * % java Exponential 50 * 5.184705528587075E21 * 5.184705528587072E21 * * % java Exponential -1 * 0.36787944117144245 * 0.36787944117144233 * * % java Exponential -10 * 4.539992962303128E-5 * 4.539992976248485E-5 * * % java Exponential -30 * -3.06681235635622E-5 * 9.357622968840175E-14 * * % java Exponential -50 * 11072.93338289197 * 1.9287498479639178E-22 * ******************************************************************************/ public class Exponential { public static void main(String[] args) { double x = Double.parseDouble(args[0]); double sum = 0.0; double term = 1.0; for (int i = 1; sum != sum + term; i++) { sum = sum + term; term = term * x / i; StdOut.println(i + " " + term + " " + sum); } StdOut.println(sum); StdOut.println(Math.exp(x)); } }