Library contents

Python math.copysign

Combine the size of one value with the sign of another.

A simple example

math.copysign

  1. Start with Magnitude 2, sign from −1
  2. Do this Copy just the sign
  3. Result −2
The size stays 2. Only the sign comes from the second input.
lesson.py
import math
print(math.copysign(2.0, -1.0))
Output
-2.0

Syntax

Python syntax
math.copysign(magnitude, direction)
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Apply a refund direction to an amount

A payment system stores an amount separately from whether it is a charge or a refund. Reuse the amount's magnitude while applying the direction belonging to the current transaction.

From the programmagnitude = 7.0
Result-7.000
lesson.py
import math

magnitude = 7.0
direction = -1.0

print(f"{math.copysign(magnitude, direction):.3f}")
Output
-7.000

A refund direction makes the seven-unit adjustment negative.

Advertisements

Label a return transaction

A cashier has a receipt amount of 24 credits and a negative return indicator. The journal uses the indicator to set the sign on the amount.

Given24 · -1
Worked result-24

Using 24 · -1 gives -24 for this measurement.

Restore a forward dial reading

A dial service receives a magnitude of twelve and a positive direction flag. It reconstructs the signed reading for the display.

Given12 · 1
Worked result12

Using 12 · 1 gives 12 for this measurement.

What to watch for

Some numeric formats distinguish negative zero from positive zero, including when used as the sign source.

Documentation for math.copysign