本文整理汇总了Python中random.random函数的典型用法代码示例。如果您正苦于以下问题:Python random函数的具体用法?Python random怎么用?Python random使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了random函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: one_schedule_var
def one_schedule_var(P, mu, K, q, N, ucb_avg, l, R):
# one scheduling step
# P : permutation matrix
# mu : actual transmission rate
# K : number of queues
# q : current queuelengths
# N : number of samplings to be updates
# avg : number of samplings
# R : maximum alphabet size
rates = np.diag(P * np.transpose(mu))
# print P
# print "rates", rates
for i in range(K):
bit = random.random()
if bit <= l[i]:
q[i] = q[i] + 1
nodes = P * np.transpose(np.matrix(range(K)))
# print nodes
for i in range(K):
bit = random.random()
if bit <= float(rates[i] / R):
# print "testing"
if q[i] - R >= 0:
q[i] = q[i] - R
else:
q[i] = 0
ucb_avg[i, int(nodes[i])] = (N[i, int(nodes[i])] * ucb_avg[i, int(nodes[i])] + 1) / (
N[i, int(nodes[i])] + 1
)
N[i, int(nodes[i])] = N[i, int(nodes[i])] + 1
else:
ucb_avg[i, int(nodes[i])] = (N[i, int(nodes[i])] * ucb_avg[i, int(nodes[i])]) / (N[i, int(nodes[i])] + 1)
N[i, int(nodes[i])] = N[i, int(nodes[i])] + 1
示例2: __init__
def __init__(self, game, name="", description="", connections=[],
explored=False, itemchances=[0.5,0.25,0.1],
monsterchances=[0.3,0.2,0.1,0.05],
bosschances=[0.0], hint="" ):
"""need game instance"""
self.number = Room.number # void room has number 0
game.rooms[self.number] = self # add room into game dict
Room.number += 1
self.explored = explored # True or False
self.name = name
self.hint = hint # description of room if still unexplored
self.description = description
self.connections = connections
self.itemchances = itemchances
self.monsterchances = monsterchances
self.bosschances = bosschances
# create items
for chance in self.itemchances:
if random.random()< chance:
newItem = Item(game, self.number) # create item in this room
# create monsters
for chance in self.monsterchances:
if random.random() < chance:
newMonster = Monster(game, self.number) # create monster in this room
# create boss(es)
for chance in self.bosschances:
if random.random() < chance:
newMonster = Monster(game, self.number, boss=True)
示例3: test_complete_alignment
def test_complete_alignment(self):
""" Test the complete alignment in 2D routine (new) """
random.seed()
name=self.get_input_file_name("1z5s-projection-2.spi")
srw = IMP.em2d.SpiderImageReaderWriter()
image=IMP.em2d.Image()
image.read(name,srw)
transformed=IMP.em2d.Image()
rot=IMP.algebra.Rotation2D(random.random()*2*pi)
trans=IMP.algebra.Vector2D(random.random()*10,random.random()*10)
T=IMP.algebra.Transformation2D(rot,trans)
IMP.em2d.get_transformed(image.get_data(),transformed.get_data(),T)
fn_transformed = self.get_input_file_name("transformed.spi")
# transformed.write(fn_transformed,srw)
result=IMP.em2d.get_complete_alignment(image.get_data(),
transformed.get_data(),True)
fn_aligned = self.get_input_file_name("aligned_complete.spi")
# transformed.write(fn_aligned,srw)
cross_correlation_coefficient = result.second
# Tolerate 1 pixel error
self.assertAlmostEqual(cross_correlation_coefficient,1, delta=0.03,
msg="Error in the complete aligment routine,"
"ccc %f less than 0.97" % (cross_correlation_coefficient))
示例4: generateArr
def generateArr(duration, dataType):
if dataType == "int":
return [int(1000*random.random()) for i in xrange(duration * 64)]
elif dataType == "float":
return [1000*random.random() for i in xrange(duration * 64)]
else:
return []
示例5: on_run
def on_run(self):
"""Run when button is pressed."""
inside = 0
for i in xrange(self.samples):
sleep(0.001)
r1, r2 = (random(), random())
if r1*r1 + r2*r2 < 1.0:
inside += 1
if (i+1) % 100 == 0:
draws = i+1
self.emit('log', {
'draws': draws,
'inside': inside,
'r1': r1,
'r2': r2,
})
p = float(inside)/draws
uncertainty = 4.0*math.sqrt(draws*p*(1.0 - p)) / draws
self.emit('status', {
'pi-estimate': 4.0*inside/draws,
'pi-uncertainty': uncertainty
})
self.emit('log', {'action': 'done'})
示例6: func
def func(generation, parents_with_fit):
parents_with_fit.sort(key = lambda (_, f): f)
parents = map(lambda (p,_): p, parents_with_fit)
elite = parents[0:elite_count]
xover = parents[elite_count:xover_last_index]
xover_children = crossover_func(options, xover)
mutated_elite = mutate_func(generation, options, elite)
if cm_preserve:
xover_2_mutate = filter(lambda _: random.random() < cm_ch, xover_children)
mutated_xover = mutate_func(generation, options, xover_2_mutate)
# case cm_preserve
mutate_count = default_mutate_count - len(mutated_xover)
resulting_xover = xover_children + mutated_xover
else:
mutate_count = default_mutate_count
resulting_xover = [ mutate_func(generation, options, [ch])[0] if random.random() < cm_ch else ch
for ch in xover_children
]
rest = parents[xover_last_index:xover_last_index+mutate_count]
mutated_rest = mutate_func(generation, options, rest)
mutated = mutated_elite + mutated_rest
return elite + resulting_xover + mutated
示例7: scroll_down
def scroll_down(driver):
at_bottom = False
while random.random() > .20 and not at_bottom:
k = str(10 + int(200*random.random()))
driver.execute_script("window.scrollBy(0,"+k+")")
at_bottom = driver.execute_script("return (((window.scrollY + window.innerHeight ) +100 > document.body.clientHeight ))")
time.sleep(0.5 + random.random())
示例8: step
def step(self):
"""
Perform a step. This is called repeatedly by the runner
and causes the client to issue commands to the server.
This holds all "intelligence" of the dummy client.
"""
if self.istep == 0 and random.random() > CHANCE_OF_LOGIN:
return
elif random.random() > CHANCE_OF_ACTION:
return
global NLOGGED_IN
if not self._cmdlist:
# no cmdlist in store, get a new one
if self.istep == 0:
NLOGGED_IN += 1
cfunc = self._actions[0]
else: # random selection using cumulative probabilities
rand = random.random()
cfunc = [func for cprob, func in self._actions[2] if cprob >= rand][0]
# assign to internal cmdlist
cmd, self._report = cfunc(self)
self._cmdlist = list(makeiter(cmd))
self._ncmds = len(self._cmdlist)
# output
if self.istep == 0 and not (self._echo_brief or self._echo_all):
# only print login
print "client %i %s (%i/%i)" % (self.cid, self._report, NLOGGED_IN, NCLIENTS)
elif self.istep == 0 or self._echo_brief or self._echo_all:
print "client %i %s (%i/%i)" % (self.cid, self._report, self._ncmds-(len(self._cmdlist)-1), self._ncmds)
# launch the action by popping the first element from cmdlist (don't hide tracebacks)
self.sendLine(str(self._cmdlist.pop(0)))
self.istep += 1 # only steps up if an action is taken
示例9: add_particles
def add_particles():
particle = batch.add(1, GL_POINTS, None,
('v2f/stream', [win.width / 2, 0]))
particle.dx = (random.random() - .5) * win.width / 4
particle.dy = win.height * (.5 + random.random() * .2)
particle.dead = False
particles.append(particle)
示例10: build_xc
def build_xc(c, eid):
line_max = random.randint(1, 50)
line_min = random.randint(0, line_max)
turn_max = random.randint(-360, 360)
turn_min = random.randint(-360, turn_max)
rt_max = random.randint(7000,10000)
rt_min = random.randint(4000,rt_max)
sense = random.randint(100,250)
L0 = random.random()
L1 = random.random()
L2 = random.random()
L3 = random.random()
T0 = 1 - L0
T1 = 1 - L1
T2 = 1 - L2
T3 = 1 - L3
xc_str = {'light':{'dMax':line_max,'dMin':line_min, 'phiMax':turn_max,'phiMin':turn_min, 'rtMax':rt_max, 'rtMin':rt_min, 'lSense':sense,'weights':{'line':{'L':L0,'T':T0},'turn':{'L':L1,'T':T1}}},'dark':{'dMax':line_max,'dMin':line_min, 'phiMax':turn_max,'phiMin':turn_min, 'rtMax':rt_max, 'rtMin':rt_min, 'lSense':sense,'weights':{'line':{'L':L2,'T':T2},'turn':{'L':L3,'T':T3}}}}
if eid > 1:
old_eid = eid - 1
xc_str = splicer.get_mutated_xc(c, old_eid)
add_xc(c, eid, 1, pickle.dumps(xc_str), 1, 1, 100)
示例11: random_divide
def random_divide(self):
ta = int(random.random()**2 * (self.instance.solution_size() - 1))
tb = ta
while tb == ta:
tb = int(random.random() * ( self.instance.solution_size() - 1))
ta, tb = min(ta, tb), max(ta, tb)
return ta, tb
示例12: f
def f(image_config):
array = np.array(image_config.image)
prob = misc.uniform_sample_from_interval(func_config.min_prob, func_config.max_prob)
rnd = np.random.rand(*array.shape[0:2])
array[rnd < prob] = 255 * random.random()
array[rnd > 1 - prob] = 255 * random.random()
image_config.image = Image.fromarray(array)
示例13: bootstrapRealization
def bootstrapRealization(genTable, pathOutput, realization): #Input is table to give Kriging
import random
lines = []
for jj in genTable:
lines.append(jj)
#
#Shuffling
#
newList = []
for jj in numpy.arange(len(lines)):
random.seed()
select = choice(lines)
# To avoid duplicates, if the line already exists, the positions RA and Dec are
# offset by a random value in the range -0.5<D<0.5 arcsec.
if select in numpy.array(newList):
select[0] += random.random()-0.5
select[1] += random.random()-0.5
#
if len(select) == 4:
newList.append([select[0],select[1],select[2],select[3]])
else:
newList.append([select[0],select[1],select[2]])
#
newList = numpy.array(newList)
# Save in dir
if not(os.path.exists(pathOutput+'/MC'+str(realization))):
os.mkdir(pathOutput+'/MC'+str(realization))
# Savetxt file
listTmp = []
for jj in newList:
listTmp.append('\t'.join(map(str, jj))) #Join elements of the same line
fileTMP = open(pathOutput+'/MC'+str(realization)+'/realization_'+str(int(realization))+'_Points.txt', 'wb')
fileTMP.write("\n".join(listTmp))
fileTMP.close()
return True
示例14: run
def run( self ):
self.heightmap = numpy.zeros( ( self.width, self.height ) ) # reset on run
c1 = random.random() # top
c3 = random.random() # bottom
c2 = random.random() # right
c4 = random.random() # left
self.divideRect( 0, 0, self.width, self.height, c1, c2, c3, c4 )
示例15: load_random_chromosome
def load_random_chromosome(chr_name):
"""Generate a chromosome with random information about it.
"""
cur_chromosome = BasicChromosome.Chromosome(chr_name)
num_segments = random.randrange(num_possible_segments)
for seg in range(num_segments):
# make the top and bottom telomeres
if seg == 0:
cur_segment = BasicChromosome.TelomereSegment()
elif seg == num_segments - 1:
cur_segment = BasicChromosome.TelomereSegment(1)
# otherwise, they are just regular segments
else:
cur_segment = BasicChromosome.ChromosomeSegment()
color_chance = random.random()
if color_chance <= color_prob:
fill_color = random.choice(color_choices)
cur_segment.fill_color = fill_color
id_chance = random.random()
if id_chance <= id_prob:
id = get_random_id()
cur_segment.label = id
cur_chromosome.add(cur_segment)
return cur_chromosome, num_segments