Java Math.signum() method returns the signum function of passed argument. If the argument is zero, it returns zero. If argument is negative, it returns -1.0. If argument is positive, it returns 1.0. In this tutorial, we will discuss signum() method with examples.
Note: In Mathematics, a signum function extracts the sign of a real number.
public class JavaExample { public static void main(String[] args) { double n1 = 15.5, n2 = -15.5, n3 = 0; System.out.println(Math.signum(n1)); System.out.println(Math.signum(n2)); System.out.println(Math.signum(n3)); } }
Output:
1.0 -1.0 0.0
Syntax of Math.signum() method
Math.signum(100); //returns 1.0
signum() Description
public static double signum(double d): Returns the signum function of the double value passed as an argument.
public static float signum(float f): Returns the signum function of the float value passed as an argument.
signum() Parameters
It takes a single parameter:
- d or f: A value whose sign is to be determined.
signum() Return Values
- 1.0 if the argument is positive.
- -1.0 if the argument is negative.
- zero if the argument is zero.
- NaN (Not a number) if the argument is NaN.
Example 1: Signum function of a Positive value
public class JavaExample { public static void main(String[] args) { double d = 123456; float f = 7.77f; System.out.println("Signum of +ve double: "+Math.signum(d)); System.out.println("Signum of +ve float: "+Math.signum(f)); } }
Output:
Example 2: Signum function of a negative value
public class JavaExample { public static void main(String[] args) { double d = -123456; float f = -7.77f; System.out.println("Signum of -ve double: "+Math.signum(d)); System.out.println("Signum of -ve float: "+Math.signum(f)); } }
Output:
Example 3: Signum function of zero
public class JavaExample { public static void main(String[] args) { double d = 0; float f = 0; System.out.println("Signum of zero double value: "+Math.signum(d)); System.out.println("Signum of zero float value: "+Math.signum(f)); } }
Output:
Example 4: Signum function of NaN
public class JavaExample { public static void main(String[] args) { double d = 0.0/0; //NaN System.out.println(Math.signum(d)); } }
Output: