[Numpy-discussion] Integers to integer powers

josef.pktd at gmail.com josef.pktd at gmail.com
Fri May 20 20:11:20 EDT 2016


On Fri, May 20, 2016 at 6:54 PM, Nathaniel Smith <njs at pobox.com> wrote:

> On May 20, 2016 12:44 PM, <josef.pktd at gmail.com> wrote:
> [...]
> >
> > can numpy cast to float by default for power or **?
>
> Maybe? The question is whether there are any valid use cases for getting
> ints back:
>
> >>> np.array([1, 2, 3]) ** 2
> array([1, 4, 9])
>
> It's not 100% obvious to me but intuitively this seems like an operation
> that we probably want to support? Especially since there's a reasonable
> range of int64 values that can't be represented exactly as floats.
>

It would still be supported by the np.power function with dtype keyword for
users that want to strictly control the dtype.

The question is mainly for the operator ** which doesn't have options and
there I think it's more appropriate for users that want correct numbers but
not necessarily have or want to watch out for the dtype.


Related: Python 3.4 returns complex for (-1)**0.5 while numpy returns nan.
That's a similar case of upcasting if the result doesn't fit.

Longterm I think it would still be nice if numpy could do value dependent
type promotion. e.g. when a value is encountered that doesn't fit, then
upcast the result at the cost of possibly having to copy the existing
results.
In the current setting the user has to decide in advance what the necessary
maybe required dtype is supposed to be. (Of course I have no idea about the
technical problems or computational cost of this.)

(Julia dispatch seems to make it easier to construct new types. e.g. we
could have a flexible dtype that is free to upcast to whatever is required
for the calculation. just guessing)


practicality:
going from int to float is a common usecase and we would expect getting the
correct numbers  2**(-2) -> promote

complex is in most fields an unusual outcome for integer or float
calculations
(e.g. box-cox transformation for x>0 )  having suddenly complex numbers is
weird, getting nans is standard float response  -> don't promote


I'm still largely in the python 2.x habit of adding a decimal points to
numbers for float or a redundant `* 1.` in my code to avoid integer
division or other weirdness. So, I never realized that ** in numpy doesn't
always promote to float which I kind of thought it did.
Maybe it's not yet time to drop all the decimal points or `* 1.` from the
code?


Josef



> -n
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> https://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20160520/3ad8bd6c/attachment.html>


More information about the NumPy-Discussion mailing list