Skip to content

.math

Learn about the different ways to manipulate data using .math

  • Lesson
  • 2 min read
  • 14 of 15 in this chapter

How does .math help?

Special abilities of the .math function include square rooting numbers, generating random numbers, Finding the highest number in a group, finding the lowest number in a group, and finding the absolute value of a number. These functions help set parameters as well as helping with data manipulation.

.math functions

One special .math function is the ability to randomize numbers. For example…

Java
int variablename = (int)(Math.random()*101);

This function assigns the int variable name to a value that is from 0 to 100. (int) tells the math.random function to return an int, 'Math.random()' always returns a value between 0 and 1, We multiply this number to yield a number larger than that

Let's say we want to return a number between 20 and 40. The code would look like this…

Java
int variablename = ((int)(Math.random()*20)+21);

Another two math functions are the minimum and maximum. Let us take a look at the code for finding a minimum value…

Java
int variablename = Math.min(20, 40);
/*this will return 20 for 'int variablename' , because 20 is the smaller number*/

Let's take a look at how we can find the maximum value.

Java
int variablename = Math.max(20,40);
//this will return 40 for 'int variablename' , because 40 is the larger number.

There are more functions that .math can handle…

Java
Math.abs(-20); //this returns the absolute value of -20(which is 20).
Math.sqrt(25); //this returns the square root of 25(5), or any number. 
Math.PI; //this returns PI