本文整理汇总了Python中random.random函数的典型用法代码示例。如果您正苦于以下问题:Python random函数的具体用法?Python random怎么用?Python random使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了random函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:rajatsen91,项目名称:queueing_bandit,代码行数:33,代码来源:lp_cp.py
示例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)
开发者ID:ferrisvienna,项目名称:ThePythonGameBook,代码行数:30,代码来源:littleAdventure.py
示例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))
开发者ID:andreyto,项目名称:imp-fork-proddl,代码行数:26,代码来源:test_align2d.py
示例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 []
开发者ID:cens,项目名称:audioSens,代码行数:7,代码来源:simulator.py
示例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'})
开发者ID:FashtimeDotCom,项目名称:databench,代码行数:27,代码来源:analysis.py
示例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
开发者ID:fehu,项目名称:min-dat--lin-regression,代码行数:29,代码来源:ga.py
示例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())
开发者ID:AntBean,项目名称:OpenWPM,代码行数:7,代码来源:webdriver_extensions.py
示例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
开发者ID:Archivis,项目名称:evennia,代码行数:33,代码来源:dummyrunner.py
示例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)
开发者ID:bitcraft,项目名称:pyglet,代码行数:7,代码来源:particles.py
示例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)
开发者ID:apgoetz,项目名称:bottsy,代码行数:28,代码来源:gen_xc.py
示例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
开发者ID:kzielonka,项目名称:evo_ca,代码行数:7,代码来源:sga.py
示例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)
开发者ID:WarBean,项目名称:MLUtil,代码行数:7,代码来源:image_augmentation.py
示例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
开发者ID:pastorenick,项目名称:SKiMS-CaT-Metallicity,代码行数:35,代码来源:KrigingMapping_def_v2.py
示例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 )
开发者ID:dplepage,项目名称:worldsynth,代码行数:7,代码来源:midpointDisplacement.py
示例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
开发者ID:BioGeek,项目名称:biopython,代码行数:29,代码来源:test_GraphicsChromosome.py
示例16: __init__
def __init__(self, num_states, num_symbols):
""" generated source for method __init___0 """
self.num_states = num_states
self.num_symbols = num_symbols
self.transition = numpy.zeros(shape=(int(num_states), int(num_states)))
self.output = numpy.zeros(shape=(int(num_states), int(num_symbols)))
self.pi = numpy.zeros(shape=(int(num_states),))
self.pi[0] = 1
i = 1
while i < num_states:
self.pi[i] = 0
i += 1
i = 0
while i < self.num_states:
j=0
while j < self.num_states:
if j < i or j > i + self.delta:
self.transition[i][j] = 0
else:
self.transition[i][j] = random.random()
j += 1
j=0
while j < self.num_symbols:
self.output[i][j] = random.random()
j += 1
i += 1
开发者ID:akarthik10,项目名称:opencv-hand-gesture,代码行数:27,代码来源:HiddenMarkov.py
示例17: randomList
def randomList(self, jobsList, tot):
""" Handy method to create a random job number set with a random behaviour.
There are 4 predefined behaviour:
* producing a list of all the jobs from 1 to tot
* producing the input jobsList
* producing a subset of jobsList
* producing a subset of all the jobs
if the set produced is empty it returns the jobsList itself
"""
r = random.random()
if r < 0.25: # All the jobs
ret = range(1, tot+1)
elif r < 0.75: # Exactly the requested jobs
ret = jobsList
elif r < 0.90: # A subset of the requested jobs
ret = [x for x in jobsList if random.random() > .25]
else: # A subset of all the jobs
ret = [x for x in range(1, tot+1) if random.random() > .25]
ret = set(ret)
jobsList = set(jobsList)
if ret & jobsList: #
return ret
else:
return jobsList
开发者ID:bbockelm,项目名称:CRAB,代码行数:25,代码来源:Tester.py
示例18: generate_doc
def generate_doc(db, prefix, suffix_length=12, id_string="%s%s", max_retry=100, data={}):
"""Generate doc with unique ID, based on provided prefix and random suffix. Retries on duplicate.
**Deprecated since couchdbcurl.client.Document.create() method.**
"""
assert not "_id" in data
assert not "_rev" in data
assert max_retry > 0
assert type(max_retry) == int
# doc = data.copy()
rand = hashlib.sha1(str(random.random())).hexdigest()[:suffix_length]
doc_id = id_string % (prefix, "")
while True:
try:
db[doc_id] = data
break
except ResourceConflict:
pass
max_retry -= 1
if max_retry < 0:
raise Exception("Retry-limit reached during document generation")
rand = hashlib.sha1(str(random.random())).hexdigest()[:suffix_length]
doc_id = id_string % (prefix, "_%s" % rand)
开发者ID:angry-elf,项目名称:django-couch-utils,代码行数:29,代码来源:__init__.py
示例19: GaussianSampling
def GaussianSampling():
u1 = rnd.random()
u2 = rnd.random()
r = np.sqrt(-2.0 * np.log(u1))
theta = 2.0 * np.pi * u2
nx = r * np.cos(theta)
return nx
开发者ID:yujungchen,项目名称:python_template,代码行数:7,代码来源:gaussian.py
示例20: sample
def sample(a, diversity=0.75):
if random.random() > diversity:
return np.argmax(a)
while 1:
i = random.randint(0, len(a)-1)
if a[i] > random.random():
return i
开发者ID:caiomsouza,项目名称:keras_monet,代码行数:7,代码来源:lstm_text_generation.py
注:本文中的random.random函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论