Source code for Exp.java

What follows is the highlighted source code with comments. You can also download this file directly: Exp.java.

```/*
* This work by W. Patrick Hooper is free of known copyright restrictions.
* The work is in the public domain.
*
* Author's website: <a href="http://wphooper.com">http://wphooper.com</a>.
*/

/**
*
* @author Pat Hooper
*/
public class Exp {

/** return n factorial. */
public static int factorial(int n) {
// We will compute n factorial via the formula
// n!=1*2*3*4*5*...
int factorial=1;

// iterate over the values i=1,...,n.
for (int i=1; i<=n; i++) {
// multiply factorial by each value of i.
factorial=factorial * i;
}

return factorial;
}

/** return x^n. */
public static double power(double x, int n) {
// This will be what we return.
double ret=1;

// iterate over the values i=1,...,n.
for (int i=1; i<=n; i++) {
// multiply factorial by each value of i.
ret = ret * x;
}

return ret;
}

/** This program takes one real number parameter and outputs its
* exponential.
*/
public static void main(String[] args) {
// read a real number from the first argument
double x=Double.parseDouble(args[0]);

// We will print out
// e^x = 1 + x + x^2/2 + x^3/6 + x^4/24 + ... + x^9/9!

double sum=0;
// iterate over the values i=0,1,...,14
for (int i=0; i<15; i++) {
sum=sum+power(x,i)/factorial(i);
}

System.out.println("exp("+x+") = "+sum);

// This uses the java.lang.Math class to compute exp(x).
System.out.println("A second opinion: exp("+x+") = "+Math.exp(x));
}

}
```
HOOPER >>>>> JAVA TUTORIAL