ndarray icon indicating copy to clipboard operation
ndarray copied to clipboard

[Feature Request] More powerful `power` like `numpy.power`

Open duskmoon314 opened this issue 1 year ago • 2 comments

#1042 has added element-wise power methods powi and powf. But they only accept one parameter.

In NumPy, numpy.power receives two arrays, x1 and x2. The latter could be a number or an array and performs power with different exponents.

An example from: https://numpy.org/doc/stable/reference/generated/numpy.power.html#numpy.power

x1 = np.arange(6)
x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
np.power(x1, x2)
# array([  0.,   1.,   8.,  27.,  16.,   5.])

Though we may archive this using an iterator, a more powerful function might fill the gap for users coming from NumPy.

duskmoon314 avatar Jun 11 '24 06:06 duskmoon314

I think this falls under the "too many methods" problem, but other maintainers may have a different opinion.

You might already know, but what you request can be coded like this

let ans = Zip::from(&x1).and(&x2).map_collect(|&a, &b| a.powi(b));  // Or powf

nilgoyette avatar Jun 11 '24 17:06 nilgoyette

I think this falls under the "too many methods" problem

Indeed. Adding more methods would be convenient when people want to port some Python code to Rust. I opened this issue while trying to port some Python code and found out I needed to use iterators.

However, this would also make implementation and maintenance more complex and may confuse users. I genuinely think more discussion should be taken.

duskmoon314 avatar Jun 12 '24 01:06 duskmoon314

(just accidentally found this issue)

From a user's perspective there's already a lot of methods for ArrayBase and diluting them for more similarity with dynamically typed NumPy will only make the methods more difficult to navigate and discover.

If this functionality were added via generics it could be nice to have, but I guess generics would be very hard to implement.

And personally I find @nilgoyette solution sufficient. Iterators are a staple feature of Rust and are used everywhere. That solution is a little bit verbose but also idiomatic. So I would say, Rust doesn't have to be like Python I guess...

Quba1 avatar Aug 18 '24 20:08 Quba1

I'm gonna agree with @nilgoyette that this gets close to muddying the waters of the API for a function that could be implemented as a one-liner. At some point (when ndarray is more stable?) we could discuss whether there should be a crate that provides support for the Python Array API, but I don't think that time is now.

With two maintainer votes for closing and the OP's thumbs-up on the alternative implementation, I'm going to close. Maintainers, please re-open if you think that's a mistake.

akern40 avatar Aug 19 '24 04:08 akern40