 Mathematics in Java

 Introduction

To assist you with various types of calculations, the java.lang package contains a class named Math. In this class are the most commonly needed operations in mathematics.

 Value Conversion

In Lesson 2, we learned how to declare variables of integral, floating-point, and string types. We also saw how to initialize the variables. If you have a program with mixed types of variables, you may be interested in converting the value of one into another. Again, in Lesson 2, we saw how much memory the variable of each data type required in order to hold its value. Here is a summary of what we learned:

 Data Type Name Memory Size byte Byte 8 bits char Character 16 bits short Small Integer 16 bits int Signed Integer 32 bits float Single-Precision Floating-Point Number 32 bits double Double-Precision Floating-Point Number 64 bits long Signed Long Integer 64 bits

As you can see, a value held by a byte variable can fit in the memory reserved for an int variable, which can be carried by a long variable. Thanks to this, you can assign a byte value to an int variable, or an int variable to a long variable. Also, based on this, because the memory reserved for an int variable is larger than the one reserved for a double variable, you can assign a variable of the former to a variable of the latter. Here is an example:

```public class Exercise {
public static void main(String[] args) {
int iNumber = 2445;
double dNumber = iNumber;

System.out.println("Number = " + iNumber);
System.out.println("Number = " + dNumber);
}
}```

This would produce:

```Number = 2445
Number = 2445.0```

This characteristic is referred to as implicit conversion.

Because of memory requirements, the direct reverse of implicit conversion is not possible. Since the memory reserved for a short variable is smaller than that of an int, you cannot assign the value of an int to a short variable. Consider the following program:

```public class Exercise {
public static void main(String[] args) {
int iNumber   = 168;
short sNumber = iNumber;

System.out.println("Number = " + iNumber);
System.out.println("Number = " + sNumber);
}
}```

This would produce the following error:

```C:\Exercise>javac Exercise.java
Exercise.java:4: possible loss of precision
found   : int
required: short
short sNumber = iNumber;
^
1 error```

Value casting consists of converting a value of one type into a value of another type. For example, you may have an integer value and you may want that value in an expression that expects a short number. Value casting is also referred to as explicit conversion.

To cast a value or a variable, precede it with the desired data type in parentheses. Here is an example:

```public class Exercise {
public static void main(String[] args) {
int iNumber   = 168;
short sNumber = (short)iNumber;

System.out.println("Number = " +  iNumber);
System.out.println("Number = " + sNumber);
}
}```

This would produce:

```Number = 168
Number = 168```

When performing explicit conversion, you should pay close attention to the value that is being cast. If you want an integer value to be assigned to a short variable, the value must fit in 16 bits, which means it must be between -32768 and 32767. Any value beyond this range would produce an unpredictable result. Consider the following program:

```public class Exercise {
public static void main(String[] args) {
int iNumber   = 680044;
short sNumber = (short)iNumber;

System.out.println("Number = " + iNumber);
System.out.println("Number = " + sNumber);
}
}```

This would produce:

```Number = 680044
Number = 24684```

Notice that the result is not reasonable.

 The Minimum of Two Values

If you have two numbers, you can find the minimum of both without writing your own code. To assist you with this, the Math class is equipped with a method named min. This method is overloaded in fours versions to handle integers and decimal numbers. The syntaxes are:

```static int     min(int     val1, int     val2);
static long    min(long    val1, long    val2);
static float   min(float   val1, float   val2);
static double  min(double  val1, double  val2);```

Here is an example of calling the method:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
int number1 = 8025;
int number2 = 73;

System.out.println("The minimum of " + number1 + " and " +
number2 + " is " + Math.min(number1, number2));
}
}```

This would produce:

`The minimum of 8025 and 73 is 73`
 The Maximum Integer Value of a Series

As opposed to the minimum of two numbers, you may be interested in the higher of both. To help you find the maximum of two numbers, you can call the max() method of the Math class from the java.lang package. It is overloaded in four versions to handle natural and decimal numbers. The syntaxes of this method are:

```static int     max(int     val1, int     val2);
static long    max(long    val1, long    val2);
static float   max(float   val1, float   val2);
static double  max(double  val1, double  val2);```

Here is an example of calling the method:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
int number1 = 8025;
int number2 = 73;

System.out.println("The minimum of " + number1 + " and " +
number2 + " is " + Math.max(number1, number2));
}
}```

This would produce:

`The maximum of 8025 and 73 is 8025`
 Absolute Values

The decimal numeric system counts from negative infinity to positive infinity. This means that numbers are usually negative or positive, depending on their position from 0, which is considered as neutral. In some operations, the number considered will need to be only positive even if it is provided in a negative format. The absolute value of a number x is x if the number is (already) positive. If the number is negative, its absolute value is its positive equivalent. For example, the absolute value of 12 is 12, while the absolute value of �12 is 12.

To get the absolute value of a number, the Math class is equipped with a method named abs, which is overloaded in four versions. Their syntaxes are:

```public static int     abs(int     value);
public static long    abs(long    value);
public static float   abs(float   value);
public static double  abs(double  value);```

This method takes the argument whose absolute value must be fond. Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
int number   = -6844;

System.out.println("Original Value = " + number);
System.out.println("Absolute Value = " + Math.abs(number));
}
}```

This would produce:

```Original Value = -6844
Absolute Value = 6844```

 The Ceiling of a Number

Consider a floating-point number such as 12.155. This number is between integer 12 and integer 13: In the same way, consider a number such as �24.06. As this number is negative, it is between �24 and �25, with �24 being greater.

In arithmetic, the ceiling of a number is the closest integer that is greater or higher than the number considered. In the first case, the ceiling of 12.155 is 13 because 13 is the closest integer greater than or equal to 12.155. The ceiling of �24.06 is �24.

To support the finding of a ceiling, the Math class is equipped with a method named ceil. Its syntax is:

`static double ceil(double a);`

This method takes as argument a floating-point number of variable whose ceiling needs to be found. Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
double value1 = 155.55;
double value2 = -24.06;

System.out.println("The ceiling of " + value1 + " is " +
Math.ceil(value1));
System.out.println("The ceiling of " + value2 + " is " +
Math.ceil(value2));
}
}```

This would produce:

```The ceiling of 155.55 is 156.0
The ceiling of -24.06 is -24.0```
 The Floor of a Number

Consider two floating numbers such as 128.44 and -36.72. The number 128.44 is between 128 and 129 with 128 being the lower. The number �36.72 is between �37 and �36 with �37 being the lower. The lowest but closest integer value of a number is referred to as its floor.

To assist you with finding the floor of a number, the Math class provides the floor() method. Its syntax is:

`static double floor(double d);`

The floor() method takes the considered value as the argument and returns a decimal number that is less than or equal to argument. Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
double value1 = 1540.25;
double value2 = -360.04;

System.out.println("The floor of " + value1 + " is " +
Math.floor(value1));
System.out.println("The floor of " + value2 + " is " +
Math.floor(value2));
}
}```

This would produce:

```The floor of 1540.25 is 1540.0
The floor of -360.04 is -361.0```
 The Power of a Number

The power is the value of one number or expression raised to another number. This follows the formula:

`ReturnValue = xy`

To support this operation, the Math class is equipped with a method named pow whose syntax is:

`static double pow(double x, double y);`

This method takes two arguments. The first argument, x, is used as the base number to be evaluated. The second argument, y, also called the exponent, will raise x to this value. Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
final double source = 25.38;
final double exp = 3.12;

double result = Math.pow(source, exp);

System.out.println("Pow(" + source + ", " + exp + ") = " + result);
}
}```

This would produce:

`Pow(25.38, 3.12) = 24099.8226934415`
 The Exponential

You can calculate the exponential value of a number. To support this, the Math class provides the exp() method. Its syntax is:

`static double exp(double d);`

Here is an example of calling this method:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
System.out.println("The exponential of 709.78222656 is " +
Math.exp(709.78222656));
}
}```

This would produce:

```The exponential of 709.78222656 is 1.79681906923757E308
```

If the value of x is less than -708.395996093 (approximately), the result is reset to 0 and qualifies as underflow. If the value of the argument x is greater than 709.78222656 (approximately), the result qualifies as overflow.

 The Natural Logarithm

To calculate the natural logarithm of a number, you can call the Math.log() method. Its syntax is:

`static double log(double d);`

Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
double log = 12.48D;

System.out.println("Log of " + log + " is " + Math.log(log));
}
}```

This would produce:

`Log of 12.48 is 2.52412736294128`
 The Square Root

You can calculate the square root of a decimal positive number. To support this, the Math class is equipped with a method named sqrt whose syntax is:

`static double sqrt(double d);`

This method takes one argument as a positive floating-point number. After the calculation, the method returns the square root of x:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
double sqrt = 8025.73D;

System.out.println("The square root of " +
sqrt + " is " + Math.sqrt(sqrt));
}
}```

This would produce:

`The square root of 8025.73 is 89.5864387058666 `
 Introduction to Trigonometric Methods A circle is a group or series of distinct points drawn at an exact same distance from another point referred to as the center. The distance from the center C to one of these equidistant points is called the radius, R. The line that connects all of the points that are equidistant to the center is called the circumference of the circle. The diameter is the distance between two points of the circumference to the center; in other words, a diameter is double the radius.

To manage the measurements and other related operations, the circumference is divided into 360 portions. Each of these portions is called a degree. The unit used to represent the degree is the degree, written as ˚. Therefore, a circle contains 360 degrees, that is 360˚. The measurement of two points A and D of the circumference could have 15 portions of the circumference. In this case, this measurement would be represents as 15˚.

The distance between two equidistant points A and B is a round shape geometrically defined as an arc. An angle is the ratio of the distance between two points A and B of the circumference divided by the radius R. This can be written as: Therefore, an angle is the ratio of an arc over the radius. Because an angle is a ratio and not a �physical� measurement, which means an angle is not a dimension, it is independent of the size of a circle. Obviously this angle represents the number of portions included by the three points. A better unit used to measure an angle is the radian or rad. A cycle is a measurement of the rotation around the circle. Since the rotation is not necessarily complete, depending on the scenario, a measure is made based on the angle that was covered during the rotation. A cycle could cover part of the circle in which case the rotation would not have been completed. A cycle could also cover the whole 360˚ of the circle and continue there after. A cycle is equivalent to the radian divided by 2 * Pi.

 The Pi Constant

The word п, also written as Pi, is a constant number used in various mathematical calculations. Its approximate value is 3.1415926535897932. The calculator of Windows represents it as 3.1415926535897932384626433832795.

To support the Pi constant, the Math class is equipped with a constant named PI.

A diameter is two times the radius. In geometry, it is written as 2R. In C++, it is written as 2 * R or R * 2 (because the multiplication is symmetric). The circumference of a circle is calculated by multiplying the diameter to Pi, which is 2Rп, or 2 * R * п or 2 * R * Pi.

A radian is 2Rп/R radians or 2Rп/R rad, which is the same as 2п rad or 2 * Pi rad.

To perform conversions between the degree and the radian, you can use the formula:

360˚ = 2п rad which is equivalent to 1 rad = 360˚ / 2п = 57.3˚.

 The Cosine of a Value

Consider the following geometric figure: Consider AB the length of A to B, also referred to as the hypotenuse. Also consider AC the length of A to C which is the side adjacent to point A. The cosine of the angle at point A is the ratio AC/AB. That is, the ratio of the adjacent length, AC, over the length of the hypotenuse, AB: The returned value, the ratio, is a double-precision number between �1 and 1.

To calculate the cosine of an angle, the Math class provides the cos() method. Its syntax is:

`static double cos(double d);`

Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
int number = 82;

System.out.println("The cosine of " + number + " is " + Math.cos(number));
}
}```

This would produce:

`The cosine of 82 is 0.949677697882543`
 The Sine of a Value

Consider AB the length of A to B, also called the hypotenuse to point A. Also consider CB the length of C to B, which is the opposite side to point A. The sine represents the ratio of CB/AB; that is, the ratio of the opposite side, CB over the hypotenuse AB.

To calculate the sine of a value, you can call the sin() method of the Math class. Its syntax is:

`static double sin(double a);`

Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
double number = 82.55;

System.out.println("The sine of " + number + " is " + Math.sin(number));
}
}```

This would produce:

`The sine of 82.55 is 0.763419622322519`
 Tangents

Consider AC the length of A to C. Also consider BC the length of B to C. The tangent is the result of BC/AC; that is, the ratio of BC over AC. To assist you with calculating the tangent of of a number, the Math class is equipped with a method named tan whose syntax is:

`static double tan(double a);`

Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
int number = 225;

System.out.println("The tangent of " + number + " is " + Math.tan(number));
}
}```

This would produce:

`The tangent of 225 is -2.5321149923343427`
 The Arc Tangent

Consider BC the length of B to C. Also consider AC the length of A to C. The arc tangent is the ratio of BC/AC. To calculate the arc tangent of a value, you can use the Math.atan() method. Its syntax is

`static double atan(double d);`

Here is an example:

```import java.lang.Math;

public class Exercise {
public static void main(String[] args) {
short number = 225;

System.out.println("The arc tangent of " + number + " is " +
Math.atan(number));
}
}```

This would produce:

`The arc tangent of 225 is 1.566351911613937`