Generate a numpy array from a python function -


i have thought simple task in numpy, i'm having trouble.

i have function takes index in array , returns value belongs @ index. to, efficiently, write values numpy array.

i have found numpy.fromfunction, doesn't behave remotely documentation suggests. seems "vectorise" function, means instead of passing actual indices passes numpy array of indices:

def vsin(i):     return float(round(a * math.sin((2 * pi * wf) * i)))  numpy.fromfunction(vsin, (len,), dtype=numpy.int16) # typeerror: length-1 arrays can converted python scalars 

(if use debugger inspect i, numpy.array instance.)

so, if try use numpy's vectorised sin function:

def vsin(i):     return (a * numpy.sin((2 * pi * wf) * i)).astype(numpy.int16)  numpy.fromfunction(vsin, (len,), dtype=numpy.int16) 

we don't type error, if len > 2**15 discontinuities chopping accross our oscillator, because numpy using int16_t represent index!

the point here isn't sin in particular: want able write arbitrary python functions (whether numpy vectorised version exists or not) , able run them inside tight c loop (rather roundabout python one), , not have worry integer wraparound.

do have write own cython extension in order able this? doesn't numpy have support running python functions once per item in array, access index?

it doesn't have creation function: can use numpy.empty (or indeed, reuse existing array somewhere else.) vectorised transformation function do.

i think issue of integer wraparound unrelated numpy's vectorized sin implementation , use of python or c.

if use 2-byte signed integer , try generate array of integer values ranging 0 above 32767, wrap-around error. array like:

[0, 1, 2, ... , 32767, -32768, -32767, ...] 

the simplest solution, assuming memory not tight, use more bytes integer array generated fromfunction don't have wrap-around problem in first place (up few billion):

numpy.fromfunction(vsin, (len,), dtype=numpy.int32) 

numpy optimized work fast on arrays passing whole array around between vectorized functions. think in general numpy tools inconvenient trying run scalar functions once per array element.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -