1

I would like to get a random floating-point value between -2 and +2. The best I could do is:

my_array = [-1, 1]
change_sign = []
for i in range(6):
  change_sign.append(my_array[np.random.randint(low=0, high=2)] * 2)
print(change_sign)
results = np.random.random([6]) * change_sign

Desired output:

[-1.14, -0.25, 0.33, 1.75, 1.99, -0.83]

But I feel like it could be done even more easily. I don't want to use other numpy methods (like uniform), just random and randint.

How could I do that ?

2
  • Could you please add a desired output? Commented Apr 7, 2020 at 9:18
  • I added it to my message. Commented Apr 7, 2020 at 9:23

2 Answers 2

2

np.random.random returns a random float between 0.0 and 1.0

so you can multiply by 4 and subtract 2 so the range would be -2.0 to 2.0

np.random.random(6)*4 - 2
array([ 1.41044053, -0.97521584,  1.55446329, -0.54314241, -1.55691897,
        0.28276924])
Sign up to request clarification or add additional context in comments.

Comments

1

To get 'n' (= 10) random numbers between 'a' (= -2) and 'b' (= 2) use this formula:

n = 10
a = -2
b = 2

r = a + (b - a) * numpy.random.random(n)

Result:

array([ 0.29379447,  1.0017837 ,  0.46310858, -1.79242304,  1.04047713,
       -0.71521254,  0.32970214,  1.16248318, -1.12456574, -0.47470759])

Comments

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.