Mathematical operations in Java

In this section, we'll be looking at performing common mathematical operations in Java. In particular, we'll be focussing mainly on floating point operations. If you're unfamiliar with the term floating point and you're not too fussy, then for now, just read the term "floating point number" as meaning "real number" (and of course a real number is a "non-whole number", e.g. 4.5, -34.11 etc as opposed to whole numbers such as 4 and -34). Floating point format is the format most commonly used in computing to store and calcualte with real numbers; the format and techniques used with it actually have some implications in terms of the precision of calculations.

In terms of their functionality, most operations fairly boringly do "what they say on the tin". So we won't focus a great deal on what, for example, Math.cos() actually does: if you're familiar with the cosine operation, the functionality of the method should be fairly obvious. On the other hand, we will focus on various non-obvious issues, in particular performance of such operations.

The basics: mathematical operations if you're not too fussy

That said, here is a "quick start guide" to performing mathematical operations in Java:

Performance of floating point operations

In general, operations that you write in Java that act on floating point variables— either via the basic operations or via the Math API— translate directly into machine instructions. This means that depending on your processor and the sequence of operations you're performing, you can generally count on hundreds of millions of floating point calculations per second. And in many situations, performance will be significantly better. Many processors, notably the Intel Pentium series, can generally "burst" at one floating point addition or subtraction per two clock cycles under the right circumstances, meaning potentially up to billions of these operations per second.

On the following pages we look at: