© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_4

4. Math

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

(Or Maths, if you prefer.)

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 called 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, multiplying and dividing? Luckily these symbols are the same in virtually every programming language: * and /.
1   int legs = zombies * 2;
2   int halfZombies = zombies / 2;
Numbers written in Java are of type int by default. But what if we want to deal with fractions that are not whole numbers?
1   float oneThirdZombies = zombies / 3.0f;

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

This is where math starts to get tricky. To engage float division (remember from Chapter 3, 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, 32 / 3 is 10.

Modulo
You don’t really need to understand Modulo, but if you want to, keep reading. Imagine that you and three buddies want to attack a group of zombies. You have to know how many each of you has to kill, so that each of you kills an equal number of zombies. For this you do integer division.
1   int numberToKill = zombies / 4;
But you want to know how many will be left over. For this, you require modulo (%):
1   int leftOverZombies = zombies % 4;

This gives you the remainder of dividing zombies by four.

More Complex Math

If you want to do anything other than add, subtract, multiply, divide, and modulo, you will have to use the java.lang.Math class. The Math class is part of the Java Development Kit (JDK) which is always available as part of core Java. There are many such classes which we will encounter as we go.

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, as follows:
1   double nextYearEstimate = Math.pow(numberOfZombies, 2.0d);
This type of method is called a static method since it does not require an object instance. (Don’t worry, you’ll learn more about this later.) Here’s a summary of the most commonly used methods in java.lang.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

../images/435475_2_En_4_Chapter/435475_2_En_4_Figa_HTML.jpg For a list of all the methods in Math, see the Java docs.1

../images/435475_2_En_4_Chapter/435475_2_En_4_Figb_HTML.jpg 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 look at this animation2 referenced in the footnote at the end of this page and keep watching it until you understand the sine wave.

Random Numbers

The easiest way to create a random number is to use 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), use the following:
1   int roll = (int) (Math.random() * 6);

This would result in a random number from 0 to 5. We could then add one to get the numbers 1 to 6. We need to have (int) here to convert the double returned from random() to an int—this is called casting.

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 (Math.floor returns the largest integer less than or equal to a given number):
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 must first create a new Random object, then you can use it to create random numbers, as follows:
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!

../images/435475_2_En_4_Chapter/435475_2_En_4_Figc_HTML.jpg Seeds If you create a Random with a seed (e.g., new Random(1234)), it will always generate the same sequence of random numbers when given the same seed.

Summary

In this chapter, you learned how to program math, such as
  • How to add, subtract, multiply, divide, and modulo

  • Using the Math library in Java

  • Creating random numbers

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset