Concept

How can a Java program compute a logarithm in an arbitrary base?

ComputerScienceOne / Computing a Logarithm

"The logarithm of x is the exponent that some base must be raised to get x. The most common logarithm is the natural logarithm, ln(x), which is base e = 2.71828.... But logarithms can be in any base b > 1. What if we wanted to compute log2(x) or logπ(x)? Let’s write a program that will prompt the user for a number x and a base b and computes logb(x). Arbitrary bases can be computed using the change of base formula: logb(x) = loga(x) / loga(b). If we can compute some base a, then we can compute any base b. Fortunately we have such a solution. Recall that the standard library provides a function to compute the natural logarithm, Math.log(). This is one of the fundamentals of problem solving: if a solution already exists, use it. In this case, a solution exists for a different, but similar problem—computing the natural logarithm—but we can adapt the solution using the change of base formula. In particular, if we have variables b (base) and x, we can compute logb(x) using Math.log(x) / Math.log(b). However, we have a problem similar to the examples in the previous section. The user could enter invalid values such as b = -10 or x = -2.54; logarithms are undefined for non-positive values in any base. We want to ensure that b > 1 and x > 0. With conditionals, we can now do this. Once we have read in the input from the user we can make a check for good input using an if statement: if(x <= 0 || b <= 1) { System.out.println(\"Error: bad input!\"); System.exit(1); } This code has something new: System.exit(1). The exit() function immediately terminates the program regardless of the rest of the code that may remain. The argument passed to exit() is an integer that represents an error code. The convention is that zero indicates “no error” while non-zero values indicate some error. This is a simple way of performing error handling: if the user provides bad input, we inform them and quit the program, forcing them to run it again and provide good input. By prematurely terminating the program we avoid any illegal operation that would give a bad result. Alternatively, we could have split the conditions into two statements and given a more descriptive error message. We use this design in the full program."

Related Ideas

How can a Java program compute a logarithm in an arbitrary base? | ComputerScienceOne | Bifalgorithm | Bifalgorithm