[Numpy-discussion] using scalar and tuple/list input on np.PyArray_MultiIterNew2

Sebastian Berg sebastian at sipsolutions.net
Mon Jan 11 11:31:30 EST 2021


On Sun, 2021-01-10 at 14:18 -0700, zoj613 wrote:
> For what it's worth, I ended up defining a function like:
> cdef np.broadcast broadcast(object a, object b):
>     """
>     Broadcast the inputs into a multiIterator object.
>     the input can be a scalar, list, tuple or numpy array or
> array_like
> object.
>     """
>     cdef bint is_a_seq = is_sequence(h)
>     cdef bint is_a_seq = is_sequence(z)
> 
>     h = <double>h if not is_a_seq else np.PyArray_FROM_OT(a,
> np.NPY_DOUBLE)
>     z = <double>z if not is_b_seq else np.PyArray_FROM_OT(b,
> np.NPY_DOUBLE)
> 
>     return np.PyArray_MultiIterNew2(a, b)
> 
> It seems to do exactly what I want. Not sure if there are any
> potential bugs
> that could result from this approach.
> 

I guess you snipped some code away that does something with h and z?
Maybe it would help if you give an example, because I am still not sure
why `np.PyArray_MultiIterNew2(a, b)` is not what you want.

Is the issue is that you need to ensure a `double` result, and
`MultiIterNew()` will be equivalent to `np.asarray(a)` and not
`np.asarray(a, dtype=np.double)`?  If you want to ensure a double
result, I think it is likely easiest if you just call:
     a = np.PyArray_FROM_OT(a, np.NPY_DOUBLE)

unconditionally.  That is equivalent to calling `np.asarray(a,
dtype=np.double)` and will ensure that you get the double result that
you expect (it will force cast though).
You could still special case scalars of course (this is especially true
if you expect Python scalars `isinstance(a, float):` is a very fast
check.

The new iterator requires you to convert to arrays (sorry for not
copying the link, oddly enough my copy-paste was acting up), but it if
they are of a different dtype, it would allow you to cast in a buffered
way (much better if you expect large arrays, likely not for smaller
ones):
    https://numpy.org/doc/stable/reference/c-api/iterator.html#simple-iteration-example

Hope this helps.

Cheers,

Sebastian




--
Sent from: http://numpy-discussion.10968.n7.nabble.com/
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion at python.org
https://mail.python.org/mailman/listinfo/numpy-discussion


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <https://mail.python.org/pipermail/numpy-discussion/attachments/20210111/9a5b1711/attachment-0001.sig>


More information about the NumPy-Discussion mailing list