[Python-ideas] Why no sign function?
Mark Dickinson
dickinsm at gmail.com
Tue Apr 27 12:36:37 CEST 2010
On Tue, Apr 27, 2010 at 10:52 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Mark Dickinson wrote:
>> On Mon, Apr 26, 2010 at 10:36 PM, Mark Dickinson <dickinsm at gmail.com> wrote:
>> I wouldn't object to a `math.is_signed` function or a
>> `float.is_signed` method with these semantics. It's not clear where
>> is the better place: we have `math.isnan` and `math.isinf`, but
>> `float.is_integer`.
>
> "is_signed" would probably be a bad name for this purpose. In typical
> compsci parlance, all of our numeric types are signed.
I agree that it's not a great name. It comes from the Decimal module:
there's a Decimal.is_signed method. That name in turn comes from the
specification, which calls it "is-signed". I'd have preferred
is_negative, but that's not really right either, since -0.0 isn't
strictly speaking negative.
> For the semantics you're talking about, math.signbit would be a more
> reasonable name. (since we can legitimately answer the question for both
> integers and floats, whereas "is_integer" is a pretty redundant question
> if you are dealing with an integer type)
And if it's a function in the math module, it seems entirely
reasonable to re-use the C99 name.
So the proposal is: add a math.signbit function, with exactly the
same semantics as the C99 signbit function: returning 1 for values
with the signbit set (negative values, -0.0, nans with the sign bit
set) and 0 otherwise. It would return 0 for a zero integer, too. A
Python implementation is as simple as:
import math
def signbit(x):
return 1 if math.copysign(1.0, x) == -1.0 else 0
Would this be of value to anyone? I'd only vote +0, since I don't
feel a great need for this function.
By the way, the signbit function definitely does have uses: for
example, it's useful for implementing odd (in the mathematical sense)
functions like asinh while making sure that signed zeros are treated
correctly:
def asinh(x):
if signbit(x):
return -asinh(-x)
# deal with nonnegative values here
If the test were simply "if x > 0.0:" then (depending on exactly what
the rest of the function looks like) you'd risk getting the wrong sign
for at least one of 0.0 and -0.0. Of course, you can still use
copysign to do the test, as above, but it's clunkier.
Mark
More information about the Python-ideas
mailing list