298. copysign — Stamp One Number's Sign Onto Another, Sign Bit and All
Bite 297 showed signum reading the sign bit. copysign is the other half: it writes one — take this magnitude, give it that number’s sign, one call.
The branch
You have a fixed magnitude and a direction living in another variable — a step size, a force, a correction — and out comes the same conditional every time:
| |
One call
| |
The receiver contributes the magnitude, the argument contributes the sign. Yesterday’s “step toward the target” loop works for floats too — magnitude from you, direction from the gap:
| |
It really is the sign bit
Like f64::signum, copysign works on the raw sign bit — which is exactly what makes it more honest than the if:
| |
Anywhere you’re bolting a direction onto a magnitude — drag opposing velocity, rounding away from zero, mirroring a coordinate — copysign is the branch-free, -0.0-correct way to say it.