rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations
https://docs.rs/ndarray/
Apache License 2.0
3.63k stars 307 forks source link

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

Closed duskmoon314 closed 3 months ago

duskmoon314 commented 5 months ago

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.

nilgoyette commented 5 months ago

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
duskmoon314 commented 5 months ago

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.

Quba1 commented 3 months ago

(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...

akern40 commented 3 months ago

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.