This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mark.dickinson
Recipients fkbreitl, gekonntde, mark.dickinson, rhettinger, valhallasw
Date 2012-03-13.22:42:00
SpamBayes Score 2.3532842e-12
Marked as misclassified No
Message-id <1331678521.29.0.509969716324.issue829370@psf.upfronthosting.co.za>
In-reply-to
Content
> Mark, the convincing use-cases apear already on this page.

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?
History
Date User Action Args
2012-03-13 22:42:01mark.dickinsonsetrecipients: + mark.dickinson, rhettinger, gekonntde, valhallasw, fkbreitl
2012-03-13 22:42:01mark.dickinsonsetmessageid: <1331678521.29.0.509969716324.issue829370@psf.upfronthosting.co.za>
2012-03-13 22:42:00mark.dickinsonlinkissue829370 messages
2012-03-13 22:42:00mark.dickinsoncreate