2

I am using math.erf to find the error function of each element in an array.

# Import the erf function from the math library
from math import erf
# Import the numpy library to represent the input data
import numpy as np

# Create a dummy np.array
dummy_array = np.arange(20)

# Apply the erf function to the array to calculate the error function of each element
erf_array = erf(dummy_array)

I am getting an error as I cannot apply this whole function to an array. Is there a way to apply the error function to the whole array (vectorised approach) without looping through each element and applying it? (The loop will take a lot of time as the tables will be large)

78282219
  • 159
  • 1
  • 12

2 Answers2

5
from scipy import special
import numpy as np

dummy_array = np.arange(20)
erf_array = special.erf(dummy_array)

It is essential that you import the special subpackage as from scipy import special. Importing just scipy as import scipy and then calling scipy.special.erf() won't work, as explained here and here.

Stef
  • 28,728
  • 2
  • 24
  • 52
  • I mean... you could just do `import scipy.special` then use `scipy.special.erf`. – Tadhg McDonald-Jensen Sep 19 '21 at 22:26
  • Is this actually faster than looping with math.erf()? – Anonymous Dec 05 '21 at 11:32
  • 1
    @Anonymous: yes, even for the given example with 20 elements I get 4 µs for `%timeit special.erf(dummy_array)` and 12 µs for `%timeit np.array([math.erf(element) for element in dummy_array])` (and 7 µs without array creation). For larger arrays the difference becomes bigger. – Stef Dec 05 '21 at 11:45
1

you can use list comprehension to apply the function to each element at once erf_array = [erf(element) for element in dummy_array)]

Ramzi
  • 11
  • 1
  • This will end up with a usual Python list, not a numpy array, which I presume OP wants implicitly. In this case the list should be fed to numpy’s `array` function, so that might be not as efficient due to reallocation. – arseniiv Jun 23 '21 at 18:04