Wednesday, 24 December 2008

Basic Mathematics in Java

The public final class Math contains all the basic numerical functions and constants.

Math.E (the base of the natural logarithms), Math.PI (ratio of circumference of a circle to its diameter).

Math.ceil, Math.floor do the expected operations, mapping doubles to ints.

Math.random, when first called creates a new PRN generator (thread-safe singleton, java.util.Random). If numerous threads are involved, multiple PRN generators ought to be instantiated. Returns a double value in the range [0,1).

Beware of the int division wall. This basically means 1/5 returns 0 since int/int returns floor(int). To avoid the "int division wall" cast to double, use decimals or write 1.0/5 to get result of division as a double.

No comments:

Blog Archive