QuantEcon / QuantEcon.cheatsheet

A cheatsheet for Python and Julia
154 stars 64 forks source link

Update Python, MATLAB "Broadcasting" #66

Open ChrisRackauckas opened 5 years ago

ChrisRackauckas commented 5 years ago

Currently for "Broadcast a function over a collection/matrix/vector", the comparison between the functions isn't the same. For MATLAB and Python, no broadcasting is shown and "Functions broadcast directly" is said, but that's not how it's actually works. For example, f = @(x) x.^2 works because the internals of f are broadcasted itself. So the function f isn't actually acting on the scalars of x, it's acting on the full array x itself. And this is true for the Python x**2 which is working because that call itself is broadcasted.

This is not a trivial difference because if someone wanted to use this idea and then call an f on some arbitrary function of scalars, it will fail because the MATLAB and Python versions are assuming very specific properties of the functions inside of f which don't always hold. Contrast that to the Julia version where f is actually evaluated on the scalars.

So the easiest way to fix this is to use a map instead. A map is different from a broadcast because it requires that all inputs are the same size. This example, and many similar examples of "broadcast", are actually maps and so it can be good to show a user how to do this via an anonymous function. Broadcast however has shape detecting features. The classic example is the multiplication table 1:10 .* (1:10)'. This would be much more difficult to write in a general form in MATLAB and Python, so it much so that it might not be an easy enough example. Thus I would recommend changing the row to be about maps and using the map or . constructs in the languages.

arnavs commented 5 years ago

Thanks @chrisrackauckas for the detailed explanation. I’m not as fluent in MATLAB or Python, but I think this makes sense. I suppose the only potential thing to consider is how to keep things simple and novice-friendly.

cc @jlperla

jlperla commented 5 years ago

The purpose here to to help complete beginners map between things they know (e.g. writing a vectorized function in matlab or python) to Julia (and vice vera). So of course we don't want to go into all of the differences between Julia's beautiful broadcasting and ugly things like how python and matlab deal deal with these use cases.

Would the following make you happier:

Do you think it is worthwhile putting in numpy.vectorize for python as well? That is a lot closer to julias broadcasting.

ChrisRackauckas commented 5 years ago

Using numpy.vectorize and MATLAB map would be worthwhile, and saying "Map a function over a vector" would be the more universal term for what's being done.

arnavs commented 5 years ago

@ChrisRackauckas @jlperla Is there a consensus on what should be done here? Let me know and I can do it.

jlperla commented 5 years ago

Lets hold off. Lower priority than other QE stuff for julia.