本文整理汇总了Python中random.triangular方法的典型用法代码示例。如果您正苦于以下问题:Python random.triangular方法的具体用法?Python random.triangular怎么用?Python random.triangular使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类random
的用法示例。
在下文中一共展示了random.triangular方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_data
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def create_data(config={}):
"""Create data and write to a JSON file."""
max_weight = config.setdefault("max_weight", 15)
items = []
if "num_items" in config:
num_items = config["num_items"]
del config["num_items"]
else:
num_items = 32
# Generate items
digits = int(math.ceil(math.log(num_items, 16)))
fmt = "%0" + str(digits) + "X"
for i in range(0, num_items):
name = fmt % (i + 1)
weight = random.triangular(1.0, max_weight // 3, max_weight)
value = random.random() * 100
items.append({"name": name, "weight": weight, "value": value})
config["items"] = items
configuration.write_file(config)
示例2: single_point
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def single_point(parent1, parent2, locus=None):
"""Return a new chromosome created with single-point crossover.
This is suitable for use with list or value encoding, and will work with
chromosomes of heterogenous lengths.
Args:
parent1 (List): A parent chromosome.
parent2 (List): A parent chromosome.
locus (int): The locus at which to crossover or ``None`` for a randomly
selected locus.
Returns:
List[List]: Two new chromosomes descended from the given parents.
"""
if len(parent1) > len(parent2):
parent1, parent2 = parent2, parent1
if locus is None:
locus = int(random.triangular(1, len(parent1) / 2, len(parent1) - 2))
child1 = parent1[0:locus] + parent2[locus:]
child2 = parent2[0:locus] + parent1[locus:]
return [child1, child2]
示例3: cut_and_splice
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def cut_and_splice(parent1, parent2, loci=None):
"""Return a new chromosome created with cut and splice crossover.
This is suitable for use with list or value encoding, and will work with
chromosomes of heterogeneous lengths.
Args:
parent1 (List): A parent chromosome.
parent2 (List): A parent chromosome.
loci (Tuple[int, int]): A crossover locus for each parent.
Returns:
List[List]: Two new chromosomes descended from the given parents.
"""
if loci is None:
loci = []
loci[0] = int(random.triangular(1, len(parent1) / 2, len(parent1) - 2))
loci[1] = int(random.triangular(1, len(parent2) / 2, len(parent2) - 2))
child1 = parent1[0:loci[0]] + parent2[loci[0]:]
child2 = parent2[0:loci[1]] + parent1[loci[1]:]
return [child1, child2]
示例4: random_code_byte_sequence
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def random_code_byte_sequence(self, length=None):
# todo: add gauss histogramm random.randgauss(min,max,avg) - triangle is not really correct here
length = length or int(random.triangular(self.MIN_CONTRACT_SIZE, 2 * self.AVERAGE_CONTRACT_SIZE + self.MIN_CONTRACT_SIZE)) # use gauss
rnd_prolog = WeightedRandomizer(self.LIKELYHOOD_PROLOG_BY_OPCODE_INT)
rnd_epilog = WeightedRandomizer(self.LIKELYHOOD_EPILOG_BY_OPCODE_INT) # not completely true as this incorps. pro/epilog
rnd_corpus = WeightedRandomizer(self.LIKELYHOOD_BY_OPCODE_INT)
b = []
for _ in range(128):
b.append(rnd_prolog.random())
for _ in range(length - 128 * 2):
b.append(rnd_corpus.random())
for _ in range(128):
b.append(rnd_epilog.random())
return bytes(b)
示例5: generate
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def generate(self, point):
"""
generates new points
in an annulus between
self.r, 2*self.r
"""
rad = random.triangular(self.r, 2*self.r, .3*(2*self.r - self.r))
# was random.uniform(self.r, 2*self.r) but I think
# this may be closer to the correct distribution
# but easier to build
angs = [random.uniform(0, 2*pi)]
if self.dim > 2:
angs.extend(random.uniform(-pi/2, pi/2) for _ in range(self.dim-2))
angs[0] = 2*angs[0]
return self.convert(point, rad, angs)
示例6: _get_waiting_in_secs
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def _get_waiting_in_secs(waiting_in_secs,
num_retries,
max_waiting_in_secs):
"""Retrieve the waiting time in seconds.
This method uses exponential back-off in figuring out the number of
seconds to wait; however, the max wait time shouldn't be more than
what is specified via max_waiting_in_seconds.
Args:
waiting_in_secs: waiting time in seconds.
num_retries: number of retries, starting from 0.
max_waiting_in_secs: maximum waiting time in seconds.
Returns:
The number of seconds to wait.
"""
# make the backoff going up even faster
waiting_in_secs *= 2**num_retries
jitter = waiting_in_secs * 0.2
waiting_in_secs += random.triangular(-jitter, jitter)
return min(waiting_in_secs, max_waiting_in_secs)
示例7: generate_random_cigar_string
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def generate_random_cigar_string(self, readlength):
"""Generate random cigar string for a read of a given length. Simulate small mismatches and indels but nothing larger than 10bp."""
softclip_left = round(triangular(0, readlength, min(1000, readlength * 0.5)))
non_clipped = readlength - softclip_left
softclip_right = round(triangular(0, non_clipped, min(1000, non_clipped * 0.5)))
non_clipped = readlength - softclip_left - softclip_right
sequence = ""
read_bases_consumed = 0
while read_bases_consumed < non_clipped:
#choose next operation
if len(sequence) == 0 or sequence[-1] == "I" or sequence[-1] == "D":
next_operation = "M"
next_length = round(triangular(1, non_clipped - read_bases_consumed, min(30, non_clipped - read_bases_consumed)))
read_bases_consumed += next_length
else:
next_operation = choice("ID")
if next_operation == "I":
next_length = round(triangular(1, min(10, non_clipped - read_bases_consumed), 1))
read_bases_consumed += next_length
else:
next_length = round(triangular(1, 10, 1))
sequence += str(next_length) + next_operation
return "{0}S{1}{2}S".format(softclip_left, sequence, softclip_right)
示例8: generate_random_cigar_string_hardclipped
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def generate_random_cigar_string_hardclipped(self, readlength):
"""Generate random cigar string for a read of a given length.
Simulate small mismatches and indels but nothing larger than 10bp. Simulate hard-clipping and return tuple (left-clipped, right-clipped, cigar)"""
hardclip_left = round(triangular(0, readlength, min(1000, readlength * 0.5)))
non_clipped = readlength - hardclip_left
hardclip_right = round(triangular(0, non_clipped, min(1000, non_clipped * 0.5)))
non_clipped = readlength - hardclip_left - hardclip_right
sequence = ""
read_bases_consumed = 0
while read_bases_consumed < non_clipped:
#choose next operation
if len(sequence) == 0 or sequence[-1] == "I" or sequence[-1] == "D":
next_operation = "M"
next_length = round(triangular(1, non_clipped - read_bases_consumed, min(30, non_clipped - read_bases_consumed)))
read_bases_consumed += next_length
else:
next_operation = choice("ID")
if next_operation == "I":
next_length = round(triangular(1, min(10, non_clipped - read_bases_consumed), 1))
read_bases_consumed += next_length
else:
next_length = round(triangular(1, 10, 1))
sequence += str(next_length) + next_operation
return (hardclip_left, hardclip_right, "{0}H{1}{2}H".format(hardclip_left, sequence, hardclip_right))
示例9: diceroll
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def diceroll(string, form_uniform=False, mode_loc = 0.9):
negative = False
if string[0] == "-":
negative = True
string = string[1:]
nums = [int(x) for x in string.split("d")]
total_sum = 0
for i in range(0, nums[0]):
if form_uniform:
total_sum += int(random.randint(1, nums[1]))
else:
if nums[1] <= 1:
total_sum += 1
else:
total_sum += int(random.triangular(1.0, nums[1], mode_loc*nums[1]))
if negative:
total_sum *= -1
return total_sum
示例10: get_dist
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def get_dist(d):
return {
'randrange': random.randrange, # start, stop, step
'randint': random.randint, # a, b
'random': random.random,
'uniform': random, # a, b
'triangular': random.triangular, # low, high, mode
'beta': random.betavariate, # alpha, beta
'expo': random.expovariate, # lambda
'gamma': random.gammavariate, # alpha, beta
'gauss': random.gauss, # mu, sigma
'lognorm': random.lognormvariate, # mu, sigma
'normal': random.normalvariate, # mu, sigma
'vonmises': random.vonmisesvariate, # mu, kappa
'pareto': random.paretovariate, # alpha
'weibull': random.weibullvariate # alpha, beta
}.get(d)
示例11: do_nu_sync
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def do_nu_sync(scheduler):
print("do_nu_sync!", scheduler)
try:
fetch_and_flush()
finally:
sleeptime = int(random.triangular(1*60, (10*60), (5*60)))
next_exec = datetime.datetime.now() + datetime.timedelta(seconds=sleeptime)
schedule_next_exec(scheduler, next_exec)
print("NU Sync executed. Next exec at ", next_exec)
示例12: single_point_bin
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def single_point_bin(parent1, parent2, length=None, locus=None):
"""Return a new chromosome through a single-point crossover.
This is suitable for use with binary encoding.
Args:
parent1 (List): A parent chromosome.
parent2 (List): A parent chromosome.
locus (int): The crossover point or ``None`` to choose one at random.
If ``None``, then ``length`` must be the number of bits used in the
parent chromosomes.
length(int): The number of bits used. Not used if a locus is provided.
Returns:
List[int]: Two new chromosomes descended from the given parents.
Raises:
ValueError: if neither ``locus`` or ``length`` is specified.
"""
if locus is None and length is None:
raise ValueError("Either the length or a locus is required.")
if locus is None:
locus = int(random.triangular(1, length / 2, length - 2))
if length is None:
length = 2 * locus
maskr = 2 ** locus - 1
maskl = (2 ** length - 1) & ~maskr
child1 = parent1 & maskl | parent2 & maskr
child2 = parent2 & maskl | parent1 & maskr
return [child1, child2]
示例13: generate
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def generate(self, point):
"""generates new points
in an annulus between
self.r, 2*self.r
Parameters
----------
point :
Returns
-------
"""
rad = random.triangular(self.r, 2 * self.r, 0.3 * (2 * self.r - self.r))
# was random.uniform(self.r, 2*self.r) but I think
# this may be closer to the correct distribution
# but easier to build
angs = [random.uniform(0, 2 * pi)]
if self.dim > 2:
angs.extend(random.uniform(-pi / 2, pi / 2) for _ in range(self.dim - 2))
angs[0] = 2 * angs[0]
return self.convert(point, rad, angs)
示例14: random_code_byte_sequence
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def random_code_byte_sequence(self, length=None):
# todo: add gauss histogramm random.randgauss(min,max,avg) - triangle is not really correct here
length = length or int(random.triangular(self.MIN_CONTRACT_SIZE, 2 * self.AVERAGE_CONTRACT_SIZE + self.MIN_CONTRACT_SIZE)) # use gauss
b = [random.choice(constantinople_skewed_set) for _ in range(length)]
return bytes(b)
示例15: __init__
# 需要导入模块: import random [as 别名]
# 或者: from random import triangular [as 别名]
def __init__(self, host_provider, expire_time=600, retry_time=60,
invalidation_threshold=0.2):
"""Initialize the host selection.
Args:
host_provider: A ``HostProvider``, used to get the current list
of live hosts.
expire_time: An integer, expire time in seconds.
retry_time: An integer, retry time in seconds.
invalidation_threshold: A float, when the number of entries
being invalidated divided by the number of all valid hosts
is above this threshold, we stop accepting invalidation
requests. We do this to stay on the conservative side to
avoid invalidating hosts too fast to starve requests.
"""
assert host_provider.initialized
# Current host.
self._current = None
# Last host, works even when current host invalided.
self._last = None
# Time when we selected the current host.
self._select_time = None
# Adjust expire time by +/- 10%, but 0 is special for testing purpose.
self._expire_time = expire_time
if expire_time:
self._expire_time = expire_time + int(
random.triangular(-expire_time * 0.1, expire_time * 0.1))
self._retry_time = retry_time
self._invalidation_threshold = invalidation_threshold
# Host name -> time when marked bad.
self._bad_hosts = {}
self._host_provider = host_provider