1. Math Functions
How to use functions
Functions are blocks of code that can be written once and run from various parts of your program. In fact, System.out.println() was a function. You can identify that something is a function by the fact that it uses parenthesis in Java. To use a function, type the function name, and supply inputs:
public class MyProgram { public static void main(String[] args) { //Run the println function with "Hello World" as an input System.out.println("Hello World"); Math.abs(-5); //Runs the Math.abs function with the input -5 //Notice that this does not output anything } }
Using functions that return values
Many functions return a value, which means that the function can be used as part of an expression. Just like 1+2 is the int 3, Math.abs(-3) performs absolute value and evaluates to the int 3. Thus, you can use Math.abs() as part of a more complex expression:
public class MyProgram { public static void main(String[] args) { int x = -5; int positiveTimesTen = Math.abs(x)*10; System.out.println(positiveTimesTen); //prints 50 System.out.println(Math.abs(-42)); //prints 42 } }
Common Math functions
Math.abs
is absolute value
Math.ceil
rounds to the more positive integer
Math.floor
rounds to the more negative integer
Math.round
rounds to the closest integer
Math.sqrt
takes one number and returns the square root
Math.pow
takes two doubles, and returns the first to the power of the second
Math.log10
takes one double, and returns the logarithm of that number in base 10
Math.log
takes one double, and returns the logarithm of that number in base e
Trig functions
Math.sin
returns the sine of the double argument. The argument should be in radians, not degrees.
Math.cos
returns the cosine of the double argument. The argument should be in radians, not degrees.
Math.tan
returns the tangent of the double argument. The argument should be in radians, not degrees.
Math.asin
returns the arc sine (inverse function) of the double argument. The return value is between -PI/2 and PI/2 radians.
Math.acos
returns the arc cosine (inverse function) of the double argument. The return value is between 0 and PI radians.
Math.atan
returns the arc tangent (inverse function) of the double argument. The return value is between -PI/2 and PI/2 radians.
Math.atan2
returns the arc tangent (inverse function) of the two arguments, y and x. This will return an angle that spans all of 2PI, which is useful for getting objects to point at each other
Math.toDegrees
converts an angle in radians (the argument) to degrees (the return value)
Math.toRadians
converts an angle in degrees (the argument) to radians (the return value)
Math constants
The doubles Math.PI and Math.E can be used as approximate values of pi and e.