What is the Copysign function in Golang?

The Copysign function in the Go programming language returns a value with the magnitude of one argument and the sign of the other.

As the name suggests, the Copysign function copies the sign of the second argument onto the first argument.

To use this function, you must import the math package in your file and access the Copysign function within it using the . notation (math.Copysign). Here, Copysign is the actual function, while math is the Go package that stores the definition of this function.

Function definition

The definition of the Copysign function inside the math package is:

Parameters

Copysign function takes two arguments of type float64:

  • x: The first argument represents the number whose magnitude will be used in the return value.

  • y: The second argument is the one whose sign is used in the return value.

Return value

The Copysign function returns a single value of type float64. This value consists of the magnitude of the first argument x and the sign of the second argument y.

This works for all numeric values, including infinite numbers.

NAN arguments are a special case. If the Copysign function is passed NAN as the first argument, the return value would be NAN regardless of the second argument. And if NAN is passed as the second argument, then the first argument is returned as it is.

Giving an empty argument or an argument that is not a numeric value results in an error.

Examples

Following is a simple example where we use the Copysign function on two decimal values of opposite signs:

package main
import("fmt"
"math"
)
func main() {
x := math.Copysign(10, -23)
fmt.Println(x)
}

In the following example, we can see how the copy sign function handles infinite numbers just like any other ordinary number. The returns -Inf, Inf come from the first argument while the - sign comes from the second argument:

package main
import("fmt"
"math"
)
func main() {
x := math.Copysign(math.Inf(1), -23)
fmt.Println(x)
}

Now we try the same thing, passing a NAN value instead of infinity:

package main
import("fmt"
"math"
)
func main() {
zero := 0.0
x := math.Copysign(zero/zero, -23)
y := math.Copysign( -23, zero/zero)
fmt.Println(x)
fmt.Println(y)
}

As displayed in the output above, with NAN in the first argument, NAN is returned, whereas when NAN is passed as the second argument, -23 is returned, which was the first argument.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved