How to create a random array in a specific range

Suppose I want to create a list or a numpy array of 5 elements like this:

array = [i, j, k, l, m] 

Where:

  • i is in the range from 1.5 to 12.4.
  • j is in the range from 0 to 5
  • k is in the range from 4 to 16
  • l is in the range of 3 to 5
  • m ranges from 2.4 to 8.9.

This is an example showing that some ranges include fractions. What would be an easy way to do this?

+6
source share
3 answers

You can just do it (thanks user2357112!)

 [np.random.uniform(1.5, 12.4), np.random.uniform(0, 5), ...] 

using numpy.random.uniform .

+10
source

I would suggest creating them manually and creating a list later:

 import numpy as np i = np.random.uniform(1.5, 12.4) j = np.random.randint(0, 5) # 5 not included use (0, 6) if 5 should be possible k = np.random.randint(4, 16) # dito l = np.random.randint(3, 5) # dito m = np.random.uniform(2.4, 8.9.) array = np.array([i, j, k, l, m]) # as numpy array # array([ 3.33114735, 3. , 14. , 4. , 4.80649945]) array = [i, j, k, l, m] # or as list # [3.33114735, 3, 14, 4, 4.80649945] 

If you want to create them at a time, you can use np.random.random use a range and a lower bound to change them and convert them to an integer where you don't want to swim:

 # Generate 5 random numbers between 0 and 1 rand_numbers = np.random.random(5) # Lower limit and the range of the values: lowerlimit = np.array([1.5, 0, 4, 3, 2.4]) dynamicrange = np.array([12.4-1.5, 5-0, 16-4, 5-3, 8.9-2.4]) # upper limit - lower limit # Apply the range result = rand_numbers * dynamicrange + lowerlimit # convert second, third and forth element to integer result[1:4] = np.floor(result[1:4]) print(result) # array([ 12.32799347, 1. , 13. , 4. , 7.19487119]) 
+6
source
 import random array = [random.uniform(1.5, 12.4), random.uniform(0,5)] print(array) 

prints:

 [9.444064187694842, 1.2256912728995506] 

You can combine them with round ()

+1
source

All Articles