-2

Let's say I have a single column float array of non-integer values:

Data = [1.1 ; 1.2 ; 1.3 ; 1.4 ; 1.5]

I would like to generate random numbers between two sequential values in this array and store those value in a new array. I.e the first value in the new array would be a random number between 1.1 and 1.2, the next random number between 1.2 and 1.3 and so on.

I'm looking to obtain a new array like data_rand = [1.15 ; 1.24 ; 1.37 ; 1.46] based on the original data array.

My question is (how would I / what is the best method to) iterate through all the values in an array and generate a non-integer random number between the each subsequent pair of numbers in the array, saving these random numbers into a new array? Could somebody provide an example based on this small 5-value data array? Or point me in the right direction for each stage of the process.

1
  • 2
    That's not Python - did you mean a list, like [1.1, 1.2, 1.3]? What have you tried so far, and what exactly is the problem with it?
    – jonrsharpe
    Commented Oct 10, 2014 at 14:06

3 Answers 3

1

To get a random value between a and b, you can add a random value between 0 and 1, multiplied by the absolute difference between a and b, to the smaller of a and b.

To get pairs of items in a list easily, you can use zip and a slice:

>>> l = [1, 2, 3]
>>> zip(l, l[1:])
[(1, 2), (2, 3)]

Beyond that, I suggest you have a go yourself.

0
import random    
rand_data = map(random.uniform, data[:-1], data[1:])

random.uniform(a, b) gives you a random floating point number between a and b. You can map this function to two slices of your list (the first slice removes the last element, the second slice removes the first element). So in your example, the two slices will look like this: [1.1, 1.2, 1.3, 1.4] and [1.2, 1.3, 1.4, 1.5].

0
import random

results = []
l = [1.1, 1.2, 1.3, 1.4, 1.5]

for x in zip(l, l[1:]):
  x = list(int(y * 100) for y in x)
  results.append(float(random.randrange(x[0], x[1])) / 100)

Here I multiply / divide by 100 because I wanted 2 decimals, use 10 for 1 decimal.

Output:

results

[1.14, 1.22, 1.37, 1.44]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.