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?
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])
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.