How do you get a square root and an absolute value in Java?
Here is what I have:
if (variable < 0) {
variable = variable + variable2;
}
But is there an easier way to get the absolute value in Java?
variable = |variable|
The most common way to represent the absolute value of a number or expression is to surround it with the absolute value symbol: two vertical straight lines. |6| = 6 means “the absolute value of 6 is 6.” |–6| = 6 means “the absolute value of –6 is 6.” |–2 – x| means “the absolute value of the expression –2 minus x.”
√2≈1.414214 and it is a positive value, so the absolute value applied to √2 basically keep it unchanged.
Use the static methods in the Math
class for both - there are no operators for this in the language:
double root = Math.sqrt(value);
double absolute = Math.abs(value);
(Likewise there's no operator for raising a value to a particular power - use Math.pow
for that.)
If you use these a lot, you might want to use static imports to make your code more readable:
import static java.lang.Math.sqrt;
import static java.lang.Math.abs;
...
double x = sqrt(abs(x) + abs(y));
instead of
double x = Math.sqrt(Math.abs(x) + Math.abs(y));
Try using Math.abs:
variableAbs = Math.abs(variable);
For square root use:
variableSqRt = Math.sqrt(variable);
Use the java.lang.Math class, and specifically for absolute value and square root:, the abs()
and sqrt()
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With