def flip(x, p = p, q = q, m = m):
     if rng.flip(p, q):
         y = m[rng.random() % len(m)]
         if rng.flip(1, 2):
             return x + y
         return x - y
     return x
def refill(pop):
    """Get rid of duplicates."""

    for l in pop:
        l[9] = sgn(l[9])
        l[-1] = abs(l[-1])
    pop.sort()

    newpop = [0] * Npop
    i = 0
    last = None
    for l in pop:
        if l != last:
            newpop[i] = l
            i += 1
        last = l
    for j in xrange(i, Npop):
        a = rng.random() % i
        b = rng.random() % i
        newpop[j] = breed(newpop[a], newpop[b])

    return newpop
def newpop(result):
    """The result of a generation is a list of pairs, where each
    pair consists of the fitness value and the individual that
    generated it.  Construct a new population (formatted as a
    list of lists) using the following steps:
        1. Sort by the fitness value (smallest first).
        2. Replace the last half of the sorted population with
           new individuals bred from pairs chosen at random
           from the first half.
    The new population is returned."""

    result.sort()
    printf('%d: %g, %s\n', Gen, result[0][0], result[0][1])
    pop = [0] * Npop
    cut = int(Npop * .5)
    for i in xrange(cut):
        pop[i] = result[i][1]
    for i in xrange(cut, Npop):
        a = rng.random() % cut
        b = rng.random() % cut
        pop[i] = breed(result[a][1], result[b][1])

    return pop
def ga():
    """Run the GA over many generations."""

    global Start, Gen

    pop = initpop(args)
    while 1:
        f = open('curpop', 'w')
        fprintf(f, '# %s\n', Opts)
        for l in pop:
            fprintf(f, '%s\n', string.join(map(str, l)))
        f.close()
        pop = refill(pop)
        result = run(pop)
        pop = newpop(result)
#                Start = Start + Len
        Start = rng.random() % 1000000000
        Gen += 1
def cross(l1, l2, p):
    """cross(list, list, probability) -> list

    Take elements from one list until a crossover is made, then take
    elements from the other list, and so on, with the given probability
    of a crossover at each position.  The initial list is chosen at
    random from one of the two lists with equal probability.  The lists
    must be the same length."""

    l = [0] * len(l1)
    x = map(None, l1, l2)
    j = rng.random() % 2
    (p, q) = torat(p)
    for i in xrange(len(l1)):
        if rng.flip(p, q):
            j = 1 - j
        l[i] = x[i][j]

    return l
Ejemplo n.º 6
0
def Uniform(a,b):  
# --------------------------------------------
# * generate a Uniform random variate, use a < b 
# * --------------------------------------------
# */
  return (a + (b - a) * random())  
Ejemplo n.º 7
0
def Uniform(a,b):  
# --------------------------------------------
# * generate a Uniform random variate, use a < b 
# * --------------------------------------------
# */
  return (a + (b - a) * random())  

################################Main Program#############################

putSeed(-1)                   # any negative integer will do      */
seed = getSeed()              # trap the value of the intial seed */
crosses = 0                   # tracks number of crosses

for i in range(0,N):                
  u     = random() #get first endpoint                                  
  theta = Uniform(-HALF_PI, HALF_PI) #get Angle
  v     = u + R * cos(theta) #get second endpoint
  if (v > 1.0):
    crosses += 1 #increase number of crosses


p = float(crosses / N)                # estimate the probability */

print("\nbased on {0:1d} replications and a needle of length {1:5.2f}".format(N, R))
print("with an initial seed of {0:1d}".format(seed))
print("the estimated probability of a cross is {0:5.3f}".format(p))

#C output:
# based on 10000 replications and a needle of length  1.00
# with an initial seed of 1396907952
Ejemplo n.º 8
0
def Equilikely(a,b):        
# # ------------------------------------------------
# * generate an Equilikely random variate, use a < b 
# * ------------------------------------------------
# */
  return (a + int((b - a + 1) * random()))
Ejemplo n.º 9
0
def Uniform(a,b):  
# --------------------------------------------
# * generate a Uniform random variate, use a < b 
# * --------------------------------------------
# */
  return (a + (b - a) * random())  
Ejemplo n.º 10
0
def Exponential(m):
# ---------------------------------------------------
# * generate an Exponential random variate, use m > 0.0 
# * ---------------------------------------------------
# */
  return (-m * log(1.0 - random()))
Ejemplo n.º 11
0
def Equilikely(a, b):
    # # ------------------------------------------------
    # * generate an Equilikely random variate, use a < b
    # * ------------------------------------------------
    # */
    return (a + int((b - a + 1) * random()))
Ejemplo n.º 12
0
def Equilikely(a, b):
    #===================================================================
    #Returns an equilikely distributed integer between a and b inclusive.
    #NOTE: use a < b
    #===================================================================
    return (a + int((b - a + 1) * random()))
Ejemplo n.º 13
0
def Equilikely(a,b):          # use a < b */
# ============================== */
  return(a + int((b - a + 1) * random()))
Ejemplo n.º 14
0
#    j                              # row index                     */
#    k                              # column index                  */                        
#    temp1                          # first 2 by 2 determinant      */
#    temp2                          # second 2 by 2 determinant     */
#    temp3                          # third 2 by 2 determinant      */
#    x                              # determinant                   */

a = [[0 for i in range(0,4)] for i in range(0,4)]  # matrix (only 9 elements used) */
count = 0                      # counts number of pos det      */

putSeed(0)

for i in range(0,N):
  for j in range(1,4):
    for k in range(1,4):
      a[j][k] = random()
      if (j != k):
        a[j][k] = -a[j][k]
    #EndFor
  #EndFor
  temp1 = a[2][2] * a[3][3] - a[3][2] * a[2][3]
  temp2 = a[2][1] * a[3][3] - a[3][1] * a[2][3]
  temp3 = a[2][1] * a[3][2] - a[3][1] * a[2][2]
  x = a[1][1] * temp1 - a[1][2] * temp2 + a[1][3] * temp3
  if (x > 0):
    count += 1
#EndFor

print("\nbased on {0:1d} replications ".format(N))
print("the estimated probability of a positive determinant is:")
print("{0:11.9f}".format(float(count / N)))