On Wed, Dec 29, 2021 at 4:54 AM Christopher Barker <[email protected]> wrote: > > On Tue, Dec 28, 2021 at 5:31 AM David Mertz, Ph.D. <[email protected]> > wrote: >> >> On Tue, Dec 28, 2021 at 1:15 AM Christopher Barker <[email protected]> >> 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 .... >
I'm not sure about that. >>> numpy.log(2.71828) 0.999999327347282 >>> numpy.log([2.71828]) array([0.99999933]) >>> type(numpy.log(2.71828)) <class 'numpy.float64'> >>> type(numpy.log([2.71828])) <class 'numpy.ndarray'> If you pass a scalar to log(), you get back a scalar, not an array. Whereas asarray would return an array with no dimensions. Not sure how significant that is, but it does still distinguish between values and arrays. ChrisA _______________________________________________ Python-ideas mailing list -- [email protected] To unsubscribe send an email to [email protected] https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/[email protected]/message/5EXROD33XVS5AOHRWUVXILHU3ZPENBS6/ Code of Conduct: http://python.org/psf/codeofconduct/
