import java.util.Scanner; /* Java class with a method that performs exponentiation. ** The intent is for students to work with the Java's assert statement ** and the loop invariant concept. */ public class Exponentiate { /* Returns (an approximation of) x raised to the nth power. ** pre: n >= 0 */ public static double xToN(double x, int n) { final double X = x; // Store original value of x in X final int N = n; // Store original value of n in N double f = ??; // missing initialization of f System.out.printf("x:%f, n:%d, f:%f\n", x, n ,f); assert loopInvariant(X, N, x, n, f); // loop invariant: X^N = x^n * f while (n != 0) { // missing loop body System.out.printf("x:%f, n:%d, f:%f\n", x, n, f); assert loopInvariant(X, N, x, n, f); } // At this point, n = 0 and so x^n = 1, which makes x^n * f = f. return f; } /* Returns true iff X^N and x^n * f are "almost equal", as judged ** by the almostEqual() method. */ private static boolean loopInvariant(double X, int N, double x, int n, double f) { return almostEqual(Math.pow(X,N), Math.pow(x,n)*f); } /* Returns true iff the two given real numbers are "almost equal", ** as measured by the "relative error" between them. */ private static boolean almostEqual(double u, double v) { double larger = Math.max(u,v); return Math.abs(u-v) / larger <= 0.0001; } /* For testing the xToN() method. The user is invited to enter a base x ** (which can be any real number) and an exponent n (necessarily a ** nonnegative integer). It uses both Math.pow() and xToN() to ** compute x^n and displays the results. */ public static void main(String[] args) { System.out.println("Welcome to the Exponentiate program.\n"); Scanner input = new Scanner(System.in); System.out.print("Enter x: "); double x = input.nextDouble(); input.nextLine(); System.out.print("Enter (nonnegative) exponent n: "); int n = input.nextInt(); input.nextLine(); System.out.println(); System.out.printf("\nYour method says %f to the %dth power = %f\n", x, n, xToN(x,n)); System.out.printf("Math.pow() says %f to the %dth power = %f\n", x, n, Math.pow(x,n)); System.out.println("\nGoodbye."); } }