Selected Reading

C++ cmath copysign() Function



The C++ cmath copysign() function is a floating-point manipulation function that takes two floating-point numbers as its parameters. It returns a new number that has the same absolute value (magnitude) as the first parameter but uses the sign (positive or negative) of the second parameter.

This function is helpful when you want to change the size of a number while keeping its positive or negative direction intact.

Syntax

Following is the syntax for C++ cmath copysign() function.

double copysign(double x, double y);
or
float copysign(float x, float y);
or
long double copysign(long double x, long double y);

Parameters

  • x - The value with the magnitude of the resulting value.

  • y - The value with the sign of the resulting value.

Return Value

The function returns the value with a magnitude of x and the sign of y.

Time Complexity

The time complexity of this function is constant, i.e.,O(1).

Example 1

The following example shows, the basic usage of copysign(x,y). The function returns the positive number but changes its sign to negative, demonstrating how it can adjust the sign of a number based on another.

#include <iostream>
#include <cmath>
int main() {
   double x = 5.0;
   double y = -3.0;
   double result = std::copysign(x, y);
   std::cout << "copysign(" << x << ", " << y << ") = " << result << std::endl;

   return 0;
}

Output

Output of the above code is as follows

copysign(5, -3) = -5

Example 2

In this example, we apply std::copysign with a negative number and a positive number. The function takes the magnitude of the negative number and changes it to positive based on the sign of the second number.

#include <iostream>
#include <cmath>
int main() {
   long double x = -7.5L;
   long double y = 4.2L;
   long double result = std::copysign(x, y);
   std::cout << "copysign(" << x << ", " << y << ") = " << result << std::endl;

   return 0;
}

Output

Following is the output of the above code

copysign(-7.5, 4.2) = 7.5

Example 3

In the following example, we demonstrate the use of the copysign() function in combination with a mathematical function (square root).

#include <iostream>
#include <cmath>
int main() {
   double x = sqrt(16.0);
   double y = -1.0;
   double result = copysign(x, y);
   std::cout << "copysign(sqrt(16.0), -1.0) = " << result << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output

copysign(sqrt(16.0), -1.0) = -4
cpp_cmath.htm
Advertisements