Thursday, 26 April 2018

Core Java: Mathematical Methods

JDK provides many common-used Mathematical methods in a class called Math. The signatures of some of these methods are:
 
double Math.pow(double x, double y) // returns x raises to power of y
double Math.sqrt(double x)          // returns the square root of x
double Math.random()                // returns a random number in [0.0, 1.0)
double Math.sin()
double Math.cos()
The Math class also provide two constants:
Math.PI   // 3.141592653589793
Math.E    // 2.718281828459045
 
To check all the available methods, open JDK API documentation ⇒ select package "java.lang" ⇒ select class "Math" ⇒ choose method.
For examples,
 
int secretNumber = (int)Math.random()*100;  // Generate a random int between 0 and 99

double radius = 5.5;
double area = radius*radius*Math.PI;
area = Math.pow(radius, 2)*Math.PI;         // Not as efficient as above

int x1 = 1, y1 = 1, x2 = 2, y2 = 2;
double distance = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
int dx = x2 - x1;
int dy = y2 - y1;
distance = Math.sqrt(dx*dx + dy*dy);        // Slightly more efficient

No comments:

Post a Comment

Please write your view and suggestion....