// This is a class that provides examples of various mathematical algorithms, // either ones not available in Java's "Math" class, or ones where the // algorithms are interesting to look at even if the basic function is // already available elsewhere. // History: // Sept. 2003 -- Created by Doug Baldwin public class MoreMath { // powerOf2 -- raise 2 to the nth power. // Precondition: n >= 0 public static double powerOf2( int n ) { if (n == 0 ) { return 1.0; } else if ( n >= 1 ) { return 2.0 * powerOf2( n-1 ); } else { return ( 1.0 / 2.0 ) * powerOf2( n+1 ); } } // The main method exercises/demonstrates the other methods. public static void main( String args[] ) { // The 2^n method: final int n = -4; // The power to raise 2 to System.out.println( "2 ^ " + n + " = " + powerOf2(n) ); } }