Functions in java math

Beyond Basic Arithmetic

The Java programming language supports basic arithmetic with its arithmetic operators: +, -, *, /, and %. The Math class in the java.lang package provides methods and constants for doing more advanced mathematical computation.

The methods in the Math class are all static, so you call them directly from the class, like this:

Note: Using the static import language feature, you don’t have to write Math in front of every math function:

import static java.lang.Math.*;

This allows you to invoke the Math class methods by their simple names. For example:

Constants and Basic Methods

The Math class includes two constants:

  • Math.E , which is the base of natural logarithms, and
  • Math.PI , which is the ratio of the circumference of a circle to its diameter.

The Math class also includes more than 40 static methods. The following table lists a number of the basic methods.

Basic Math Methods

Method Description
double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)
Returns the absolute value of the argument.
double ceil(double d) Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
double floor(double d) Returns the largest integer that is less than or equal to the argument. Returned as a double.
double rint(double d) Returns the integer that is closest in value to the argument. Returned as a double.
long round(double d)
int round(float f)
Returns the closest long or int, as indicated by the method’s return type, to the argument.
double min(double arg1, double arg2)
float min(float arg1, float arg2)
int min(int arg1, int arg2)
long min(long arg1, long arg2)
Returns the smaller of the two arguments.
double max(double arg1, double arg2)
float max(float arg1, float arg2)
int max(int arg1, int arg2)
long max(long arg1, long arg2)
Returns the larger of the two arguments.
Читайте также:  Приведите пример полиморфизма java

The following program, BasicMathDemo , illustrates how to use some of these methods:

public class BasicMathDemo < public static void main(String[] args) < double a = -191.635; double b = 43.74; int c = 16, d = 45; System.out.printf("The absolute value " + "of %.3f is %.3f%n", a, Math.abs(a)); System.out.printf("The ceiling of " + "%.2f is %.0f%n", b, Math.ceil(b)); System.out.printf("The floor of " + "%.2f is %.0f%n", b, Math.floor(b)); System.out.printf("The rint of %.2f " + "is %.0f%n", b, Math.rint(b)); System.out.printf("The max of %d and " + "%d is %d%n", c, d, Math.max(c, d)); System.out.printf("The min of of %d " + "and %d is %d%n", c, d, Math.min(c, d)); >>

Here’s the output from this program:

The absolute value of -191.635 is 191.635 The ceiling of 43.74 is 44 The floor of 43.74 is 43 The rint of 43.74 is 44 The max of 16 and 45 is 45 The min of 16 and 45 is 16

Exponential and Logarithmic Methods

The next table lists exponential and logarithmic methods of the Math class.

Exponential and Logarithmic Methods

Method Description
double exp(double d) Returns the base of the natural logarithms, e, to the power of the argument.
double log(double d) Returns the natural logarithm of the argument.
double pow(double base, double exponent) Returns the value of the first argument raised to the power of the second argument.
double sqrt(double d) Returns the square root of the argument.

The following program, ExponentialDemo , displays the value of e , then calls each of the methods listed in the previous table on arbitrarily chosen numbers:

public class ExponentialDemo < public static void main(String[] args) < double x = 11.635; double y = 2.76; System.out.printf("The value of " + "e is %.4f%n", Math.E); System.out.printf("exp(%.3f) " + "is %.3f%n", x, Math.exp(x)); System.out.printf("log(%.3f) is " + "%.3f%n", x, Math.log(x)); System.out.printf("pow(%.3f, %.3f) " + "is %.3f%n", x, y, Math.pow(x, y)); System.out.printf("sqrt(%.3f) is " + "%.3f%n", x, Math.sqrt(x)); >>

Here’s the output you’ll see when you run ExponentialDemo :

The value of e is 2.7183 exp(11.635) is 112983.831 log(11.635) is 2.454 pow(11.635, 2.760) is 874.008 sqrt(11.635) is 3.411

Trigonometric Methods

The Math class also provides a collection of trigonometric functions, which are summarized in the following table. The value passed into each of these methods is an angle expressed in radians. You can use the toRadians method to convert from degrees to radians.

Trigonometric Methods

Method Description
double sin(double d) Returns the sine of the specified double value.
double cos(double d) Returns the cosine of the specified double value.
double tan(double d) Returns the tangent of the specified double value.
double asin(double d) Returns the arcsine of the specified double value.
double acos(double d) Returns the arccosine of the specified double value.
double atan(double d) Returns the arctangent of the specified double value.
double atan2(double y, double x) Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta .
double toDegrees(double d)
double toRadians(double d)
Converts the argument to degrees or radians.

Here’s a program, TrigonometricDemo , that uses each of these methods to compute various trigonometric values for a 45-degree angle:

public class TrigonometricDemo < public static void main(String[] args) < double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi " + "is %.4f%n", Math.PI); System.out.format("The sine of %.1f " + "degrees is %.4f%n", degrees, Math.sin(radians)); System.out.format("The cosine of %.1f " + "degrees is %.4f%n", degrees, Math.cos(radians)); System.out.format("The tangent of %.1f " + "degrees is %.4f%n", degrees, Math.tan(radians)); System.out.format("The arcsine of %.4f " + "is %.4f degrees %n", Math.sin(radians), Math.toDegrees(Math.asin(Math.sin(radians)))); System.out.format("The arccosine of %.4f " + "is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.acos(Math.cos(radians)))); System.out.format("The arctangent of %.4f " + "is %.4f degrees %n", Math.tan(radians), Math.toDegrees(Math.atan(Math.tan(radians)))); >>

The output of this program is as follows:

The value of pi is 3.1416 The sine of 45.0 degrees is 0.7071 The cosine of 45.0 degrees is 0.7071 The tangent of 45.0 degrees is 1.0000 The arcsine of 0.7071 is 45.0000 degrees The arccosine of 0.7071 is 45.0000 degrees The arctangent of 1.0000 is 45.0000 degrees

Random Numbers

int number = (int)(Math.random() * 10);

By multiplying the value by 10, the range of possible values becomes 0.0

Using Math.random works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.Random and invoke methods on that object to generate numbers.

Источник

Class Math

The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

Unlike some of the numeric methods of class StrictMath , all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.

By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math .

The quality of implementation specifications concern two properties, accuracy of the returned result and monotonicity of the method. Accuracy of the floating-point Math methods is measured in terms of ulps, units in the last place. For a given floating-point format, an ulp of a specific real number value is the distance between the two floating-point values bracketing that numerical value. When discussing the accuracy of a method as a whole rather than at a specific argument, the number of ulps cited is for the worst-case error at any argument. If a method always has an error less than 0.5 ulps, the method always returns the floating-point number nearest the exact result; such a method is correctly rounded. A correctly rounded method is generally the best a floating-point approximation can be; however, it is impractical for many floating-point methods to be correctly rounded. Instead, for the Math class, a larger error bound of 1 or 2 ulps is allowed for certain methods. Informally, with a 1 ulp error bound, when the exact result is a representable number, the exact result should be returned as the computed result; otherwise, either of the two floating-point values which bracket the exact result may be returned. For exact results large in magnitude, one of the endpoints of the bracket may be infinite. Besides accuracy at individual arguments, maintaining proper relations between the method at different arguments is also important. Therefore, most methods with more than 0.5 ulp errors are required to be semi-monotonic: whenever the mathematical function is non-decreasing, so is the floating-point approximation, likewise, whenever the mathematical function is non-increasing, so is the floating-point approximation. Not all approximations that have 1 ulp accuracy will automatically meet the monotonicity requirements.

The platform uses signed two’s complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int or long and overflow errors need to be detected, the methods whose names end with Exact throw an ArithmeticException when the results overflow.

The 2019 revision of the IEEE 754 floating-point standard includes a section of recommended operations and the semantics of those operations if they are included in a programming environment. The recommended operations present in this class include sin , cos , tan , asin , acos , atan , exp , expm1 , log , log10 , log1p , sinh , cosh , tanh , hypot , and pow . (The sqrt operation is a required part of IEEE 754 from a different section of the standard.) The special case behavior of the recommended operations generally follows the guidance of the IEEE 754 standard. However, the pow method defines different behavior for some arguments, as noted in its specification. The IEEE 754 standard defines its operations to be correctly rounded, which is a more stringent quality of implementation condition than required for most of the methods in question that are also included in this class.

Источник

Java Math класс и его методы

Java-университет

Класс Java Math и его методы - 1

В данной статье мы проведем краткий обзор класса Math в Java. Поговорим о методах данного класса и о том, как их использовать. Класс Math располагается в пакете java.lang и предоставляет набор статических методов для осуществления ряда различных математических вычислений. Ниже приведены примеры вычислений, для которых класс Math может оказаться полезным:

  • Вычисление абсолютных значений (значений по модулю)
  • Вычисление значений тригонометрических функций (синусов, косинусов и т.д.)
  • Возведение в различные степени
  • Извлечение корней различных степеней
  • Генерация случайных чисел
  • Округления
  • И пр.

Ниже мы попробуем рассмотреть как класс Java Math помогает решать задачи, перечисленные выше.Начнем разбор класса с методов, которые позволяют вычислить значение по модулю. За это отвечает метод abs. Данный метод перегружен и в классе Math имеются следующие его различия:

  • static double abs(double a)
  • static float abs(float a)
  • static int abs(int a)
  • static long abs(long a)

Пример использования:

 public static void main(String[] args) < System.out.println(Math.abs(-1)); // 1 System.out.println(Math.abs(-21.8d)); // 21.8 System.out.println(Math.abs(4532L)); // 4532 System.out.println(Math.abs(5.341f)); // 5.341 >

Вычисление значений тригонометрических функций

  • static double sin(double a)
  • static double cos(double a)
  • static double tan(double a)
  • static double asin(double a)
  • static double acos(double a)
  • static double atan(double a)
  • static double toDegrees(double angrad)
  • static double toRadians(double angdeg)
 public static void main(String[] args)
 0.0 0.49999999999999994 1.0 1.0 0.8660254037844387 6.123233995736766E-17 

Что не совсем соответствует таблицам синусов и косинусов, отчасти благодаря погрешностям при переводе из градусов в радианы.

Возведение в степень

Для возведения числа в степень класс Math предоставляет метод pow, который имеет следующую сигнатуру:

 static double pow(double a, double b) 
 public static void main(String[] args) < System.out.println(Math.pow(1,2)); // 1.0 System.out.println(Math.pow(2,2)); // 4.0 System.out.println(Math.pow(3,2)); // 9.0 System.out.println(Math.pow(4,2)); // 16.0 System.out.println(Math.pow(5,2)); // 25.0 System.out.println(Math.pow(1,3)); // 1.0 System.out.println(Math.pow(2,3)); // 8.0 System.out.println(Math.pow(3,3)); // 27.0 System.out.println(Math.pow(4,3)); // 64.0 System.out.println(Math.pow(5,3)); // 125.0 >

Извлечение корней

 public static void main(String[] args) < System.out.println(Math.sqrt(4)); // 2.0 System.out.println(Math.sqrt(9)); // 3.0 System.out.println(Math.sqrt(16)); // 4.0 System.out.println(Math.cbrt(8)); // 2.0 System.out.println(Math.cbrt(27)); // 3.0 System.out.println(Math.cbrt(125)); // 5.0 >

Генерация случайных чисел

Для генерации случайных чисел класс Math предоставляет метод random. Данный метод генерирует случайное позитивное вещественное (double) число в промежутке от 0.0 до 1.0. Сигнатура метода имеет следующий вид:

 public static double random() 
 public static void main(String[] args) < for (int i = 0; i < 5; i++) < System.out.println(Math.random()); >> 
 0.37057465028778513 0.2516253742011597 0.9315649439611121 0.6346725713527239 0.7442959932755443 

С помощью небольших манипуляций, можно использовать метод random класса Math для получения целочисленных случайных чисел лежащих в определенном диапазоне. Приведем пример функции которая принимает два аргумента min и max и возвращает случайное целое число, которое лежит в промежутке от min (включительно) до max (включительно):

 static int randomInARange(int min, int max)
 public class MathExample < public static void main(String[] args) < // Карта, в которой мы будем хранить количество выпадений какого-то числа Mapmap = new TreeMap<>(); // За 10000 операций for (int i = 0; i < 10000; i++) < // Сгенерируем рандомное число от -10 включительно до 10 включительно final Integer randomNumber = randomInARange(-10, 10); if (!map.containsKey(randomNumber)) < // Если карта еще не содержит "выпавшего случайного числа" // Положим его в карту с кол-вом выпадений = 1 map.put(randomNumber, 1); >else < // Иначе, увеличим количество выпадений данного числа на 1 map.put(randomNumber, map.get(randomNumber) + 1); >> // Выведем на экран содержимое карты в формате ключ=[значение] for (Map.Entry entry : map.entrySet()) < System.out.println(String.format("%d=[%d]", entry.getKey(), entry.getValue())); >> static int randomInARange(int min, int max) < return (int) (Math.random() * ((max - min) + 1)) + min; >> 
 -10=[482] -9=[495] -8=[472] -7=[514] -6=[457] -5=[465] -4=[486] -3=[500] -2=[490] -1=[466] 0=[458] 1=[488] 2=[461] 3=[470] 4=[464] 5=[463] 6=[484] 7=[479] 8=[459] 9=[503] 10=[444] Process finished with exit code 0 

Округление

  • static long round(double a)
  • static int round(float a)
  • static double floor(double a)
  • static double ceil(double a)
 public static void main(String[] args) < System.out.println(Math.round(1.3)); // 1 System.out.println(Math.round(1.4)); // 1 System.out.println(Math.round(1.5)); // 2 System.out.println(Math.round(1.6)); // 2 System.out.println(Math.floor(1.3)); // 1.0 System.out.println(Math.floor(1.4)); // 1.0 System.out.println(Math.floor(1.5)); // 1.0 System.out.println(Math.floor(1.6)); // 1.0 System.out.println(Math.ceil(1.3)); // 2.0 System.out.println(Math.ceil(1.4)); // 2.0 System.out.println(Math.ceil(1.5)); // 2.0 System.out.println(Math.ceil(1.6)); // 2.0 >

Заключение

  • Вычислять значения по модулю;
  • Вычислять значения тригонометрических функций;
  • Возводить числа в степень;
  • Извлекать квадратный и кубический корни;
  • Генерировать случайные числа;
  • Округлять числа.

Источник

Оцените статью