3

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.

2
  • check out np.vectorize Commented Oct 5, 2017 at 15:03
  • 4
    Use NumPy funcs - Replace m. with np.. Commented Oct 5, 2017 at 15:04

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This much appreciated. Thank you very much for the tip! I've been working with Matlab in the past, and now migrating to Python. I'm amazed how powerful and community-rich Python is.
2

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)

1 Comment

Thank you very much for the tip! I'll replace it now
0

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.

1 Comment

Thank you very much for the tip! I'll start using numpy ans scipy functions whenever needed now :)
-1

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.

3 Comments

No. using python loops (yes, even list comprehensions) is much slower than numpy/scipy methods applied to vectors.
If you're using numpy you should still ALWAYS use numpy functions. Your function is converting a vector to a list as well.
Nitpick, map does not produce a generator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.