2

I have an allegedly easy to solve question, but i still cannot figure it out:

I have an array with 1000 numbers called "mu" like this:

array([2.25492522e-01, 2.21059993e-01, 2.16757006e-01,....)

Now i need to plug these values in two different functions: For numbers in the array, that are less than 0.009, i need to use equation1:

nu = 1 - 5.5 * mu**(0.66) + 3.77 * mu

For all other numbers in the array, i need to plug these into equation2:

nu = 0.819**(-11.5*mu)+0.0975**(-70.1*mu)

In the end, i need an array of the function values "nu".

I gave this code a try, but it didn't work

for item in mu:
    if item < 0.009:
       nu = 1 - 5.5 * mu**(0.66) + 3.77 * mu
    else:
       nu = 0.819**(-11.5*mu)+0.0975**(-70.1*mu)

print nu

How can I tell Python to put the right numbers in?

1 Answer 1

3

One problem is you aren't using item in your for loop. Nor are you appending to a list or assigning to a new array to store your results. In any case, NumPy has specific functions designed for this task. For example, using numpy.where:

def func1(x):
    return 1 - 5.5 * x**(0.66) + 3.77 * x

def func2(x):
    return 0.819**(-11.5*x)+0.0975**(-70.1*x)

res = np.where(mu < 0.009, func1(mu), func2(mu))

While you may feel this is inefficient as twice as many calculations are being processed than required, this is far outweighted by the benefits of vectorised operations.

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

1 Comment

Thank you, jpp. Your provided answer works as expected!

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.