Как взять корень в java
Перейти к содержимому

Как взять корень в java

  • автор:

Изучаем Java

Класс Math содержит набор математических функций, часто оказывающихся не­обходимыми при решении разных задач.
Чтобы извлечь квадратный корень из числа, применяют метод sqrt.
double х = 4;
double у = Math.sqrt(х);
System.out.println(у); // Печатает число 2.0.

Между методами println и sqrt есть небольшая разница. Метод println дей­ствует на объект System, out, имея второй параметр у — число, подлежащее вы­воду. (Напомним, что out — это объект, определенный в классе System и пред­ставляющий собой стандартное устройство вывода.)

В то же время метод sqrt в классе Math не работает ни с одним объектом. Он имеет единственный параметр х — число, из которого нужно извлечь корень. Такие методы называются статиче­скими.

В языке Java нет оператора возведения в степень: для этого нужно использовать метод pow из класса Math.

Оператор
double у = Math.pow(x,a) ;
присваивает переменной у значение переменной х, возведенное в степень а.

Оба параметра метода pow, а также возвращаемое им значение имеют тип double.

Класс Math содержит обычные тригонометрические функции:
Math.sin
Math.cos
Math.tan
Math.atan
Math.atan2

Кроме этого, в него включены экспоненциальная и обратная к ней логарифмиче­ская функции (натуральный логарифм):
Math.exp
Math.log

В классе определены также две константы
Math.PI
Math.E,
обозначающие аппроксимации чисел Пи и е.

Для повышения своей производительности функции в классе Math используют про­граммы из встроенного модуля для вычислений с плавающей точкой.
Если точность вычислений важнее скорости их выполнения, используйте класс strictMath.
Он реализует алгоритмы из библиотеки «Freely Distributable Math Library» («Свободно распространяемая библиотека математических функций») fdlibm, гарантирующей идентичность результатов на всех платформах.

Исходные тексты программ, реали­зующих эти алгоритмы, можно найти на web-странице http://www.netlib.org/fdlibm/index.html. (В библиотеке fdlibm дается несколько определений каждой функции, класс StrictMath следует версии IEEE754, имена функций в которой на­чинаются с буквы «е».)

Преобразования числовых типов

Часто возникает необходимость преобразовать один числовой тип в другой.

На рис. 3.1 показаны разрешенные преобразования.

Шесть черных стрелок на рис. 3.1 обозначают преобразования, которые выпол­няются без потери информации. Три серые стрелки означают преобразования, при которых может произойти потеря точности. Например, количество цифр в большом целом числе 123456789 превышает количество цифр, которое может быть представ­лено типом float.
Число, преобразованное в тип float, имеет правильную величи­ну, но несколько меньшую точность.

int n = 123456789;
float f = n; // Число n равно 1.23456789268.

Рис. 3.1 Разрешенные преобразования числовых типов

Если два значения объединяются бинарным оператором (например n+f, где n — целое число, a f — число с плавающей точкой), то перед выполнением операции оба операнда преобразовываются в числа, имеющие одинаковый тип.

Если хотя бы один из операндов имеет тип double, то второй тоже преобразо­вывается в число типа double.

В противном случае, если хотя бы один из операндов имеет тип float, то второй тоже преобразовывается в число типа float.
В противном случае, если хотя бы один из операндов имеет тип long, то второй тоже преобразовывается в число типа long.
В противном случае оба операнда преобразовываются в числа типа int.

Приведение числовых типов

В предыдущем разделе мы видели, что при необходимости значения типа int ав­томатически преобразовываются в значения типа double. С другой стороны, есть не­сколько очевидных ситуаций, когда число типа double рассматривается как целое. Преобразования чисел в языке Java возможны, однако, разумеется, при этом может происходить потеря информации. Такие преобразования называются приведением типа (cast).

Синтаксически приведение типа задается парой скобок, внутри которых
указывается желательный тип, а затем — имя переменной. Например,
double х = 9.997;
int nx = (int)x;

Теперь в результате приведения значения с плавающей точкой к целому типу пере­менная nх равна 9, поскольку при этом дробная часть числа отбрасывается.

Если нужно округлить число с плавающей точкой до ближайшего целого числа (что во многих случаях является намного более полезным), используется метод
Math.round.
double x = 9.997;
int nx = (int) Math. round (x);

Теперь переменная nx равна 10. При вызове метода round по-прежнему нужно выполнять приведение поскольку возвращаемое им значение имеет тип long, и присвоить его переменной типа int можно лишь с помощью явного приведения.

При попытке привести число одного типа к другому результат может выйти за пре­делы допустимого диапазона. В этом случае результат будет усечен.

Например, вы­ражение (byte) 300 равно 44. Поэтому рекомендуется явно проверять заранее, бу­дет ли результат лежать в допустимом диапазоне после приведения типов.

Приведение между булевским и целыми типами невозможно. Это предотвращает появление ошибок. В редких случаях для того, чтобы привести булевское значе­ние к числовому типу, можно использовать условное выражение
b ? 1 : 0.

Math.sqrt() in Java

Math.sqrt() method of java.lang package is used to find the correctly rounded and positive square root of a given number in Java.

This method takes double as an argument and returns a variable of double type. There are various special cases where it returns particular values as per the input. Also, we can implement our own square root method using a mathematical formula and using the Math.pow() method.

We can also find the square root of BigInteger whose range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 with the help of the inbuilt sqrt() method of the respective class.

Scope of Article

  • This article explains sqrt in Java, its parameters, syntax, return values, and examples.
  • We will also learn to find square root using Math.pow() method and implementation of sqrt method. We will also discuss BigInteger.sqrt() method in Java.

Introduction

The Math.sqrt() in Java is present in java.lang.Math class and is used to calculate the square root of the given number. It returns the double value that is correctly rounded positive square root of a given double value. In case of negative number input it returns NaN(Not a Number) as square root of negative number are not real but imaginary numbers. Since it is a static method we can directly call it using its class name like Math.sqrt() .

Method Declaration of Math.sqrt() Method in Java

Math.sqrt() method in Java is declared as follows:

It is a static method i.e. can be directly called using Math class.

Syntax of Math.sqrt() in Java

To find the square root of a number we use the following syntax, pass the number num to sqrt() method. Also, num can be of the type int , float , or double . Lastly, we can store the result in another variable of Double type.

Parameters of Math.sqrt() in Java

Math.sqrt() method takes a single variable of double data type whose square root we are supposed to find.

Return Values of Math.sqrt() in Java

Math.sqrt() method returns a double value which is the square root of the given value and is a correctly rounded positive number. If the argument is NaN or a negative number, it returns NaN i.e. Not a Number.

Examples of Math.sqrt() Method in Java

Let us see an example for finding the square root of the user entered number.

Output:

Explanation:

We store the user-entered value into the num variable of double type, which is passed to the Math.sqrt() method. Math.sqrt() method returns a double value which is stored in squareRoot variable and printed.

Example: Special Cases

There are various special cases where we might expect a different value for instance say square root of infinity or a negative number.

Note : NaN stands for Not a Number in Java. It is a special floating-point value that denotes overflows and errors. It is generated in the cases where a floating-point number is divided by zero or the square root of a negative number is computed as square root of negative numbers result in imaginary numbers.

Let us consider these five special cases:

  • Zero(0) — It returns 0.0 (zero as a double value) as a square root of 0.
  • Negative Integer — It return NaN as square root of negative number is a complex number.
  • Positive Infinity — It returns Infinity.
  • Negative Infinity — As it is infinity but still a negative number it returns NaN.
  • NaN — Square root of NaN is returned as NaN itself.

Let us verify the outputs using a Java program:

As we can see in the above example, it returns NaN for NaN or negative numbers, or negative Infinity as arguments. It returns 0.0 for 0 as an argument and Infinity for Double.POSITIVE_INFINITY as an argument.

Working of Math.sqrt() in Java

The square root of a number in Java is calculated using simple arithmetic operations such as addition, subtraction, multiplication, and division. And lastly, with the help of loops, we get the desired answer. The mathematical formula used to find the square root precisely is given below.

Algorithm for Finding Square Root of a Number in Java

We firstly take two variables num and half . num is left uninitialized and half is initialized as value/2 . We run a do-while loop, inside do-while loop we initialized num=half each time the loop runs, and half = (num + value/num) where value is user-entered number. We run this loop until num is not equal to half . As this condition satisfies half is the required square root of value .

Java Math sqrt()

In this tutorial, we will learn about the Java Math.sqrt() method with the help of examples.

The sqrt() method returns the square root of the specified number.

Example

Syntax of Math.sqrt()

The syntax of the sqrt() method is:

Here, sqrt() is a static method. Hence, we are accessing the method using the class name, Math .

sqrt() Parameters

The sqrt() method takes a single parameter.

  • num — number whose square root is to be computed

sqrt() Return Values

  • returns square root of the specified number
  • returns NaN if the argument less than 0 or NaN

Note: The method always returns the positive and correctly rounded number.

Example: Java Math sqrt()

In the above example, we have used the Math.sqrt() method to compute the square root of infinity, positive number, negative number, and zero.

Here, Double.POSITIVE_INFINITY is used to implement positive infinity in the program.

When we pass an int value to the sqrt() method, it automatically converts the int value to the double value.

Class Math

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *