Monday 6 June 2022

Java math: copySign: Copy the sign of argument

‘copySign’ method returns the first floating-point argument with the sign of the second floating-point argument.

 

Signature

public static double copySign(double a, double b)

public static float copySign(float a, float b)

 

Return the value of ‘a’ by copying the sign of value ‘b’.

 

Examples

Math.copySign(10.030000, 114.000000) = 10.030000

Math.copySign(10.030000, -10.800000) : -10.030000

Math.copySign(-10.800000, 114.000000) : 10.800000

Math.copySign(-10.800000, -11.500000) : -10.800000

 

Find the below working application.

 


 

CopySign.java

package com.sample.app;

public class CopySign {
	public static void main(String[] args) {
		
		float f1 = 10.03f;
		float f2 = 114f;
		float f3 = -10.8f;
		float f4 = -11.5f;
		
		System.out.printf("Math.copySign(%f, %f) = %f\n", f1, f2, Math.copySign(f1, f2));
		System.out.printf("Math.copySign(%f, %f) = %f\n", f1, f3, Math.copySign(f1, f3));
		System.out.printf("Math.copySign(%f, %f) = %f\n", f3, f2, Math.copySign(f3, f2));
		System.out.printf("Math.copySign(%f, %f) = %f\n", f3, f4, Math.copySign(f3, f4));
		
		double d1 = 10.03;
		double d2 = 114;
		double d3 = -10.8;
		double d4 = -11.5;
		
		System.out.printf("\nMath.copySign(%f, %f) = %f\n", d1, d2, Math.copySign(d1, d2));
		System.out.printf("Math.copySign(%f, %f) = %f\n", d1, d3, Math.copySign(d1, d3));
		System.out.printf("Math.copySign(%f, %f) = %f\n", d3, d2, Math.copySign(d3, d2));
		System.out.printf("Math.copySign(%f, %f) = %f\n", d3, d4, Math.copySign(d3, d4));
		
	}

}

Output

Math.copySign(10.030000, 114.000000) = 10.030000
Math.copySign(10.030000, -10.800000) : -10.030000
Math.copySign(-10.800000, 114.000000) : 10.800000
Math.copySign(-10.800000, -11.500000) : -10.800000

Math.copySign(10.030000, 114.000000) = 10.030000
Math.copySign(10.030000, -10.800000) : -10.030000
Math.copySign(-10.800000, 114.000000) : 10.800000
Math.copySign(-10.800000, -11.500000) : -10.800000



Previous                                                 Next                                                 Home

No comments:

Post a Comment