2.3 The Math Class
The Java API provides a class named Math, which contains number of static methods that compute various common mathematical functions. A static method can be called using the name of the class containing the method.
The pow() Method
The class Math contains a method pow, which is used to calculate xy in a program. Here is an example of how the pow method is used:
result = Math.pow(2, 3);
Math.pow(2,3) computes 8.0. This statement is equivalent to the following algebraic statement
result = 23
The sqrt() Method
The Math.sqrt method accepts a value as its argument and returns the square root of the value. Here is an example of how the method is used:
result = Math.sqrt(16.0);
In this example the value 16.0 is passed as an argument to the sqrt method. The method then return the square root of 16.0, which is assigned to the result variable.
/**
* This program demonstrate
* Class Math methods.
*/
public class MathMethodsDemo
{
public static void main(String[] args)
{
// To hold data.
double x, y, result;
x = 16;
y = 2.0;
// Get the power.
result = Math.pow(x, y);
// Display result.
System.out.println(result);
// Get square root.
result = Math.sqrt(x);
// Display result.
System.out.println(result);
}
}
Output :
256.0
4.0
4.0
You can find others Math Class methods :http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
No comments:
Post a Comment