# [issue829370] math.signum(int)

Mark Dickinson report at bugs.python.org
Tue Mar 13 23:42:01 CET 2012

```Mark Dickinson <dickinsm at gmail.com> added the comment:

I meant that I'd be interested to see examples of real code (e.g., specific numeric algorithms, etc.) where signum would be useful, and where existing functionality doesn't really do the job neatly.  In most examples I can think of, I'm either creating a sign only to multiply some quantity by it later, or I'm making some decision based on the sign.  In the first case, math.copysign usually fits the needs very well;  in the second, I only need a two-way choice anyway (until Python gets three-way if statements).

For example, a case that *seems* like it would be a good candidate for a sign function at first glance is computing the roots of a quadratic polynomial a*x**2 + b*x + c in a numerically safe manner.  There what you want to do is find the auxiliary quantity

q = -(b + sign(b)*sqrt(b**2 - 4*a*c))

and compute the roots as q / (2*a) and (2*c) / q.  [The point of doing it this way is to avoid loss of significant digits from a subtraction of nearly-equal quantities in the case where b is large compared to a and c.]

But that's a perfect use-case for copysign:  instead of first computing the sign of b and then multiplying by the sqrt, you'd just compute

q = -(b + copysign(sqrt(b**2 - 4*a*c), b))

Moreover, in this case you don't want the sign function described in this issue anyway, since it gives wrong results when b == 0;  you want a two-valued sign function that always gives -1 or 1, even for an argument of 0.

So, do you have better examples than the one above?

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue829370>
_______________________________________
```