jeudi 10 mai 2018

Python - Generate random real number between range with a step size

I am using python-3.x, and I am trying to generate an initial population that contains random real numbers between 0 and 1 where these numbers should be one of the following: 0, 0.33333, 0.666667 or 1

That means the difference between these numbers is 0.33333 (1/3). I tried to modify this code in many ways but their no luck

import numpy as np
import random
from random import randint
from itertools import product
pop_size = 7
i_length = 2
i_min = 0
i_max = 1
level = 2
step = ((1/((2**level)-1))*(i_max-i_min))

def individual(length, min, max):
    return [ randint(min,max) for x in range(length) ]
def population(count, length, min, max):
    return [ individual(length, min, max) for x in range(count) ]

population = population(pop_size, i_length, i_min, i_max)

##count: the number of individuals in the population
##length: the number of values per individual
##min: the minimum possible value in an individual's list of values
##max: the maximum possible value in an individual's list of values
##this code was taken from :https://lethain.com/genetic-algorithms-cool-name-damn-simple/

I did this lines which works very well for me:

population2 = np.array(list(product(np.linspace(i_min, i_max, 2**level), repeat=2)))
population3 = [j for j in product(np.arange(i_min, i_max+step, step), repeat=2)]

but the problem it will list all the possible values which are not what I want. I want random numbers where the population size will be given

the result I want to see is smailar to (numpy array or list):

population = [[0, 1],
             [0, 0.3333],
             [0.3333, 1],
             [1, 0.6667],
             [0.3333, 0.6667],
             [0.6667, 0],
             [0.3333, 0.3333]]

Any advice would be much appreciated




Aucun commentaire:

Enregistrer un commentaire