4. Math

(or “Maths” if you prefer)

4.1 Adding, subtracting, etc.

Your friend Bob was just bitten by a zombie, but escaped alive. Unfortunately there is now one more zombie to worry about:

1 zombies = zombies + 1;

There’s a shorter way to write the same thing (and we are pressed for time here; the zombies are coming):

1 zombies += 1;

Actually, there’s an even shorter way to write this, and it’s call the increment operator:

1 zombies++;

Luckily, there’s also a decrement operator (to use when we kill a zombie):

1 zombie--;

Adding and subtracting are easy enough, but what about their cousins, multiply and divide? Luckily these symbols are the same in virtually every programming language: * and /

1 int legs = zombies * 2;
2 int halfZomies = zombies / 2;

Numbers written in Java are of type int by default. But what if we want to deal with fractions (like one third)?

1 float oneThirdZombies = zombies / 3.0f;

No, 3.0f is not a typo. The “f” makes 3 a float. You can use lower or upper-case letters (D means double, F means float, and L means long).

This is where math starts to get tricky. In order to engage float division (remember, float is an imprecise number) we need 3 to be a float. If we instead wrote “zombies / 3” this would result in integer division and the remainder would be lost. For example, 33 / 3 is 10.

Modulo

You don’t really need to understand Modulo, but if you want to, keep reading. Imagine you and three budies want to attack a group of zombies. You need to know how many each of you need to kill so that each of you kill an equal number of zombies. For this you do the integer division:

1 int numberToKill = zombies / 4;

But you want to know how many will be left over. For this, you need modulo (%):

1 int leftOverZombies = zombies % 4;

This gives you the remainder of dividing zombies by four.

4.2 More complex Math

If you want to do anything other than add, substract, multiply, divide, and modulo, you will need to use the java.util.Math class.

Let’s say you want to raise a number to the power of 2. For example, if you want to estimate the exponentially increasing number of zombies:

1 double nextYearEstimate = Math.pow(numberOfZombies, 2.0d);

This type of method is called a static method (don’t worry we’ll learn more about these later).

Here’s a summary of the most commonly used methods in java.util.Math:

  • abs: Returns the absolute value of a value.
  • min: The minimum of two numbers.
  • max: The maximum of two numbers.
  • pow: Returns the value of the first argument raised to the power of the second argument.
  • sqrt: Returns the correctly rounded positive square root of a double value.
  • cos: Returns the trigonometric cosine of an angle.
  • sin: Returns the trigonometric sine of an angle.
  • tan: Returns the trigonometric tangent of an angle.

For a list of all the methods in Math, see the Java docs.

Sine

If you’re unfamiliar with sine and cosine, they are very useful whenever you want to draw a circle for example. If you’re on your computer right now, and want to learn more about sine and cosine, please go look at this animation and keep watching it until you understand the sine wave.

4.3 Random numbers

The easiest way to create a random number is using the Math.random() method.

The random() method returns a double value greater than or equal to zero and less than one.

For example, to simulate a roll of the dice (to determine who gets to deal with the next wave of zombies):

1 int roll = (int) (Math.random() * 6);

This would result in a random number from 0 to 5.

JavaScript also has a Math.random() method. For example, to get a random integer between min (included) and max (excluded) you would do the following:

1 Math.floor(Math.random() * (max - min)) + min;

However, if you want to create lots of random numbers in Java, it’s better to use the java.util.Random class instead. It has several different methods for creating random numbers, including:

  • nextInt(int n): A random number from 0 to n (not including n).
  • nextInt(): A random number uniformly distributed across all possible int values.
  • nextLong(): Same as nextInt() but for long.
  • nextFloat(): Same as nextInt() but for float.
  • nextDouble(): Same as nextInt() but for double.
  • nextBoolean(): True or false.
  • nextBytes(byte[] bytes): Fills the given byte array with random bytes.

You first need to create a new Random object, then you can use it to create random numbers:

1 Random randy = new Random();
2 int roll6 = randy.nextInt(6) + 1; // 1 to 6
3 int roll12 = randy.nextInt(12) + 1; // 1 to 12

Now you can create random numbers and do math with them. Hurray!

Seeds

If you create a Random with a seed (eg. new Random(1234)), it will always generate the same sequence of random numbers when given the same seed.

4.4 Summary

In this chapter we learned how to program math, such as:

  • How to add, substract, multiply, divide, and modulo.
  • Using the Math library in Java.
  • Creating random numbers.