本文整理汇总了Python中random.rand函数的典型用法代码示例。如果您正苦于以下问题:Python rand函数的具体用法?Python rand怎么用?Python rand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_ratings
def generate_ratings(num_types, num_users, ratings_per_user=20, num_items=100,
alpha=None, noise=-1, plsi=False):
p = Poisson(ratings_per_user)
ratings = [[rint(1,5) for i in range(num_items)] for i in range(num_types)]
if alpha == None:
alpha = [1]*num_types
user_ratings = []
user_indices = []
type_dists = []
for i in range(num_users):
ratings_per_user = p.sample()
if plsi:
type_dist = normalize([rand() for t in range(num_types)])
else:
type_dist = dirichlet(alpha)
type_dists.append(type_dist)
rating = []
indices = []
for j in rsample(range(num_items), ratings_per_user):
if rand() < noise:
rating.append(rint(1,5))
else:
type = sample(type_dist)
rating.append(ratings[type][j])
indices.append(j)
user_ratings.append(rating)
user_indices.append(indices)
user_ratings = user_indices, user_ratings
return user_ratings, ratings, type_dists
示例2: enter_roll_mode
def enter_roll_mode():
global scr
global mode
global form
mode='roll'
f.change_mode('window')
f.wipe()
f.frame('Roll your character')
f.selector.wipe()
f.text(20,50,'Choose your race:',fg='green',size=12)
race_choice=f.selector(['human','orc','dwarf','elf','half-troll'],race_choice_agent)
race_choice.activate(20,75)
race_choice.focus(0)
map=w.load_map()
c=[rand(0,31),rand(0,31)]
form['coord']=c
#f.inform('Your coordinates are: '+str(c))
while (map[c[0]][c[1]]<40)|(map[c[0]][c[1]]>90): c=[rand(0,31),rand(0,31)]
f.text(220,50,'Starting location:',fg='blue',size=12)
f.text(240,80,'('+str(c[0])+','+str(c[1])+')',size=12)
f.text(50,f.HEIGHT-50,"Press 's' to start...",fg='yellow',size=12)
if map[c[0]][c[1]]<60:
f.symbol(230//f.charsize,70//f.charsize+1,'+',color='green')
else:
f.symbol(230//f.charsize,70//f.charsize+1,'v',color='brown')
示例3: auto_corr
def auto_corr(l):
m = 10000
c1 = 0.
c2 = 0.
cn = 0.
delta = .3
samples = np.zeros(m)
samples[0] = rand()
for ix in np.arange(m)-1:
delta_x = delta*(2.*rand()-1)
next_x = (samples[ix] + delta_x) % 1.
if check_configuration(samples[ix], next_x, rand()):
samples[ix+1] = next_x
else:
samples[ix+1] = samples[ix]
for ix in np.arange(m-l):
c1 += (samples[ix]*samples[ix+l])
c1 *= (1./(m-l))
for ix in np.arange(m):
cn += samples[ix]
c2 += samples[ix]**2
cn = ((1./m)*cn)**2
c2 *= (1./m)
return (c1-cn)/(c2-cn)
示例4: mc
def mc(number_of_samples, n1, n0):
configs = np.zeros(number_of_samples)
delta = .3
configs[0] = rand()
total_points = 0.
sum = 0.
sum_squared = 0.
for ix in np.arange(len(configs))-1:
delta_x = delta*(2.*rand()-1)
next_x = (configs[ix] + delta_x) % 1.
if check_configuration(configs[ix], next_x, rand()):
configs[ix+1] = next_x
else:
configs[ix+1] = configs[ix]
if ix >= n1:
if not (ix-n1) % n0:
sum += fx(configs[ix])/dist_fn(configs[ix])
sum_squared += (fx(configs[ix])/dist_fn(configs[ix]))**2.
total_points += 1.
return sum, sum_squared, total_points
示例5: update
def update(self):
if self.dest != self.real_dest: # we're going in a random direction.
self.pause += 1
if self.pause >= self.delay:
self.pause = 0
self.dest = self.real_dest[:]
# Randomly decide if we want to go toward our dest, or in a random dir.
if rand(1, 100) == 1 and not self.at_dest and self.pause == 0:
# random direction!
self.dest = [rand(0, self.size[0]), rand(0, 380)]
elif self.pause == 0:
self.dest = self.real_dest[:]
vec = [self.dest[0] - self.rect.centerx, self.dest[1] - self.rect.centery]
mag = sqrt(vec[0]**2 + vec[1]**2)
if mag <= 10 and self.pause == 0: # here
self.real_dest = self.rect.center
self.at_dest = 1
return
elif mag <= 10 and self.pause != 0: # at rand dest
return
vec[0] /= mag
vec[1] /= mag
self.rect = self.rect.move(self.speed * vec[0], self.speed * vec[1])
示例6: update
def update(self):
#print "In tempSensor[" + str(self.id) + "].update()" #debug
#if statement so other sensors can be easily added
#only including the 22 here because that is all I have to test
print "Reading Tempature Sensor: " + str(self.id)
if self.sensorType == "DHT22":
#read in the sensor
for ii in range(self.retries):
humidity, temperature = self.sensorLibrary.read(22, self.pin) ## 22 is what Adafruit_DHT.DHT22 returns in example .\Adafruit_Python_DHT\examples\AdafruitDHT.py
if humidity is not None and temperature is not None:
self.lastTemp = temperature
self.lastHumd = humidity
self.iteratationsToVal = ii
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)
break # have the data, now leave
else:
self.iteratationsToVal = -9999
print 'Failed to get reading'
elif self.sensorType == "test": #test case
from random import randint as rand
self.lastTemp = rand(0,25)
self.lastHumd = rand(0,100)
self.iteratationsToVal = -1
print "leaving Test"
else:
print("Error reading in temp sensor type. This should cause an exception")
示例7: __init__
def __init__(self, dst=NullAddress, src=NullAddress):
"""
Base class for all packets.
If src is None, it is filled in with the sending Entity.
If dst is None, nothing special happens, but when it gets
to the next hop, the receiver probably won't know what to do with it!
You can subclass this to add your own packet fields, but they should all
be either simple primitive types, or plain ol' containers (lists,
tuples, dicts) containing primitive types or more plain ol' containers
(containing primitive types or more plain 'ol containers containing...).
"""
self.src = src
self.dst = dst
# Decremented for each entity we go through.
self.ttl = self.DEFAULT_TTL
# List of entities we've been sent through. For debugging.
self.trace = []
# When using NetVis, packets are visible, and you can set the color.
# color is a list of red, green, blue, and (optionally) alpha values.
# Each value is between 0 and 1. alpha of 0 is transparent. 1 is
# opaque.
self.outer_color = hsv_to_rgb(rand(), rand() * .8 + .2,
rand() * .5 + .5, .75)
self.inner_color = [0, 0, 0, 0] # transparent
示例8: mazeDFS
def mazeDFS(width,height):
stack = []
grid = [[x%2*y%2 for x in range(width)] for y in range(height)]
total = ((width-1)/2)*((height-1)/2)
cy = rand(1,height,2)
cx = rand(1,width,2)
visited = 1
while visited<total:
possible= [[y,x] for y,x in
[[cy-2,cx],[cy,cx+2],[cy+2,cx],[cy,cx-2]]
if y>0 and x>0 and y<height-1 and x<width-1]
neighbor= [[y,x] for y,x in possible if grid[y-1][x]!=2 and grid[y+1][x]!=2 and grid[y][x-1]!=2 and grid[y][x+1]!=2]
if len(neighbor)>0:
ny,nx = neighbor[rand(0,len(neighbor))]
wy = ny if nx!=cx else (ny-1 if ny>cy else cy-1)
wx = nx if ny!=cy else (nx-1 if nx>cx else cx-1)
grid[wy][wx] = 2
stack.append([cy,cx])
cy = ny
cx = nx
visited+=1
else:
cy,cx = stack.pop()
grid[0][1] = 1
grid[height-1][width-2] = 1
return grid
示例9: new
def new(my, good, extent, f=None):
if my == good:
return my
elif f:
return good if rand() < extent * f else my
else:
return good if rand() < extent else my
示例10: update
def update(self):
users = self.users
fr = rand(1,5)
to = rand(1,5)
return (fr, to,
users.update(users.c.projid==fr).execute(
projid=to).rowcount)
示例11: draw_map
def draw_map(self):
for y in range(self.height):
for x in range(self.width):
self.sys.own.worldPosition = [x*S,y*S,0]
if self.map[x][y].block:
index = self.map[x][y].block_index
try:
mesh = self.map[x][y].block+str(index)
tile = logic.getCurrentScene().addObject(mesh,self.sys.own)
self.map[x][y].block = tile
except ValueError:
raise Exception("**********\nStairs at {} {} are reested! \nCorrect block for index {} not found!\n**********".format(x,y,index))
logic.endGame()
#draw props
if self.map[x][y].prop:
p = self.map[x][y].prop
self.sys.own.worldPosition = [(x*S)+rand(-1,1),(y*S)+rand(-1,1), 2]
if p == 'LifePotion':
self.sys.own.worldPosition.z = 0
prop = logic.getCurrentScene().addObject(p, self.sys.own)
ori = prop.worldOrientation.to_euler()
ori.z = rand(0,628)*0.01
prop.worldOrientation = ori
if p == 'Zombie':
self.monsters.append(prop)
elif p == 'LifePotion':
self.items.append(prop)
示例12: randTurn
def randTurn(field):
first = True
x,y = 0, 0
while field[x][y] != "-" or first:
first = False
x, y = rand(0,18), rand(0,18)
return x, y
示例13: step
def step(self, mutation_rate=1, crossover_rate = 1,
number_of_individuals=0):
highest_fitness_this_generation = 0
fittest_individual_this_generation = None
if number_of_individuals <= 0:
number_of_individuals = len(self.population)
while len(self.population.next_generation) < number_of_individuals:
if self.sort_population_each_step:
self.population.sort()
if 0 < crossover_rate > rand():
parent, other_parent = self.population.select_for_crossover()
offspring = parent + other_parent # crossover
else:
offspring = self.population.select_for_mutation()
if 0 < mutation_rate > rand():
offspring = offspring.mutate()
self.population.add_to_next_generation(offspring)
if offspring.fitness > highest_fitness_this_generation:
fittest_individual_this_generation = offspring
highest_fitness_this_generation = offspring.fitness
if highest_fitness_this_generation > self.highest_fitness_found:
self.highest_fitness_found = fittest_individual_this_generation.fitness
self.fittest_individual_found = fittest_individual_this_generation
self.population.switch_to_next_generation()
return fittest_individual_this_generation
示例14: writer
def writer(out_file):
"""
param:
out_file:
the output filename for the csv
"""
teams = []
for number in range(1,2):
for number in range(1,50):
teams.append([str(number)])
for number in range(1,50):
teams.append([str(number)])
#print teams
for item in teams:
#print item, '\n'
item.append(rand(1,100))
for number in range(1,11):
item.append(rand(1,10))
item.append(random.choice('yn'))
#print teams
data = csv.writer(out_file, delimiter=',')
for item in teams:
data.writerow(item)
示例15: hande
def hande(heaven, earth, passing_grade=1):
pool = [rand(1, 10) for i in range(heaven)]
num_rerolls_used = 0
if earth < 0:
earth = -earth
while num_rerolls_used < earth:
for i, v in enumerate(pool):
if v < 7:
pool[i] = rand(1, 10)
num_rerolls_used += 1
break
if not sum(v < 7 for v in pool):
break
hits = sum(x >= 7 for x in pool) + pool.count(10)
if hits == passing_grade:
ret = "Pass (%s)" % (', '.join(str(x) for x in pool))
if hits > passing_grade:
ret = "Pass +%d (%s)" % \
(hits - passing_grade, ', '.join(str(x) for x in pool))
if hits < passing_grade:
ret = "Fail -%d (%s)" % \
(passing_grade - hits, ', '.join(str(x) for x in pool))
if num_rerolls_used < abs(earth):
val = abs(earth) - num_rerolls_used
ret += " (%d reroll" % val
if val != 1:
ret += "s"
ret += " left)"
return ret