Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently using Numpy to assign function values to array

I am interested in finding the fastest way of carrying a simple operation in Python3.6 using Numpy. I wish to create a function and from a given array to an array of function values. Here is a simplified code that does that using map:

import numpy as np
def func(x):
    return x**2
xRange = np.arange(0,1,0.01)
arr_func = np.array(list(map(func, xRange)))

However, as I am running it with a complicated function and using large arrays, runtime speed is very important for me. Is there a known faster way?

EDIT My question is not the same as this one, because I am asking about assigning from a function, as opposed to a generator.

like image 392
splinter Avatar asked Aug 16 '17 08:08

splinter


1 Answers

Check the related How do I build a numpy array from a generator?, where the most compelling option seems to be preallocating the numpy array and setting values, instead of creating a throwaway intermediate list.

arr_func = np.empty(len(xRange))
for i in range(len(xRange)):
  arr_func[i] = func(xRange[i])
like image 81
orip Avatar answered Oct 12 '22 22:10

orip