
On Tue, Dec 28, 2021 at 5:31 AM David Mertz, Ph.D. <david.mertz@gmail.com> wrote:
On Tue, Dec 28, 2021 at 1:15 AM Christopher Barker <pythonchb@gmail.com> wrote:
On Mon, Dec 27, 2021 at 4:07 PM Steven D'Aprano
Julia (if I recall correctly) has a nice syntax for automatically turning any function or method into an element-wise function:
And numpy has an even easier one: np.log(a_scalar) np.log(an_array)
I have an @elementwise decorator I use for teaching decorators. I could dig it up, but everyone here could write it too. The main work is simply returning the same kind of collection that was passed in (as opposed to, e.g. always a list). But that's 2 lines of work.
and numpy has a vectorize() function, which, I only just realized, can be used as a decorator -- as long as you're happy with the defaults.
Ah, but numpy has to use their own special log function that does something like this:
# Obviously just pseudocode def numpy.log(obj): if obj is a scalar: return log(obj) # Scalar version. else: # Apply the log function to every element of the # vector, array or matrix. elements = [log(x) for x in obj] return type(obj)(elements) well, yes, numpy provides special functions, but they look more like this: def numpy.log(obj): obj = np.asarray(obj) return np._log(obj) where np._log is written in C. (yes, np.vectorize does indeed wrap the input function in a loop) Anyway, the point is that numpy works by having an nd-array as a first class object -- I suppose it's "only" for performance reasons that that's necessary, but it's why having a special notation to vectorize any function wouldn't be that helpful. it doesn't have to check "is this a scalar?", because ndarrays can be any (well up to 32) dimensionality -- a scalar, 1D, 2D, etc .... And I'm a bit confused as to why Julia needs that -- it's also based on arrays-as-first-class-objects, but I haven't looked at Julia for ages. Having said that, I do think that the vectorized approach makes for more readable, and less error prone, code for a large class of problems. I often use numpy when performance is a non-issue. In fact, numpy is slower than "pure python" for very small arrays, but I still use it. So having a built-in way to do vectorized operations would be pretty cool. I've often thought that a "numpython" interpreter would be pretty nifty -- it would essentially make ndarrays builtins, so that you could apply all sorts of nifty optimizations at run time. But I've never fleshed out that idea. -CHB -- Christopher Barker, PhD (Chris) Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython