Zephyrnet Logo

Math.sqrt – raiz quadrada em Java

Data:

Introdução

Calculating the square root of a number is one of the common operations we do in computer science. This simple mathematical function finds its use in all areas of programming – be it in algorithms or any other mathematical model we wish to represent, we’ll most likely use square roots in some way.

There are many ways in which we can calculate the square root of a number in Java, but the main topic of this article is the sqrt() método do Math classe.

A Matemática class in Java 8

A Math class contains methods for performing a variety of basic numeric operations such as logarithmic, square root, min and max, trigonometric functions etc. However, as stated earlier, the topic of this article is the sqrt() method implemented within this class. The sqrt() method has the following syntax:

public static double sqrt(double a)

It’s a pretty straightforward method, taking in a single double and returning a double as well. The method itself returns the correctly rounded positive square root of a double value. There are, however, a few special cases that require our attention while using this method:

  • Se o argumento for NaN ou menos que 0, then the result is NaN.
  • Se o argumento for infinito positivo, then the result is infinito positivo.
  • Se o argumento for infinito negativo, then the result is NaN.
  • Se o argumento for positivo 0 or negativo 0, then the result is the same as the argument given.

Otherwise, the result is the double value closest to the true mathematical square root of the argument value. There really isn’t much more to discuss with this method, so we can jump straight into an example:

double positiveNumberSqrt = Math.sqrt(137.4);
double negativeNumberSqrt = Math.sqrt(-137.4);
double invalidValueSqrt = Math.sqrt(0.0/0.0);
double positiveInfSqrt = Math.sqrt(Double.POSITIVE_INFINITY);
double negativeInfSqrt = Math.sqrt(Double.NEGATIVE_INFINITY);
double positiveZeroSqrt = Math.sqrt(0.0);
double negativeZeroSqrt = Math.sqrt(-0.0);

Conclusão

As you’ve seen in this short article, we used the Math.sqrt() method to showcase just how simple it is to find the square root of a number in Java. Of course, this isn’t the only way to find the square root of a number in Java, but it’s certainly the most elegant and the easiest one. We’ve also discussed the Math class a bit, which is also filled with a variety of mathematical functions that can fulfill the needs of most of our needs when it comes to math-related concepts.

local_img

Inteligência mais recente

local_img