AppDividend
Latest Code Tutorials

Java Math copySign() Function Example

0

Java math copySign() is an inbuilt method that copies the sign of the second argument to the magnitude of the first argument and returns the result. As per the definition given by Oracle, this method has implementations permitted, which treats some NaN arguments as positive and other NaN arguments as negative to allow the greater performance.

Java Math copySign()

The java.lang.Math.copySign() method returns a first argument with the sign of the second argument.

Syntax

public static float copySign(float a, float b)
public static double copySign(double a, double b)

Parameter(s)

Two parameters – the first for magnitude, the second for a sign.

Return Value

The magnitude of a first argument with the sign of the second argument.

See the following figure.

 

Java Math copySign()

Consider the following examples.

Example1.java: The following example demonstrates the use of this method.

See the following code.

public class Example1 {
  public static void main(String[] args) {
    float a = 124.5f;
    float b = -4.5f;

    double c = -4.5;
    double d = 124.5;

    System.out.println(Math.copySign(a, b));
    System.out.println(Math.copySign(c, d));
  }
}

Output

->javac Example1.java
->java Example1
-124.5
4.5

Example2.java: The following example demonstrates the situation when NaN is passed as the second argument.

See the following code.

public class Example2 {
  public static void main(String[] args) {
    float a = 124.5f;
    float b = Float.NaN;

    double c = -4.5;
    double d = Double.NaN;

    System.out.println(Math.copySign(a, b));
    System.out.println(Math.copySign(c, d));
  }
}

Output

->javac Example2.java
->java Example2
124.5
4.5

Example3.java: The following example demonstrates the situation when NaN is passed as the first argument.

See the following code.

public class Example3 {
  public static void main(String[] args) {
    float a = Float.NaN;
    float b = -4.5f;

    double c = Double.NaN;
    double d = 124.5;

    System.out.println(Math.copySign(a, b));
    System.out.println(Math.copySign(c, d));
  }
}

Output

->javac Example3.java
->java Example3
NaN
NaN

See also

Java Math nextUp()

Java Math nextDown()

Java Math nextAfter()

Java Math max()

Java Math floor()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.