2

I have a function:

import numpy as np, random

def simulation(low, high, num_pairs):
    c = np.round(np.random.uniform(low, high, num_pairs), 2)
    n = np.round((0.4*c-0.8), 2) # calculate rounded value
    n = np.where(n < 0, 0, n) # if negative `n`, make zero, else `n`
    return list(zip(c, n))

Calling this:

c_n_pairs = simulation(0, 15, 10)
print(*c_n_pairs, sep = "\n")

Outputs:

(5.69, 1.48)
(11.33, 3.73)
(7.16, 2.06)
(2.93, 0.37)
(8.47, 2.59)
(12.82, 4.33)
(12.84, 4.34)
(7.12, 2.05)
(7.11, 2.04)
(0.07, 0.0)

What I have works, but I'm wondering about the two n statements and if those can be consolidated into one.

    n = np.round((0.4*c-0.8), 2) # calculate rounded value
    n = np.where(n < 0, 0, n) # if negative `n`, make zero, else `n`
1
  • Right, I was caught between a couple different thoughts and didn't think that through. Commented Feb 22, 2020 at 15:55

1 Answer 1

1

You can use np.maximum to take the elementwise maximum for an array. This allows you to check if each element is less than zero and replace it with zero if this is the case, exactly the same as np.where.

def simulation(low, high, num_pairs):
    c = np.round(np.random.uniform(low, high, num_pairs), 2)
    n = np.maximum(np.round((0.4*c-0.8), 2), 0)
    return list(zip(c, n))
Sign up to request clarification or add additional context in comments.

1 Comment

np.zeros(c.size) is redunded 0 is enogh

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.