本文整理汇总了Python中random.triangular函数的典型用法代码示例。如果您正苦于以下问题:Python triangular函数的具体用法?Python triangular怎么用?Python triangular使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了triangular函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: updateweights
def updateweights(n1, n2):
#Initialising a random number and if that number exceeds the crossingover rate then proceeding ahead for crossing over
#else returning the 2 NeuralNets as it is
a= random.random()
if a < crossingoverrate:
#Creating a list of weights of both the NeuralNets for easy processing ahead
weightslist1 = np.array(n1.nettolist())
weightslist2 = np.array(n2.nettolist())
#Main Crossing over step- We take an element-wise average of the weights of
#both the NeuralNets . This incorporates the weights of both the NeuralNets
#in equal proportion. We make 2 such lists , this is the crossing over step
#since we are taking characters from both the NeuralNets that too equally.
child1 = [i * 0.5 for i in np.add(weightslist1, weightslist2)]
child2 = [i * 0.5 for i in np.add(weightslist1, weightslist2)]
#Initialising a random number and if that number exceeds the mutation rate then proceeding ahead for mutation
#else the child remains as it is
b= random.random()
c= random.random()
if b < mutationrate:
print "Hi"
#Randomly picking any one index of the list to be mutated
index = random.randint(0, len(child1) - 1)
#perturbing the value slightly by adding a small component proportional to the original value of the weight
#for that index (it is being multiplied by a random number generated from a triangular distribution)
#This step is similar to mutation in genetics, where the genome gets randomly perturbed by external mutagens.
child1[index] += random.triangular(-1, 1) * child1[index]
if c < mutationrate:
print "Hello"
index = random.randint(0, len(child2) - 1)
child2[index] += random.triangular(-1, 1) * child2[index]
#After the crossing over and mutation (if any), the list of weights is converted back to weights for the NeuralNets.
n1.listtonet(child1)
n2.listtonet(child2)
return (n1, n2)
示例2: specimen_generator
def specimen_generator():
global random_specimen
global mated_specimen
while True:
r = get_results()
result_count = len(r)
if result_count < 10 or mated_specimen > 10*random_specimen:
dna = map(lambda x: x+97, range(26))
dna = map(chr, dna)
shuffle(dna)
dna = "".join(dna)
#print "random: %s" % dna
with random_specimen_lock:
random_specimen += 1
yield {"dna" : dna, "parents" : [], "id" : next_id(), "guesses" : None, "wrong" : None, "winrate" : None}
else:
dna_i = int(triangular(0, len(r), 0))
dnb_i = int(triangular(0, len(r), 0))
dna = r[dna_i]
dnb = r[dnb_i]
dnc = merge_dna(dna["dna"], dnb["dna"])
print "mated %s & %s -> %s\n" % (dna["dna"], dnb["dna"], dnc)
with mated_specimen_lock:
mated_specimen += 1
yield {"dna" : dnc, "parents" : ["%s (%s)" % (dna_link(dna["dna"]), dna["winrate"]),
"%s (%s)" % (dna_link(dnb["dna"]), dnb["winrate"])],
"id" : next_id(), "guesses" : None, "wrong" : None, "winrate" : None}
示例3: tickle_bids
def tickle_bids(low, high, amountlow=.02, amounthigh=.09, concurrent=4, pause=33.5):
try:
while True:
time.sleep(pause)
clear_all_bids()
amount_midpoint = amounthigh - ((amounthigh - amountlow) / 2)
bid_amounts = []
for i in range(concurrent):
bid_btc_amount = float("{0:.4f}".format(random.triangular(amountlow,
amounthigh,
amount_midpoint)))
bid_amounts.append(bid_btc_amount)
bid_price_midpoint = float(high) - ((float(high) - float(low)) / 2)
print 'Bid price midpoint: %f' % bid_price_midpoint
for bid_btc_amount in bid_amounts:
bid = float("{0:.2f}".format(random.triangular(low, high, bid_price_midpoint)))
print 'Bid: %f [%f]' % (bid, bid_btc_amount)
total_btc_int = int(bid_btc_amount * BTC_INT_FACTOR)
buy_price_int = int(bid * USD_INT_FACTOR)
res = API.add_order('bid', total_btc_int, buy_price_int)
print res
except KeyboardInterrupt:
print '\nStopping...'
clear_all_bids()
示例4: write_songs
def write_songs(artist, song_list, parsed_url):
length = len(song_list)
count = 0
selected_indices = []
while count < length:
# Find a random index from the song_list and ensure it is new.
rand_idx = random.randint(0, length - 1)
while rand_idx in selected_indices:
rand_idx = random.randint(0, length - 1)
song = song_list[rand_idx]
song_path = os.path.join(DATA_PATH, artist)
song_file_name = filey.scrub_file_name(song.name + SONG_EXT)
if filey.already_exists(song_path, song_file_name):
print "%s already exists. Continuing." % (song_file_name)
else:
# Be like human.
sleep(random.triangular(4.8, 7.23, 12.4))
rand_int = random.randint(0, 10)
if rand_int == 9:
sleep(random.triangular(2.6, 10, 7))
song_data = get_song_lyrics(parsed_url, song.url)
filey.write_to_file(song_path, song_file_name, song_data)
selected_indices.append(rand_idx)
count += 1
示例5: step
def step(self, prev_xy):
if self.map.player_xy in self.map.objs:
for obj in self.map.objs[self.map.player_xy]:
if isinstance(obj, StairUp) and prev_xy != self.map.player_xy:
self.map = self.map.prev
elif isinstance(obj, StairDown) and prev_xy != self.map.player_xy:
if not self.map.next:
t = copy.copy(self.map.type)
t.stairup = True
t.stairdown = True
t.size = random.choice((t.tiny, t.small, t.medium))
t.treasure_level = int(random.triangular(0.0, 9.9, math.sqrt(self.map.level)))
t.monster_level = int(random.triangular(0.0, 9.9, math.sqrt(self.map.level)))
self.map.next = Map(t)
self.map.next.prev = self.map
self.map = self.map.next
return
obj.on_player(self.player)
self.map.objs[self.map.player_xy][:] = [x for x in self.map.objs[self.map.player_xy] if x.delete == False]
self.map.objs_lock = True
for pos, objs in self.map.objs.items():
for obj in objs:
obj.step(pos, self.map, self.player)
self.map.objs = {k: [x for x in self.map.objs[k] if x.delete == False] for k in self.map.objs.keys()}
self.map.objs_lock = False
self.player.lust += 1
示例6: create_expression
def create_expression():
"""This function takes no arguments and returns an expression that
generates a number between -1.0 and 1.0, given x and y coordinates."""
# expr = lambda x, y: (random.random() - 2 * 81) - 1
# expr_dict= {'A': lambda x, y: sin(sin(sin(cos(x * y)))),
# 'B': lambda x, y: sin(pi) * 2,
# 'C': lambda x, y: sin(3 * pi(sin(21))),
# 'D': lambda x, y: (cos(sin((pi * 8)))),
# 'E': lambda x, y: cos(cos(sin(7)))
# }
# expr_dict = {'sure': lambda x, y: sin(sin(sin(cos(pi)))),
# 'the': lambda x, y: random.triangular(0.2, 0.9),
# 'dang': lambda x, y: sin(pi(sin(pi(sin(cos(-1)))))),
# 'should': lambda x, y: cos(x * cos(sin(pi))),
# 'make': lambda x, y: random.uniform(1278, 900000),
# 'art': lambda x, y: random.gauss(x, y)}
expr_list = [lambda x, y: (random.random() * 21) - 1 / 3,
lambda x, y: (random.triangular(0, 1) * 2) - 1,
lambda x, y: (random.uniform(x, y) * 2) - 1,
lambda x, y: ((x**3) - sin(3)),
lambda x, y: (random.triangular(0.2, 0.8) / 2) - 1,
lambda x, y: sin(pi * 2) - 3 / 4,
lambda x, y: sqrt(sin(pi / 2) * cos(x)),
lambda x, y: sin(cos(sin(cos(sin(cos(sin(cos(pi)))))))),
lambda x, y: 7 + sin(pi) / sqrt(2**4),
lambda x, y: sqrt(3) * sin(sin(sin(pi) - 1)),
lambda x, y: (random.random() * 8) + sqrt(66) / 2,
lambda x, y: sin(sin(sin(sin(sin(sin(sin(sin(sin(7 * x - y))))))))),
lambda x, y: random.uniform(sin(1), pi) **8 / 2]
return random.choice(expr_list)
示例7: create_noble
def create_noble(self, mode = "manual"):
if mode == "manual":
intel = self.Controller.get_input("What is the Nobles intelligence? (0 - 10)", "int")
ambition = self.Controller.get_input("What is the Nobles ambition? (0 - 10)", "int")
network = self.Controller.get_input("How strong is the Nobles network? (0 - 10)", "int")
wealth = self.Controller.get_input("How wealthy is the Noble? (0 - 10)", "int")
while True:
gender = str(input("Male or Female? (m/f)"))
gender = gender.lower()
if gender == "m" or gender == "f":
break
print("Sorry, I don't have enough programming skill to deal with non-binary genders")
elif mode == "random":
intel = int(round(random.triangular(0, 10)))
ambition = int(round(random.triangular(0, 10)))
network = int(round(random.triangular(0, 10)))
wealth = int(round(random.triangular(0, 10)))
gender = random.choice(["m", "f"])
nobility = (network + wealth) / 2
names = self.create_noble_name(gender, nobility)
egg = self.egg_checker(names[0])
if egg:
names = egg
stats = egg[3]
intel = stats[0]
ambition = stats[1]
network = stats[2]
wealth = stats[3]
gender = stats[4]
full_name = names[0]
full_title = names[1]
extended_title = title = names[2]
stats = {
"full_name": full_name,
"full_title": full_title,
"extended_title": extended_title,
"intel": intel,
"ambition": ambition,
"network": network,
"wealth": wealth,
"gender": gender,
"employed": False #Adding an "employed" stat here
}
self.nobles[full_name] = stats
self.save_file()
print("")
print("New noble added!\nName: %s\nIntelligence: %d\nAmbition: %d\nNetwork: %d\nWealth: %s" % (
extended_title,
intel,
ambition,
network,
wealth
))
print("")
示例8: randomize
def randomize(self, random_state=1):
"""Randomize."""
self.random_state = random_state
random.seed(self.random_state)
self.nearest_neighbors_threshold = \
int(random.triangular(0,
2 * self.nearest_neighbors_threshold,
self.nearest_neighbors_threshold))
self.true_class_bias = \
random.triangular(0,
2 * self.true_class_bias,
self.true_class_bias)
self.multi_class_bias = \
random.triangular(0,
2 * self.multi_class_bias,
self.multi_class_bias)
self.multi_class_threshold = \
random.triangular(0,
2 * self.multi_class_threshold,
self.multi_class_threshold)
self.true_class_threshold = \
random.triangular(0,
2 * self.true_class_threshold,
self.true_class_threshold)
logger.debug(self.__str__())
示例9: advance_epoch
def advance_epoch(self):
"""Pass the time."""
# Sort ascending because this is cost rather than fitness.
self.population.sort(key=fitness, reverse=True)
new_population = []
# Clone our best people.
iters = int(Pool.population_size * 0.4)
for counter in range(iters):
new_individual = self.population[counter].copy()
new_population.append(new_individual)
# Breed our best people, producing four offspring for each couple.
iters = int(Pool.population_size * 0.6)
for counter in range(0, iters, 2):
# Perform rank roulette selection.
father = self.population[int(triangular(0, iters, 0))]
mother = self.population[int(triangular(0, iters, 0))]
children = self.crossover(father, mother)
children[0].mutate()
new_population += children
self.population = new_population
for person in self.population:
person.update_fitness()
self.epoch += 1
示例10: simulation_per_month_model
def simulation_per_month_model(input_model):
"""
Model to solve the problem
"""
# Static model data
cold_start_initial_users = 400
cost_per_request = 0.01
request_per_user = 4
# Model
# Select randomly input parameters
events = random.triangular(input_model[1][0], input_model[1][1], input_model[1][2])
# Calculate the cost
cost = 0
# For each event in the month
for event in range(0, round(events)):
event_duration = random.triangular(input_model[2][0], input_model[2][1], input_model[2][2])
# For each day of the event
for day in range(0, round(event_duration)):
# Get users to track
users_to_track = random.triangular(input_model[0][0], input_model[0][1], input_model[0][2])
cost += event_duration * users_to_track * request_per_user * cost_per_request
cost += cold_start_initial_users * request_per_user * cost_per_request
return cost
示例11: random_position
def random_position(a, b):
"""Draw from a bimodal distribution with support in (a,b).
This is just two triangular distributions glued together. Empirically
it's a nice way to build the word clouds, but it should be replaced at
some point with something more sophisticated. See the note below.
Here's the idea behind the crazy bimodal distribution:
* If we drop the words too close to the axes they'll just stack up
and we get something that looks like a plus
* If we drop a word at the corner of the region it'll stack right
above the previous word dropped from that direction, then get
shoved left. The result looks like a square.
* Dropping halfway between the axis and the corner will result in
something halfway in-between (usually a hexagon)
I think that what this method is `approximating' is the following:
* Divide the area into quadrants
* Keep track of the area covered in each quadrant
* Drop the new word in a random position on the edge of the
quadrant with the least coverage
"""
if random.choice([ 0, 1 ]):
return random.triangular(a, 0.5*(a+b))
else:
return random.triangular(0.5*(a+b), b)
示例12: impulse
def impulse(self):
for body in self.group.dynamicBodies():
if body.acc.z == 0:
body.vel.x = round(random.triangular(-.5,.5), self.group.precision)
body.vel.y = round(random.triangular(-.5,.5), self.group.precision)
body.vel.z = round(random.triangular(0,1.5), self.group.precision)
self.group.wakeBody(body)
示例13: create_sub_strands
def create_sub_strands(splines, points=None):
new_splines = []
if not points:
resolution_points = [curve_tools.get_nurbs_points(spline)
for spline in splines]
else:
resolution_points = points
for _ in range(0, len(resolution_points), 2):
# Pick a random spline to start from
spline1 = random.choice(resolution_points)
# Pick a random spline to end which is not the start spline
for _ in range(9999):
spline2 = random.choice(resolution_points)
if not spline2 == spline1:
break
# Pick a random start point from spline1
start_index = int(random.triangular(0, len(spline1)))
start_point = spline1[start_index]
# Pick a ranomd end point from spline2
end_index = int(random.triangular(0, len(spline2)))
end_point = spline2[end_index]
# Create the mid point
mid_point = start_point + (end_point - start_point) * 0.5
new_spline = (start_point, mid_point, end_point)
# Drape the spline
new_spline = drape_spline(new_spline)
new_splines.append(new_spline)
splines.append(new_spline)
return new_splines
示例14: partially_matched
def partially_matched(parent1, parent2):
"""Return a new chromosome created via partially matched crossover (PMX).
This is suitable for permutation encoded GAs. Partially matched crossover
respects the absolute position of alleles.
"""
third = len(parent1) // 3
l1 = int(random.triangular(1, third, third * 2))
l2 = int(random.triangular(third, third * 2, len(parent1) - 1))
if l2 < l1:
l1, l2 = l2, l1
matching = parent2[l1:l2]
displaced = parent1[l1:l2]
child = parent1[0:l1] + matching + parent1[l2:]
tofind = [item for item in displaced if item not in matching]
tomatch = [item for item in matching if item not in displaced]
for k, v in enumerate(tofind):
subj = tomatch[k]
locus = parent1.index(subj)
child[locus] = v
return child
示例15: genetic
def genetic(n, popsize=None, rate=0.5):
if popsize is None:
popsize = 2 * n
if rate is None:
rate = random.random()
m = int(rate * popsize)
population = []
for i in range(popsize):
population.append(Chromosome(n))
population.sort()
generations = 0
while not is_solution(population[0]):
del population[-m:]
for i in range(math.floor(m / 2) if len(population) > 1 else 0):
j = int(random.triangular(0, len(population) - 1, 0))
k = int(random.triangular(j + 1, len(population), j + 1))
# triangular distribution is biased toward low end
chrom1, chrom2 = crossover(population[j], population[k])
bisect.insort(population, chrom1)
bisect.insort(population, chrom2)
for i in range(math.ceil(m / 2) if len(population) > 1 else m):
j = int(random.triangular(0, len(population), 0))
bisect.insort(population, mutate(population[j]))
generations += 1
return True, population[0]