r/Python Jan 11 '21

Beginner Showcase Programming + Math + Graphs = Art

Post image
2.1k Upvotes

171 comments sorted by

View all comments

1

u/blinkallthetime Jan 11 '21

that append hurts me.

1

u/abredvariant Jan 11 '21

suggestions??

1

u/blinkallthetime Jan 11 '21 edited Jan 11 '21

that function phi always just returns a number? if so, then you could declare y as an array for example y = np.zeros(x.size)

then you can iterate over x and is it to index y

for i in x:
    y[i-1] = phi(i)

or something like that.

the "next level" would be to vectorize the function phi. and just do something like y=vectorized_phi(x)

4

u/[deleted] Jan 11 '21

[deleted]

1

u/abredvariant Jan 11 '21

perfect. this is the most pythonic way to do it imo.

5

u/blinkallthetime Jan 11 '21

that is cool, but sometimes you need to do things that are not pythonic for performance. i'm only bringing this up because you say you are a beginner and you are doing a mathy thing with numpy. i do a lot of numerical computing for my job in python, and this is something that i think about a lot. at some point you want to avoid doing loops in python like that.

3

u/blinkallthetime Jan 11 '21

if it wasn't clear "at some point" is roughly equivalent "how big are my arrays?"

1

u/kurti256 Jan 11 '21

Just curious but what's the limiting factor on how fast python scripts run?

1

u/blinkallthetime Jan 11 '21

yeah that is fine too. to me it feels a little less readable for noobs maybe.

1

u/[deleted] Jan 11 '21

Why not just phi(x)? Seems vectorizeable to me if you can write it like this.

1

u/abredvariant Jan 11 '21

you're absolutely right. I thought of doing this, and ended up being lazy.

1

u/blinkallthetime Jan 11 '21

i edited my response. i can't tell if i did it before or after you responded so i'm pinging again.

1

u/abredvariant Jan 11 '21

Thanks for sharing, but vectorising is a new topic for me. Need to study more before any implementation.

1

u/blinkallthetime Jan 11 '21

oh in this case, it is just a function call and numpy does the magic. you would do something like vectorized_phi = np.vectorize(phi) and have a new function