copysign(): Copying Sign of One Number to Another

Copy sign of y to x
copysign(x, y)
Returns x with sign of y. Data type of return value is float.

Example
print(math.copysign(3, -2))  # -3.0
print(math.copysign(-3, -2)) # -3.0
print(math.copysign(-3, 2))  # 3.0
print(math.copysign(3, 2))   # 3.0
Switching signs:
import math

result = math.copysign(5, -3)
print(result)  # Output: -5.0
Ensuring positive values:
result = math.copysign(-7, 4)
print(result)  # Output: 7.0
Handling zero:
result = math.copysign(0, -2)
print(result)  # Output: -0.0
Finance:
Example: Adjusting losses based on market conditions
If you want to apply the sign of the market direction (positive for gains, negative for losses) to a specific amount:
import math

loss = math.copysign(5000, -1)  # Apply a negative sign to represent loss
print(loss)  # Output: -5000
Physics:
Example: Applying direction to velocity or force
When calculating velocity in physics, if direction matters:
velocity = math.copysign(20, -1)  # Negative velocity means moving in the opposite direction
print(velocity)  # Output: -20

Example 1: Basic Usage

Demonstrates the basic functionality of `copysign()`.
import math

print(math.copysign(3, -5))  # Output: -3.0
print(math.copysign(-4, 2))  # Output: 4.0

Example 2: Copying Sign with Zero

Handling zero, where the function can yield `+0.0` or `-0.0`.
print(math.copysign(0, -1))  # Output: -0.0
print(math.copysign(0, 1))   # Output: 0.0

Example 3: Adjusting Values in Scientific Calculations

Used in scientific contexts where you need the absolute value with a specific sign.
values = [10, -20, 15, -25]
adjusted = [math.copysign(val, -1) for val in values]
print(adjusted)
Output
[-10.0, -20.0, -15.0, -25.0]

Applications of copysign()

  • Data Normalization: Standardize signs across datasets.
  • Scientific Computing: Adjust values based on specific sign conditions.
  • Financial Calculations: Control sign in calculations, such as debits and credits.


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer