我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用random.normalvariate()。
def generate_tokens(mean, std_dev, num_tokens): tokens = {} cnt = 0 while cnt < num_tokens: length = int(round(random.normalvariate(mean, std_dev))) if length < 2: continue flag = True while flag: new_token = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) if tokens.get(new_token) is None: tokens[new_token] = True flag = False cnt += 1 return list(tokens.keys())
def generate_table(mean, std_dev, tokens, num_records, id_col_name, attr_col_name): records = [] cnt = 0 num_tokens = len(tokens) while cnt < num_records: size = int(round(random.normalvariate(mean, std_dev))) new_string = '' for i in range(size): rand = random.randint(0, num_tokens - 1) if i == 0: new_string += tokens[rand] else: new_string += ' ' + tokens[rand] records.append([cnt, new_string]) cnt += 1 return pd.DataFrame(records, columns=[id_col_name, attr_col_name])
def coin(inp, me=None): """coin [amount] -- Flips [amount] of coins.""" if inp: try: amount = int(inp) except (ValueError, TypeError): return "Invalid input!" else: amount = 1 if amount == 1: me("flips a coin and gets {}.".format(random.choice(["heads", "tails"]))) elif amount == 0: me("makes a coin flipping motion with its hands.") else: heads = int(random.normalvariate(.5 * amount, (.75 * amount) ** .5)) tails = amount - heads me("flips {} coins and gets {} heads and {} tails.".format(amount, heads, tails))
def nrolls(count, n): "roll an n-sided die count times" if n == "F": return [random.randint(-1, 1) for x in xrange(min(count, 100))] if n < 2: # it's a coin if count < 100: return [random.randint(0, 1) for x in xrange(count)] else: # fake it return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))] else: if count < 100: return [random.randint(1, n) for x in xrange(count)] else: # fake it return [int(random.normalvariate(.5 * (1 + n) * count, (((n + 1) * (2 * n + 1) / 6. - (.5 * (1 + n)) ** 2) * count) ** .5))]
def _init_retcon_marriage(self, spouse): """Jump back in time to instantiate a marriage that began outside the town.""" config = self.sim.config # Change actual sim year to marriage year, instantiate a Marriage object marriage_date = self.birth_year + ( random.normalvariate( config.person_ex_nihilo_age_at_marriage_mean, config.person_ex_nihilo_age_at_marriage_sd ) ) if ( # Make sure spouses aren't too young for marriage and that marriage isn't slated # to happen after the town has been founded marriage_date - self.birth_year < config.person_ex_nihilo_age_at_marriage_floor or marriage_date - spouse.birth_year < config.person_ex_nihilo_age_at_marriage_floor or marriage_date >= self.sim.true_year ): # If so, don't bother regenerating -- just set marriage year to last year and move on marriage_date = self.sim.true_year - 1 self.sim.year = int(round(marriage_date)) self.marry(spouse)
def _init_memory(self): """Determine a person's base memory capability, given their parents'.""" config = self.person.sim.config if random.random() < config.memory_heritability: takes_after = random.choice([self.person.mother, self.person.father]) memory = random.normalvariate(takes_after.mind.memory, config.memory_heritability_sd) else: takes_after = None memory = random.normalvariate(config.memory_mean, config.memory_sd) if self.person.male: # Men have slightly worse memory (studies show) memory -= config.memory_sex_diff if memory > config.memory_cap: memory = config.memory_cap elif memory < config.memory_floor_at_birth: memory = config.memory_floor_at_birth feature_object = Feature(value=memory, inherited_from=takes_after) return feature_object
def lotty(msg): message = msg[u'content'] sender_qq = msg[u'sender_qq'] db = MyDB() if msg[u'type'] == u'group_message': my_name = msg[u'receiver'] message = message.replace(u'@' + my_name, u'').strip() if message in ReplyStrings.lotty: user = db.get_user_info(sender_qq) if not user: return True, ReplyStrings.unknown_error coin = user[1] if coin < Coin.lotty_price: return True, ReplyStrings.insufficient_coin % (Coin.lotty_price, coin) got = int(random.normalvariate(Coin.lotty_mu, Coin.lotty_sigma)) got = max(got, Coin.lotty_min) got = min(got, Coin.lotty_max) db.mod_coin(sender_qq, got) return True, ReplyStrings.lotty_win % (got, Coin.lotty_max) return False, u""
def test_rosenbrock(): initial_state = [tuple((random.normalvariate(0, 5) for _ in xrange(DIMENSION))) for x in xrange(N_ANNEALERS)] annealer = CoupledAnnealer( rosenbrock, probe, n_annealers=N_ANNEALERS, initial_state=initial_state, steps=STEPS, processes=4, verbose=1, ) annealer.anneal() energy, state = annealer.get_best() assert len(state) == DIMENSION
def random_rectangle(max_side, min_side, sigma=0.5, ratio=1.0, coherce=True): assert min_side <= max_side # half_side = (max_side-min_side)/2 center = max_side-half_side width = random.normalvariate(0, sigma)*half_side height = random.normalvariate(0, sigma)*half_side # if ratio > 1: height = height/ratio else: width = width*ratio # Coherce value to max if coherce: width = coherce_to(max_side, min_side, width+center) height = coherce_to(max_side, min_side, height+center) return width, height
def n_rolls(count, n): """roll an n-sided die count times :type count: int :type n: int | str """ if n == "F": return [random.randint(-1, 1) for x in range(min(count, 100))] if n < 2: # it's a coin if count < 100: return [random.randint(0, 1) for x in range(count)] else: # fake it return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))] else: if count < 100: return [random.randint(1, n) for x in range(count)] else: # fake it return [int(random.normalvariate(.5 * (1 + n) * count, (((n + 1) * (2 * n + 1) / 6. - (.5 * (1 + n)) ** 2) * count) ** .5))]
def coin(text, notice, action): """[amount] - flips [amount] coins :type text: str """ if text: try: amount = int(text) except (ValueError, TypeError): notice("Invalid input '{}': not a number".format(text)) return else: amount = 1 if amount == 1: action("flips a coin and gets {}.".format(random.choice(["heads", "tails"]))) elif amount == 0: action("makes a coin flipping motion") else: heads = int(random.normalvariate(.5 * amount, (.75 * amount) ** .5)) tails = amount - heads action("flips {} coins and gets {} heads and {} tails.".format(amount, heads, tails))
def __init__(self, acc): ''' Mail checker object for one account @param acc: the account to be checked periodically, each account has at most one checker @type acc: EmailAccount ''' # pylint: disable-msg=W0212 import random self._name = acc._name self._account = acc self._timer = eTimer() self._timer_conn = self._timer.timeout.connect(self._checkMail) # I guess, users tend to use identical intervals, so make them a bit different :-) # constant stolen from ReconnectingFactory self._interval = int(self._account._interval)*60*1000 self._interval = int(random.normalvariate(self._interval, self._interval * 0.11962656472)) debug("[CheckMail] %(name)s: __init__: checking all %(interval)s seconds" %{'name':self._name, 'interval':self._interval/1000}) self._timer.start(self._interval) # it is minutes self._unseenList = None self._checkMail()
def pcaCreate(image_files,dir,name_num, dir_list): image_list = [] new_file_name = dir save_dir = dir_list + new_file_name save_dir_tt = save_dir + "\\" for image_file in image_files: image_list.append(misc.imread(image_file)) for image in image_list: img = np.asarray(image, dtype='float32') img = img / 255. img_size = img.size / 3 img1 = img.reshape(img_size, 3) img1 = np.transpose(img1) img_cov = np.cov([img1[0], img1[1], img1[2]]) lamda, p = np.linalg.eig(img_cov) p = np.transpose(p) alpha1 = random.normalvariate(0, 0.3) alpha2 = random.normalvariate(0, 0.3) alpha3 = random.normalvariate(0, 0.3) v = np.transpose((alpha1 * lamda[0], alpha2 * lamda[1], alpha3 * lamda[2])) add_num = np.dot(p, v) img2 = np.array([img[:, :, 0] + add_num[0], img[:, :, 1] + add_num[1], img[:, :, 2] + add_num[2]]) img2 = np.swapaxes(img2, 0, 2) img2 = np.swapaxes(img2, 0, 1) misc.imsave(save_dir_tt + np.str(name_num) + '.jpg', img2) name_num += 1 return image_list
def pcaCreate_Ori(image_files,dir): parser = argparse.ArgumentParser() parser.add_argument("file_suffix", help="specific the file suffix") parser.add_argument("root_dir", help="E:\\") parser.add_argument("-f", "--file", help="record result to file") parser.add_argument("data_set",help= "specific the file suffix") args = parser.parse_args() img_num = len(os.listdir(args.root_dir + '/' + args.dataset)) for i in range(img_num): img_name = os.listdir(args.root_dir + '/' + args.dataset)[i] img = Image.open(os.path.join(args.root_dir, args.dataset, img_name)) img = np.asarray(img, dtype='float32') img = img / 255. img_size = img.size / 3 img1 = img.reshape(img_size, 3) img1 = np.transpose(img1) img_cov = np.cov([img1[0], img1[1], img1[2]]) lamda, p = np.linalg.eig(img_cov) p = np.transpose(p) alpha1 = random.normalvariate(0, 0.3) alpha2 = random.normalvariate(0, 0.3) alpha3 = random.normalvariate(0, 0.3) v = np.transpose((alpha1 * lamda[0], alpha2 * lamda[1], alpha3 * lamda[2])) add_num = np.dot(p, v) img2 = np.array([img[:, :, 0] + add_num[0], img[:, :, 1] + add_num[1], img[:, :, 2] + add_num[2]]) img2 = np.swapaxes(img2, 0, 2) img2 = np.swapaxes(img2, 0, 1) misc.imsave('test2222.jpg', img2)
def retry(self, connector=None): """Have this connector connect again, after a suitable delay. """ if not self.continueTrying: if self.noisy: log.msg("Abandoning %s on explicit request" % (connector,)) return if connector is None: if self.connector is None: raise ValueError("no connector to retry") else: connector = self.connector self.retries += 1 if self.maxRetries is not None and (self.retries > self.maxRetries): if self.noisy: log.msg("Abandoning %s after %d retries." % (connector, self.retries)) return self.delay = min(self.delay * self.factor, self.maxDelay) if self.jitter: self.delay = random.normalvariate(self.delay, self.delay * self.jitter) if self.noisy: log.msg("%s will retry in %d seconds" % (connector, self.delay,)) from twisted.internet import reactor def reconnector(): self._callID = None connector.connect() self._callID = reactor.callLater(self.delay, reconnector)
def perturb(self): self.weight += random.normalvariate(0, MUTATE_POWER)
def sleep(self) -> None: new_delay = min(self.delay * self.factor, self.max_delay) self.delay = random.normalvariate(new_delay, new_delay*self.jitter) await asyncio.sleep(self.delay, loop=self.loop)
def run(self): while not self.stopped(): self.network.push_to_random() time.sleep(max(random.normalvariate(bptc.push_waiting_time_mu, bptc.push_waiting_time_sigma), 0))
def random_resize(image, lower_size, upper_size, sig): factor = random.normalvariate(1, sig) if factor < lower_size: factor = lower_size if factor > upper_size: factor = upper_size image = scipy.misc.imresize(image, factor) return image
def sample(self): return random.normalvariate(self.mean, self.std)
def run(self, shared): if shared["energy"] < shared["energyCap"] - 100: # x = self.pos[0] + self.radius/2 + r.uniform(-1, 1)*self.spawnRadius # y = self.pos[1] + self.radius/2 + r.uniform(-1, 1)*self.spawnRadius x = self.pos[0] + self.radius/2 + r.normalvariate(15, self.spawnRadius)*r.choice([-.5, .5]) y = self.pos[1] + self.radius/2 + r.normalvariate(15, self.spawnRadius)*r.choice([-.5, .5]) objects.add(Food(objects.nextID, 100, color=(0,0,0), x=x, y=y))
def random_resize(image, gt_image, lower_size, upper_size, sig): factor = random.normalvariate(1, sig) if factor < lower_size: factor = lower_size if factor > upper_size: factor = upper_size image = scipy.misc.imresize(image, factor) gt_image = scipy.misc.imresize(gt_image, factor, interp='nearest') return image, gt_image
def __Levyfly(self, step, Pbest, n, dimension): for i in range(n): stepsize = 0.2 * step * (self.__agents[i] - Pbest) self.__agents[i] += stepsize * np.array([normalvariate(0, 1) for k in range(dimension)])
def rand_norm_array(mu, sigma, n): # use normalvariate instead of gauss for thread safety return [random.normalvariate(mu, sigma) for _ in range(n)]
def generate_values(spec, num, inputs=None): try: # fixed value fixed = float(spec) values = [fixed] * num except ValueError: parts = spec.split(':') type = parts[0] params = parts[1:] # uniform distribution: u:min:max if type == "u": min = float(params[0]) max = float(params[1]) values = [random.uniform(min, max) for _ in xrange(0, num)] # normal distribution: n:mean:std_dev elif type == "n": mean = float(params[0]) std_dev = float(params[1]) values = [random.normalvariate(mean, std_dev) for _ in xrange(0, num)] # scaled values: x:factor elif type == "x": factor = float(params[0]) if inputs is not None: values = [inputs[i] * factor for i in xrange(0, num)] else: print("Inputs are not specified") sys.exit(-1) else: print("Unknown distribution") sys.exit(-1) return values
def generate_values(spec, num, inputs=None): try: # fixed value fixed = float(spec) values = [fixed] * num except ValueError: parts = spec.split(':') type = parts[0] params = parts[1:] # uniform distribution: u:min:max if type == "u": min = float(params[0]) max = float(params[1]) values = [random.uniform(min, max) for _ in xrange(0, num)] # normal distribution: n:mean:std_dev elif type == "n": mean = float(params[0]) std_dev = float(params[1]) values = [random.normalvariate(mean, std_dev) for _ in xrange(0, num)] # scaled values: x:factor elif type == "x": factor = float(params[0]) if inputs is not None: values = [inputs[i] * factor for i in xrange(0, num)] else: print "Inputs are not specified" sys.exit(-1) else: print "Unknown distribution" sys.exit(-1) return values
def test(self): x = Bandit(CONFIG) player = 'player' slots = { 'a': [ lambda: random.random() < 0.1, lambda: random.normalvariate(50, 10), ], 'b': [ lambda: random.random() < 0.01, lambda: random.normalvariate(600, 100), ], 'c': [ lambda: random.random() < 0.001, lambda: random.normalvariate(8000, 1000), ], } keys = list(slots.keys()) for k in keys: self.assertTrue(x.register_arm(k)) self.assertFalse(x.register_arm(keys[0])) self.assertFalse(x.reset(player)) for _ in range(10): arm = x.select_arm(player) f0, f1 = slots[arm] self.assertTrue(arm in keys) x.register_reward(player, arm, f1() if f0() else 0.0) info = x.get_arm_info(player) self.assertEqual(3, len(info)) self.assertTrue(isinstance(info[keys[0]], ArmInfo)) model = x.save_bytes() x = Bandit(CONFIG) x.load_bytes(model) self.assertEqual(CONFIG, json.loads(x.get_config())) info = x.get_arm_info(player) self.assertEqual(3, len(info)) self.assertTrue(isinstance(info[keys[0]], ArmInfo))
def random_resize(image, gt_image, lower_size, upper_size, sig): factor = random.normalvariate(1, sig) if factor < lower_size: factor = lower_size if factor > upper_size: factor = upper_size image = scipy.misc.imresize(image, factor) shape = gt_image.shape gt_zero = np.zeros([shape[0], shape[1], 1]) gt_image = np.concatenate((gt_image, gt_zero), axis=2) gt_image = scipy.misc.imresize(gt_image, factor, interp='nearest') gt_image = gt_image[:, :, 0:2]/255 return image, gt_image
def bwalk(min, max, std): """ Generates a bounded random walk. """ rng = max - min while True: max += normalvariate(0, std) yield abs((max % (rng * 2)) - rng) + min
def orders(hist): """ Generates a random set of limit orders (time, side, price, size) from a series of market conditions. """ for t, px, spd in hist: side, d = ('sell', 2) if random() > 0.5 else ('buy', -2) order = round(normalvariate(px + (spd / d), spd / OVERLAP), 2) size = int(abs(normalvariate(0, 100))) yield t, side, order, size ################################################################################ # # Order Book
def next_delay(self): if self.connect_attempts == 0: # if we never tried before, try immediately return 0 elif self.connect_attempts >= self.max_retries: raise RuntimeError('max reconnects reached') else: self.retry_delay = self.retry_delay * self.retry_delay_growth self.retry_delay = random.normalvariate(self.retry_delay, self.retry_delay * self.retry_delay_jitter) if self.retry_delay > self.max_retry_delay: self.retry_delay = self.max_retry_delay return self.retry_delay
def levy_flight(beta,best,est,alpha): sg=sigma(beta) u=np.random.normal(0,sg**2) v=abs(np.random.normal(0,1)) step=u/pow(v,1/beta) step_size=alpha+step#+(step*(est-best)) new=est+step_size#*np.random.normal()#random.normalvariate(0,sg) return new
def time_per_part(): """Return actual processing time for a concrete part.""" return random.normalvariate(PT_MEAN, PT_SIGMA)
def WriteHistogramSeries(writer, tag, mu_sigma_tuples, n=20): """Write a sequence of normally distributed histograms to writer.""" step = 0 wall_time = _start_time for [mean, stddev] in mu_sigma_tuples: data = [random.normalvariate(mean, stddev) for _ in xrange(n)] histo = _MakeHistogram(data) summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=histo)]) event = tf.Event(wall_time=wall_time, step=step, summary=summary) writer.add_event(event) step += 10 wall_time += 100
def sentences(): ret = [] for _ in xrange(max(3, int(random.normalvariate(30, 10)))): ret.append(sentence()) return " ".join(ret)
def retry(self, connector=None): """ Have this connector connect again, after a suitable delay. """ if not self.continueTrying: if self.noisy: log.msg("Abandoning %s on explicit request" % (connector,)) return if connector is None: if self.connector is None: raise ValueError("no connector to retry") else: connector = self.connector self.retries += 1 if self.maxRetries is not None and (self.retries > self.maxRetries): if self.noisy: log.msg("Abandoning %s after %d retries." % (connector, self.retries)) return self.delay = min(self.delay * self.factor, self.maxDelay) if self.jitter: self.delay = random.normalvariate(self.delay, self.delay * self.jitter) if self.noisy: log.msg("%s will retry in %d seconds" % (connector, self.delay,)) def reconnector(): self._callID = None connector.connect() if self.clock is None: from twisted.internet import reactor self.clock = reactor self._callID = self.clock.callLater(self.delay, reconnector)
def spacing_jitter_scale(self): """ """ mu = 0 sigma = 0.4 jitter = random.normalvariate(mu, sigma) return jitter * self.spacing_jitter
def _determine_personality_feature(self, feature_type): """Determine a value for a Big Five personality trait.""" config = self.person.sim.config feature_will_get_inherited = ( self.person.biological_mother and random.random() < config.big_five_heritability_chance[feature_type] ) if feature_will_get_inherited: # Inherit this trait (with slight variance) takes_after = random.choice([self.person.biological_father, self.person.biological_mother]) feature_value = random.normalvariate( self._get_a_persons_feature_of_type(person=takes_after, feature_type=feature_type), config.big_five_inheritance_sd[feature_type] ) else: takes_after = None # Generate from the population mean feature_value = random.normalvariate( config.big_five_mean[feature_type], config.big_five_sd[feature_type] ) if feature_value < config.big_five_floor: feature_value = config.big_five_floor elif feature_value > config.big_five_cap: feature_value = config.big_five_cap feature_object = Feature(value=feature_value, inherited_from=takes_after) return feature_object
def _init_ex_nihilo_memory(self): """Determine this person's base memory capability.""" config = self.person.sim.config memory = random.normalvariate(config.memory_mean, config.memory_sd) if self.person.male: # Men have slightly worse memory (studies show) memory -= config.memory_sex_diff if memory > config.memory_cap: memory = config.memory_cap elif memory < config.memory_floor: memory = config.memory_floor feature_object = Feature(value=memory, inherited_from=None) return feature_object
def run(self): # sleep for a small amount of time, between 0.1 and 0.9 _sleep_for = abs(random.normalvariate(0.5, 0.5)) log.debug("Mock probe {} sleeping for {}...".format(self.name, _sleep_for)) time.sleep(_sleep_for) print("Mock prober {} done".format(self.name))
def probe(solution, tgen): sigma = 100 * tgen probe_solution = [] for x in solution: probe_solution.append(x + random.normalvariate(0, sigma)) return probe_solution