0% found this document useful (0 votes)
17 views13 pages

Math Class API Java

The document provides an overview of the Math class in Java, detailing various mathematical functions such as trigonometric, logarithmic, and rounding methods. It explains how to use these functions, including examples and the significance of constants like PI and E. Additionally, it highlights the differences between rounding methods (round, ceil, floor) and their appropriate use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

Math Class API Java

The document provides an overview of the Math class in Java, detailing various mathematical functions such as trigonometric, logarithmic, and rounding methods. It explains how to use these functions, including examples and the significance of constants like PI and E. Additionally, it highlights the differences between rounding methods (round, ceil, floor) and their appropriate use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Math class Java.

Mathematical functions
(trigonometric, log, etc.) Rounding round, floor, ceil
MATH CLASS FUNCTIONS JAVA

As for mathematical functions in Java, the available functions are defined in the Math class.
There are many available functions. You can check the full list in the official API documentation.
Java (according toversion of Java in use for example for the version 8
to seehttp://docs.oracle.com/javase/8/docs/api/java/lang/Math.html).

Next, we will show the most important functions and examples of use:

Mathematical function Meaning Example of use Result

abs Absolute value int x = Math.abs(2.3); x = 2;

atan Arctangent double x = Math.atan(1); x = 0.78539816339744;

sine Breast double x = Math.sin(0.5); x = 0.4794255386042;

cos Cosine double x = Math.cos(0.5); x = 0.87758256189037;

tan Tangent double x = Math.tan(0.5); x = 0.54630248984379;

exp Natural exponentiation double x = Math.exp(1); x = 2.71828182845904;

log Natural logarithm double x = Math.log(2.7172); x = 0.99960193833500;

pow Power double x = Math.pow(2.3); x = 8.0;

round Rounding double x = Math.round(2.5); x = 3;

random Random number double x = Math.random(); x = 0.20614522323378;

floor Rounding down to the nearest whole number double x = Math.floor(2.5); x = 2.0;

ceiling Rounding up to the next whole number double x = Math.ceil(2.5); x = 3.0;


It is important to highlight that mathematical functions, belonging to the Math class, are
They always invoke in the following way: Math.function(arguments).
The functions related to angles (atan, cos, sin, tan, etc.) work in
radians. Therefore, to work with degrees, we will have to perform the
timely conversion. The Math class itself provides the methods :toRadians for
convert degrees to radians and toDegrees to convert
radians to sexagesimal degrees, although the conversions may not be
totally accurate. For example, cos(toRadians(90.0)) should return 0, but
it is likely to return a value approximately zero but not exactly
zero because decimal precision is not absolute.
The function: random, allows generating random numbers in the range ]0,1[.
both 0 and 1 are excluded.
The natural exponentiation function or exponentiation of e, mathematically
it means ex, which in Java would be Math.exp(x), where x is a real number and the base
the Neperian constant e = 2.7172...
The natural logarithm function, mathematically means Ln x, which in Java
it would correspond to the expression Math.log(x).

The power function, mathematically means baseexponentthat in Java


would convert to Math.pow(base, exponent), where base and exponent are
real numbers, therefore, if we want to obtain the cube root of 2, the
the instruction would be Math.pow(2,0.333).

There is no direct function to obtain the integer part of a real number,


but for these cases, it can be obtained in the following way:
int x = (int)(8.7); --> x = 8;
int x = (int)(-8.7); --> x = -8;
Clarify that obtaining the integer part is different from rounding.
If you are going to work with physical or mathematical constants, you will find it interesting the
final instruction for declaring constants. The advantage of declaring a
constant instead of a variable, consists of the fact that the constant cannot vary
during the course of the program. Therefore, it prevents the possibility of making an error.
an invalid value at a given moment. Constants facilitate the
program documentation and it makes it easy to modify. A typestyle statement
the constant could be the following:
final double pi = 3.14159265358979;
However, Java itself has its own constant to define the
mathematical constant PI: Math.PI
The following program will demonstrate its use in converting an angle.
sexagesimal to radians.
/* Example of a java class using the constant PI from the Math class–
learnprogramming.com */
public class Program {
public static void main(String args[]) {
double sexagesimal = 30;
double radians = Math.PI/180 * degrees;
Angle in radians:
}
}

DIFFERENCE BETWEEN ROUND, CEIL, AND FLOOR

The functions round, ceil, and floor are used to obtain an integer close to a
decimal number and have similarities, in fact in some cases they return the
same result. However, they also have differences that are interesting.
to know. These three functions apply to decimal numerical values and
return a numerical value that in the case of round is a long integer, while
that in the case of floor and ceil, they return a matching double type value or
equivalent to an integer.

The round method always rounds to the nearest integer, for example 2.6
rounds to 3 while -2.6 rounds to -3. If the decimal is exactly
between two values it rounds up to the nearest upper integer (for example 2.5
rounds to 3 and -2.5 rounds to -2.

The floor method returns the smaller integer, for example 2.9
would be 2.0 and -2.9 would be -3.0. Also 2.1 would be 2.0 and -2.1
-3.0.

The ceil method returns the greater integer, for example, 2.9 would become
At 3.0 and -2.9 it would be -2.0. Also, 2.1 would be at 3.0 and -2.1 would be at -
2.0.

In each program we must determine which method is appropriate for


obtain the desired results. For example, if we have to round
For amounts of money, it seems more logical to use round. On the other hand, if we are
working with a person's age in years using decimals, we will be able to
reasoning in another way. A person's age is a positive value (it is not
possible that it takes negative values). We say that a person is x years old.
as long as they do not turn x+1 years old, so that during the entire intermediate period
we say that he/she is x years old. For example, if I turn 35 on February 4th
2096, from February 4, 2096 to February 3, 2097 I will say that
I am 35 years old. But in a program that worked with decimals, at the point
the interval between these two dates would be 35.50 years. If I want to obtain the value
what age represents from the decimal value, it would be logical to use the
floor method because it will return 35 for all decimal values between
35 and 36, just as we express ages in natural language. In this case
both round and ceil would not provide a suitable result for our
interests.

Write this code and check its results:

Some Methods of the Math Class.


Method. Description.

abs(double a) Returns the absolute value of a double value entered as a parameter.


absolute value of float a Returns the absolute value of a float value entered as a parameter.
absolute value of integer a Returns the absolute value of an integer value provided as a parameter.

abs(long a) Returns the absolute value of a long value passed as a parameter.

acos(double a) Returns the arc cosine of a value provided as a parameter.

addExact(int x, int y) Returns the sum of its arguments, throwing an exception if the result d

addExact(long x, long y) Returns the sum of its arguments, throwing an exception if the result s
long.

asin(double a) Returns the arcsine of a given value.

atan(double a) Returns the arctangent of an entered value.

cbrt(double a) Returns the cubic root of a double value.

cos(double a) Returns the trigonometric cosine of an angle.

exp(double a) Returns Euler's number e raised to the power of a double value.

log(double a) Returns the natural logarithm (base e) of a double value.

log10(double a) Returns the logarithm base 10 of a double value.

max(double a, double b) Returns the larger of two double values

max(float a, float b) Returns the greater of two float values.

max(int a, int b) Returns the greater of two integer values.

max(long a, long b) Returns the greater of two long values.

min(double a, double b) Returns the smaller of two double values.


min(float a, float b) Returns the smaller of two float values.

min(int a, int b) Returns the lesser of two integer values.

min(long a, long b) Returns the smaller of two long values.

multiplyExact(int x, int y) Returns the product of the arguments, throwing an exception if the result
int.

multiplyExact(long x, long Returns the product of the arguments, throwing an exception if the result
y) long.

pow(double a, double b) Returns the value of the first argument raised to the power of the second argument

random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than

round(double a) Returns the nearest rounded long to the entered double.

round(float a) Returns the closest integer rounded to the entered float.

sin(double a) Returns the trigonometric sine of an angle.

sqrt(double a) Return the correctly rounded positive square root of a double value.

tan(double a) Returns the trigonometric tangent of an angle.

Example of a Java program that uses the Math class.


In the following Java program example, we use the Math class to perform some
calculations and operations. We also take advantage and use theDecimalFormat classfor
Present one of the results they give us in this format, so we can practice.
and solidifying what we are learning during the Java course.

0
1 package clasemath;
2
3 import java.text.DecimalFormat;
4 /**
5 *
6 * @author codesitio.com
7 */
8 public class MathClass {
9
10 public static String methodForm ( String pattern, double data) {
11 DecimalFormat objDF = new DecimalFormat (pattern);
12 String result = objDF.format(dato);
13 return result;
14 }
15
16 public static void main(String[] args) {
17 double num1 = -10.570;
18 double num2 = 4.10;
19 int num3 = 10;
20 int num4 = 38;
21 double data;
22
23 System.out.printf ("The absolute value of %.3f is %.2f %n", num1, Math.abs(num1));
24
25 System.out.printf("The maximum of %d and %d is %d %n", num3, num4, Math.max(num3, num4));
26
27 System.out.printf ("The minimum of %d and %d is %d %n", num3, num4, Math.min (num3, num4));
28
29 System.out.printf ("The value of e is %.4f %n", Math.E);
30
31 System.out.printf("exp (%d) is %.3f %n", num3, Math.exp(num3));
32
33 System.out.printf("log (%d) is %.3f %n", num4, Math.log(num4));
34
35 System.out.printf("%.2f raised to %d is %f %n", num2, num3, dato = Math.pow(num2, num3));
36
37 System.out.printf("The formatted output is: %n " + metodoForm("###,###.##", dato )+"%n");
38
39 System.out.printf ("The square root of (%.2f) is %.2f %n", num2, Math.sqrt (num2));
40 }
41 }
42
In the console, we would have the following results:
random() method of the Math class.
We can use the random method to generate random numbers. The range or margin
with which the random method works ranges between 0.0 and 1.0 (the latter not included).
Therefore, to generate an integer between 0 and 9, you must write the following
sentence:

0
int number = (int) (Math.random() * 10);
2
In this way, by multiplying the value by 10, the range of possible values becomes:

0
1 0.0 <= number < 10.0
2
To conclude, you can see an example of a Java program that uses the random method.
the Math class is thispage.

The Math Class


Classes and objects

Constant data members

Member functions

Calculation of the irrational number

The Math class has data members and static member functions, let's
to know some of these functions, what they are called and what task they perform.

Data members constants

The Math class defines two very useful constants, the number and the number e.

public final class Math {


public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
//...
}
The final modifier indicates that the values it holds cannot be changed.
they are constant values

These constants are accessed from the Math class, as follows


System.out.println("Pi is " + Math.PI);
System.out.println("e is " + Math.E);

Member functions
The Math class defines many functions and different versions of each function.

For example, to find the absolute value of a number, define the following
functions. One is called or the other depending on the type of data that is passed to it
unique argument.
public final class Math {
public static int abs(int a) {
return (a < 0) ? -a : a;
}
public static long abs(long a) {
return (a < 0) ? -a : a;
}
public static float abs(float a) {
return (a < 0) ? -a : a;
}
public static double abs(double a) {
return (a < 0) ? -a : a;
}
//...
}

For example, find the absolute value of the following numbers.


int i = -9;
double x = 0.3498;
System.out.println("|" + i + "| is " + Math.abs(i));
System.out.println("|" + x + "| is " + Math.abs(x));

Math.abs(i) calls the first version, and Math.abs(x) calls the latest version.

Trigonometric functions

In trigonometric functions, the arguments are expressed in radians.


For example, the angle 45º is converted into radians and then the sine and cosine are found.
and the tangent
double angle = 45.0 * Math.PI / 180.0;
System.out.println("cos(" + angle + ") is " + Math.cos(angle));
System.out.println("sin(" + angle + ") is " + Math.sin(angle));
System.out.println("tan(" + angle + ") is " + Math.tan(angle));

To convert from rectangular coordinates to polar coordinates, the atan2 function is useful, which
It accepts two arguments, the ordinate and the abscissa of the point. It returns the angle.
in radians.
double y=-6.2; //ordinate
double x=1.2; abscissa
System.out.println("atan2(" + y + " , " + x + ") is " + Math.atan2(y,
x));

Exponential and logarithmic functions

The exponential function exp returns the number e raised to a power.


System.out.println("exp(1.0) is " + Math.exp(1.0));
System.out.println("exp(10.0) is " + Math.exp(10.0));
System.out.println("exp(0.0) is " + Math.exp(0.0));

The function log calculates the natural logarithm (base e) of a number

System.out.println("log(1.0) is " + Math.log(1.0));


System.out.println("log(10.0) is " + Math.log(10.0));
System.out.println("log(Math.E) is " + Math.log(Math.E));

Power function and square root

To raise a number x to the power y, pow(x, y) is used.


System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5));

To find the square root of a number, the sqrt function is used.


The square root of
Math.sqrt(x));

Approximation of a decimal number

To express a real number with a specified number of decimal places


we use the round function. For example, to express the numbers x and y with
we write two decimal places
double x = 72.3543;
double y = 0.3498;
System.out.println(x + " is approx. " +
(double)Math.round(x*100)/100;
System.out.println(y + " is approx. " +
(double)Math.round(y*100)/100;

It yields 72.35 and 0.35 as one might expect. Note that round returns a
integer number that is necessary to promote a double to carry out the
division by 100.

If we use the floor function instead of round, we would get

System.out.println(x + " is approx. " + Math.floor(x*100)/100);


System.out.println(y + " is approx. " + Math.floor(y*100)/100);

It results in 72.35 and 0.34. The approximation of the first is correct as the
The third decimal digit is 4 less than 5. The approximation of the second is incorrect.
since the third decimal digit is 9 greater than 5. In most of the
calculations there are errors, so the difference between floor and round is not
significant.

The greater and the lesser of two numbers

To find the largest and the smallest of two numbers, one uses the
minmax functions that compare numbers of the same type.
int i = 7;
int j = -9;
double x = 72.3543;
double y = 0.3498;
to find the smaller of two numbers
System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j));
System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y));
To find the greater of two numbers
System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j));
max(

Random numbers

The Math class defines a function called random that returns a number
pseudo-random contained in the interval [0.0, 1.0). There is another alternative, it
they can generate pseudo-random numbers from an object of
theclassRandom, call the function memberNextDouble.
Random number:
System.out.println("Another random number: " + Math.random());
Calculation of the irrational number

To find the length of a circumference with radius R, one first calculates the
perimeter of an equilateral triangle (3 sides) inscribed in that circumference,
then, from a hexagon (6 sides), a dodecagon (12 sides), and so on.
The limit of the perimeter sequence is precisely the length of the
circumference2 R.

If we take a circle of unit radius, when dividing the values by two


We will obtain the successive approximations of the number from the perimeters.
irrational .

From the figure, we can calculate the length


on the sidena regular inscribed polygon
in the circumference with radius R, (in red color).

In the same way, we obtain the length of the side


of a regular polygon inscribed with 2n sides (in
blue color.

Considering that

We establish the relationship betweenn yes2nand therefore, between the perimeter Pndel
regular polygon of sides and the perimeter P2nof the regular polygon of 2 sides.

Taking as radius R, the unit

For a triangle, n=3, the length of the side is a.3=2sin60º, and the
perimeter
For a hexagon, n=6, the length of the side is a6=2sin30º=1, and the
perimeter6=6.
and so on.

To obtain successive approximations of the irrational number through the


We proceed as follows with the previous formula.

We start from the value of the perimeter P of an equilateral triangle inscribed in


a circle with a radius of one, the value of denes 3.
2. We calculate the perimeter P of a polygon with 2n sides from the value of
perimeter of a regular polygon with sides.
3. The obtained value will be the value of the perimeter of a regular polygon.
den=2sides.
4. The value of P is printed divided by two (approximation of )
5. It goes back to step 2.

Now, we have to translate the mathematical formulas into code, and here is where
We can have some surprises.

First of all, we must take into account that the expression is

mathematically equivalent to but it is not when we work with


numbers on the computer.

For example, without data types. When evaluating the denominator in the first
expression we obtain the square of which grows very quickly with,
overlapping (overflow) themaximum value that a variable can hold
fullgiven by Integer.MAX_VALUE. Integer is the class that describes numbers
integers. Therefore, when performing calculations on the computer, it is advisable to use
the second expression instead of the first, even if we change the data type
since then

The calculation of it involves an infinite number of iterations, since as we have


since it is not possible to exceed the maximum value that can be stored
integer variable, our first intention would be to program a loop that performs
the maximum number of iterations
double perimeter = 3 * Math.sqrt(3); inscribed equilateral triangle
long n=3;
int i=0; number of iterations
while(n<Long.MAX_VALUE){
perimeter=2*n*Math.sqrt(2.0-Math.sqrt(4.0-
(perimeter/n)*(perimeter/n));
n=2*n;
i++;

You might also like