How to use arrays/vectors in a Python user-defined function?

Viewed 1841

I'm building a function to calculate the Reliability of a given component/subsystem. For this, I wrote the following in a script:

import math as m
import numpy as np

def Reliability (MTBF,time):
  failure_param = pow(MTBF,-1)
  R = m.exp(-failure_param*time)
  return R

The function works just fine for any time values I call in the function. Now I wanna call the function to calculate the Reliability for a given array, let's say np.linspace(0,24,25). But then I get errors like "Type error: only length-1 arrays can be converted to Python scalars".

Anyone that could help me being able to pass arrays/vectors on a Python function like that?

Thank you very much in advance.

4 Answers

The math.exp() function you are using knows nothing about numpy. It expects either a scalar, or an iterable with only one element, which it can treat as a scalar. Use the numpy.exp() instead, which accepts numpy arrays.

To be able to work with numpy arrays you need to use numpy functions:

import numpy as np

def Reliability (MTBF,time):
    return np.exp(-(MTBF ** -1) * time)

If possible you should always use numpy functions instead of math functions, when working with numpy objects.

They do not only work directly on numpy objects like arrays and matrices, but they are highly optimized, i.e using vectorization features of the CPU (like SSE). Most functions like exp/sin/cos/pow are available in the numpy module. Some more advanced functions can be found in scipy.

Rather than call Reliability on the vector, use list comprehension to call it on each element:

[Reliability(MTBF, test_time) for test_time in np.linspace(0,24,25)]

Or:

map(Reliability, zip([MTBF]*25, linspace(0,24,25))

The second one produces a generator object which may be better for performance if the size of your list starts getting huge.

Related