Math Library class

Download Report

Transcript Math Library class

CS 115
OBJECT ORIENTED PROGRAMMING I
LECTURE 4 part 3
GEORGE KOUTSOGIANNAKIS
Topic
• Math Library Class.
About the Math Library class
• The Math class provides static constants and static
methods for performing common calculations.
• The Math class is in the java.lang package, so it does
not need to be imported
• The methods of this class are all static.
– A static method is a method that can be invoked (called) by
using the name of the class that it belongs and the .
Operator
– For example to call the method random ( a method that
produces random numbers) we use
Math.random();
3
Math Library class
• Checking the API documentation for random
we see the description:
public static double random() Returns a
double value with a positive sign, greater than
or equal to 0.0 and less than 1.0. Returned
values are chosen pseudorandomly with
(approximately) uniform distribution from that
range.
4
Math Library class
Two static constants
PI - the value of pi
E - the base of the natural logarithm
Example:
System.out.println( Math.PI );
System.out.println( Math.E );
The output is:
3.141592653589793
2.718281828459045
5
Sample Methods of the Math Class
Return type
dataTypeOfArg
double
Method name and argument list
abs( dataType arg )
returns the absolute value of the argument
arg, which can be a double, float, int or long.
log( double a )
double
returns the natural logarithm (in base e) of
its argument.
sqrt( double a )
returns the positive square root of a
pow( double base, double exp )
double
returns the value of base raised to the
power exp
The Math min/max Methods
Return type
Method name and argument list
dataTypeOfArgs
min( dataType a, dataType b )
returns the smaller of the two arguments. The
arguments can be doubles, floats, ints, or longs.
dataTypeOfArgs
max( dataType a, dataType b )
returns the larger of the two arguments. The
arguments can be doubles, floats, ints, or longs.
Find smallest of three numbers:
int smaller = Math.min( num1, num2 );
int smallest = Math.min( smaller, num3 );
See Example 3.16 in Text -MathMinMaxMethods.java
Another Example program using the
Math Class
import java.util.Scanner;
public class MyMathClass
{
public static void main(String[] args)
{
double exponent=4.0;
double result=0.00;
double sqrt=0.00;
result=Math.pow(10, exponent);
sqrt=Math.sqrt(exponent);
System.out.println("The result is"+“ "+result);
System.out.println("The square root of the number”+” “++exponent+” ”+” is"+” “+sqrt);
}
}
8