Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get absolute values and square roots

Tags:

java

math

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|
like image 633
JXPheonix Avatar asked Mar 27 '12 21:03

JXPheonix


People also ask

How do you get absolute value?

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.”

What is the absolute value of square root of 2?

√2≈1.414214 and it is a positive value, so the absolute value applied to √2 basically keep it unchanged.


3 Answers

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));
like image 136
Jon Skeet Avatar answered Oct 20 '22 16:10

Jon Skeet


Try using Math.abs:

variableAbs = Math.abs(variable);

For square root use:

variableSqRt = Math.sqrt(variable);
like image 44
Dan W Avatar answered Oct 20 '22 17:10

Dan W


Use the java.lang.Math class, and specifically for absolute value and square root:, the abs() and sqrt() methods.

like image 1
amit Avatar answered Oct 20 '22 16:10

amit