EXPONENTS
Java provides a method to calculate exponential values in java.lang.math
and another one which can be used with large values (too big for long) in
java.math.BigInteger. We will discuss the one defined in java.lang.math
in this lesson:
Math.pow(base, exponent);
Using this method is really straight forward and requires no further
explanation.
Ancient Algorithm to Determine Exponential Value: The following
algorithm is believed to have been developed by the ancient Egyptians
approximately 4000 years ago. It is a very efficient algorithm for calculating
an exponential value. It could well be the algorithm used by the java.lang.Math.pow()
function, but we have no way of knowing this since the java.lang.Math.pow()
function is declared native which means that the actual implementation of
the algorithm is platform dependent which means that it is written and complied
in another language (most likely C or assembly). This means that you can't
look in the SRC directory to see the code for it!
Like I said, this is a real efficient algorithm. It is also a recursive
algorithm. You will notice that the method actually calls itself. You
might try tracing the progress of this method for small input numbers like
x=2 and n=7. Tracing the progress of a recursive algorithm is a real good
way of beginning to understand recursion in general.
Assignment: You will write a command line application which
asks the user for input: a base and an exponent. It will then calculate
the value of this exponential value in three different ways:
- Using the java.lang.Math.pow() function
- Using the algorithm shown above
- Using a for loop
All input and output will be handled within a recursive function. That is,
the function will call itself until the user indicates that he or she
is finished with the application.