'How is math.copysign(x, y) in Python useful?
I was going over the functions of the math module in Python and found the math.copysign (x,y) function. I want to know when someone would use this function. I check many websites and they show how to use the function. I understand how to use it, but I would like to know in which cases it will be useful to get the absolute value of the first argument and the sign of the second.
math.copysign(x, y)
Solution 1:[1]
Here's one easy example. Suppose I'm writing a game, and I want the enemy to move toward the player at a given speed. The speed is determined by one variable and the direction is determined by where the player is
enemy.velocity = math.copysign(enemy.base_speed, player.xposition - enemy.xposition)
This sort of vector math (here, it's really just directional math, since we're dealing in one dimension) becomes second nature when you've used it awhile.
Solution 2:[2]
Could be useful when trying to find positive or negative floats.
I just stumbled on error in my code, which was solved by copysign:
#Error:
#a is a float value:
a=-0.0004
if int(a) < 0:
#do something
Won't work, because int(-0.004) will be 0, which has no sign.
So had to change to:
a=-0.0004
if math.copysign(1,a) < 0:
#do something
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Silvio Mayolo |
Solution 2 | Gnudiff |