我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用random.gauss()。
def overlay_generator(hexgrid, depth=params.shells, major=params.major): # GPolygon.RegularPoly(coord,major,poly,rot,"#000000",strokeOpacity,linethick,"#00ffff",fillalpha) s1 = '' numhextiles = float(len(hexgrid)) for idx, hexel in enumerate(hexgrid): speckle = random.gauss(1, 0.5) rank = int((speckle * idx / numhextiles) * 15) invrank = 15 - rank blue = hex(rank)[2:] red = hex(invrank)[2:] tilecolor = red + red + '00' + blue + blue ts = "map.addOverlay(GPolygon.RegularPoly(new GLatLng{coord},\ {major},6,90,\"\#{strokeColor}\",{strokeOpacity},{strokeWeight},\"\#{fillColor}\",{fillalpha}))\ \n".format(coord=hexel, major=major, strokeColor=tilecolor, strokeOpacity=params.opacity, strokeWeight=params.strokeWeight, fillColor=tilecolor, fillalpha=params.opacity) s1 += ts return s1
def overlay_generator(self, hexgrid, depth=params.shells, major=params.major): # GPolygon.RegularPoly(coord,major,poly,rot,"#000000",strokeOpacity,linethick,"#00ffff",fillalpha) s1 = '' numhextiles = float(len(hexgrid)) for idx, hexel in enumerate(hexgrid): speckle = random.gauss(1, 0.5) rank = int((speckle * idx / numhextiles) * 15) invrank = 15 - rank blue = hex(rank)[2:] red = hex(invrank)[2:] tilecolor = red + red + '00' + blue + blue ts = "map.addOverlay(GPolygon.RegularPoly(new GLatLng{coord},\ {major},6,90,\"\#{strokeColor}\",{strokeOpacity},{strokeWeight},\"\#{fillColor}\",{fillalpha}))\ \n".format(coord=hexel, major=major, strokeColor=tilecolor, strokeOpacity=params.opacity, strokeWeight=params.strokeWeight, fillColor=tilecolor, fillalpha=params.opacity) s1 += ts return s1
def get_pretrained_embeddings(filepath): embeddings = dict() with open(filepath, 'r') as f: for line in f: info = line.strip().split() #lines = [line.strip().split() for line in f.readlines()] #embeddings = dict([(line[0], [float(r) for r in line[1:]]) for line in lines]) embeddings[info[0]] = [float(r) for r in info[1:]] f.close() embedding_size = len(embeddings.values()[0]) print 'Embedding size={}'.format(embedding_size) embeddings[START_MARKER] = [random.gauss(0, 0.01) for _ in range(embedding_size)] embeddings[END_MARKER] = [random.gauss(0, 0.01) for _ in range(embedding_size)] if not UNKNOWN_TOKEN in embeddings: embeddings[UNKNOWN_TOKEN] = [random.gauss(0, 0.01) for _ in range(embedding_size)] return embeddings
def _fix(self, n=0): o = random.choice(self.objlist) if issubclass(o, ASN1_INTEGER): return o(int(random.gauss(0,1000))) elif issubclass(o, ASN1_IPADDRESS): z = RandIP()._fix() return o(z) elif issubclass(o, ASN1_STRING): z = int(random.expovariate(0.05)+1) return o("".join([random.choice(self.chars) for i in range(z)])) elif issubclass(o, ASN1_SEQUENCE) and (n < 10): z = int(random.expovariate(0.08)+1) return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z)) return ASN1_INTEGER(int(random.gauss(0,1000))) ############## #### ASN1 #### ##############
def _bootstraped(): def worker(n=1000, mu1=10, sigma1=1, mu2=10.2, sigma2=1): def g(mu, sigma): return random.gauss(mu, sigma) x = [g(mu1, sigma1) for i in range(n)] y = [g(mu2, sigma2) for i in range(n)] return n, mu1, sigma1, mu2, sigma2, \ 'different' if bootstrap(x, y) else 'same' # very different means, same std print worker(mu1=10, sigma1=10, mu2=100, sigma2=10) # similar means and std print worker(mu1=10.1, sigma1=1, mu2=10.2, sigma2=1) # slightly different means, same std print worker(mu1=10.1, sigma1=1, mu2=10.8, sigma2=1) # different in mu eater by large std print worker(mu1=10.1, sigma1=10, mu2=10.8, sigma2=1)
def _ediv(): "Demo code to test the above." import random bell= random.gauss random.seed(1) def go(lst): print ""; print sorted(lst)[:10],"..." for d in ediv(lst,tiny=2): rprint(d); nl() X,Y="X","Y" l=[(1,X),(2,X),(3,X),(4,X),(11,Y),(12,Y),(13,Y),(14,Y)] go(l) l[0] = (1,Y) go(l) go(l*2) go([(1,X),(2,X),(3,X),(4,X),(11,X),(12,X),(13,X),(14,X)]) go([(64,X),(65,Y),(68,X),(69,Y),(70,X),(71,Y), (72,X),(72,Y),(75,X),(75,X), (80,Y),(81,Y),(83,Y),(85,Y)]*2) l=[] for _ in range(1000): l += [(bell(20,1), X),(bell(10,1),Y), (bell(30,1),'Z'),(bell(40,1),'W')] go(l) go([(1,X)])
def _sdiv(): "Demo code to test the above." import random bell= random.gauss random.seed(1) def go(lst,cohen=0.3, num1=lambda x:x[0], num2=lambda x:x[1]): print ""; print sorted(lst)[:10],"..." for d in sdiv(lst,cohen=cohen,num1=num1,num2=num2): print d[1][0][0] l = [ (1,10), (2,11), (3,12), (4,13), (20,20),(21,21), (22,22), (23,23), (24,24), (30,30),(31,31), (32,32), (33,33),(34,34)] go(l,cohen=0.3) go(map(lambda x:(x[1],x[1]),l)) ten = lambda: bell(10,2) twenty = lambda: bell(20,2) thirty = lambda: bell(30,2) l=[] for _ in range(1000): l += [(ten(), ten()), (twenty(),twenty()), (thirty(),thirty())] go(l,cohen=0.5)
def rnd(shape, mean=0.0, stddev=0.01): """Return a list with the given shape with random float elements. The values are generated from a Gaussian distribution. Args: shape (tuple, list): A shape to generate random floats for. 1 or 2 dimensional. mean (float): Mean of the Gaussian distribution. stddev (float): Standard deviation of the distribution. Returns: list: A list with random float elements with the dimensions specified by `shape`. """ if not isinstance(shape, (tuple, list)): raise TypeError('Invalid shape. The shape must be a tuple or a list.') dimension = len(shape) if dimension is 1: # Create a 1 dimensional array with random elements return [random.gauss(mean, stddev) for _ in range(shape[0])] elif dimension is 2: # Create a 2 dimensional matrix with random elements return [[random.gauss(mean, stddev) for _ in range(shape[1])] for _ in range(shape[0])] else: raise NotImplementedError('Random generation with dimensions > 2 is not yet implemented.')
def _makeFakeTrade(self): "Generate a realistic-looking trade" tp = self._t_price tpf = self._t_price_sigma tv = self._t_vol tvf = self._t_vol_sigma t_exec = self._prev_time + self._frequency t_update = t_exec + random.uniform(0, self.FAKE_LATENCY) self._fake_trade_id += 1 self._prev_time = t_update return Trade( exchange_id = self.EXCHANGE_ID, price = tp if tpf is None else random.gauss(tp, tpf), volume = tv if tvf is None else random.gauss(tv, tvf), ts_exec = t_exec, ts_update = t_update, trade_id = self._fake_trade_id )
def current(self, deltat=None): """Return current wind speed and direction as a tuple speed is in m/s, direction in degrees.""" if deltat is None: tnow = time.time() deltat = tnow - self.tlast self.tlast = tnow # update turbulance random walk w_delta = math.sqrt(deltat) * (1.0 - random.gauss(1.0, self.turbulance)) w_delta -= (self.turbulance_mul - 1.0) * (deltat / self.turbulance_time_constant) self.turbulance_mul += w_delta speed = self.speed * math.fabs(self.turbulance_mul) return (speed, self.direction) # Calculate drag.
def _fix(self, n=0): o = random.choice(self.objlist) if issubclass(o, ASN1_INTEGER): return o(int(random.gauss(0,1000))) elif issubclass(o, ASN1_IPADDRESS): z = RandIP()._fix() return o(z) elif issubclass(o, ASN1_STRING): z = int(random.expovariate(0.05)+1) return o(bytes([random.choice(self.chars) for i in range(z)])) elif issubclass(o, ASN1_SEQUENCE) and (n < 10): z = int(random.expovariate(0.08)+1) # return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z)) return o([ x._fix(n+1) for x in [self.__class__(objlist=self.objlist)]*z]) return ASN1_INTEGER(int(random.gauss(0,1000))) ############## #### ASN1 #### ##############
def create_simple_tree(nevents): """Create a simple TTree with a couple of branches.""" t = TTree('aTTree','A TTree') t.Branch('run', AddressOf(pytree, 'run'),'run/I') t.Branch('evt', AddressOf(pytree, 'evt'),'evt/I') t.Branch('x', AddressOf(pytree, 'x'),'x/F') t.Branch('y', AddressOf(pytree, 'y'),'y/F') t.Branch('z', AddressOf(pytree, 'z'),'z/F') for i in range(nevents): pytree.run = 1 if (i<500) else 2 pytree.evt = i pytree.x = gauss(0., 10.) pytree.y = gauss(0, 10.) pytree.z = gauss(5., 50.) t.Fill() return t
def build_normal_distribution(maximum, minimum, mean, deviation, integer=False): """ Build a normal distribution to use for randomizing values for input into transformation functions\n :param maximum: Float or int, The maximum value the value can be]\n :param minimum: Float or int, The minimum value the value can be\n :param mean: Float, the mean (mu) of the normal distribution\n :param deviation: Float, the deviation (sigma) of the normal distribution\n :param integer: OPTIONAL, whether the value is required to be an integer, otherwise False\n :return: Float or int, The value to insert into the transform function """ value = random.gauss(mean, deviation) if integer is True: value = round(value) if value > maximum: value = maximum elif value < minimum: value = minimum return value
def move(self, turn, forward): if forward < 0: raise ValueError('Robot cant move backwards') # turn, and add randomness to the turning command orientation = self.orientation + float(turn) + random.gauss(0.0, self.turn_noise) orientation %= 2 * pi # move, and add randomness to the motion command dist = float(forward) + random.gauss(0.0, self.forward_noise) x = self.x + (cos(orientation) * dist) y = self.y + (sin(orientation) * dist) x %= world_size # cyclic truncate y %= world_size # set particle res = robot() res.set(x, y, orientation) res.set_noise(self.forward_noise, self.turn_noise, self.sense_noise) return res
def sense(self, add_noise=1): Z=[] for i in range(len(landmarks)): deltay=landmarks[i][0]-self.y deltax=landmarks[i][1]-self.x bearing=atan2(deltay, deltax)-self.orientation if add_noise: bearing += random.gauss(0.0, self.bearing_noise) bearing %=2*pi Z.append(bearing) return Z # copy your code from the previous exercise # and modify it so that it simulates bearing noise # according to # self.bearing_noise ############## ONLY ADD/MODIFY CODE ABOVE HERE #################### # -------- # # extract position from a particle set #
def _fix(self, n=0): o = random.choice(self.objlist) if issubclass(o, ASN1_INTEGER): return o(int(random.gauss(0,1000))) elif issubclass(o, ASN1_IPADDRESS): z = RandIP()._fix() return o(z) elif issubclass(o, ASN1_STRING): z = int(random.expovariate(0.05)+1) return o("".join(random.choice(self.chars) for _ in xrange(z))) elif issubclass(o, ASN1_SEQUENCE) and (n < 10): z = int(random.expovariate(0.08)+1) return o([self.__class__(objlist=self.objlist)._fix(n + 1) for _ in xrange(z)]) return ASN1_INTEGER(int(random.gauss(0,1000))) ############## #### ASN1 #### ##############
def acquireDiskResource(ngamsCfgObj, slotId): """ Acquire access right to a disk resource. ngamsCfgObj: NG/AMS Configuration Object (ngamsConfig). slotId: Slot ID referring to the disk resource (string). Returns: Void. """ T = TRACE() storageSet = ngamsCfgObj.getStorageSetFromSlotId(slotId) if (not storageSet.getMutex()): return global _diskMutexSems if (not _diskMutexSems.has_key(slotId)): _diskMutexSems[slotId] = threading.Semaphore(1) code = string.split(str(abs(random.gauss(10000000,10000000))), ".")[0] logger.debug("Requesting access to disk resource with Slot ID: %s (Code: %s)", slotId, str(code)) _diskMutexSems[slotId].acquire() logger.debug("Access granted")
def _bootstraped(): def worker(n=1000, mu1=10, sigma1=1, mu2=10.2, sigma2=1): def g(mu,sigma) : return random.gauss(mu,sigma) x = [g(mu1,sigma1) for i in range(n)] y = [g(mu2,sigma2) for i in range(n)] return n,mu1,sigma1,mu2,sigma2,\ 'different' if bootstrap(x,y) else 'same' # very different means, same std print(worker(mu1=10, sigma1=10, mu2=100, sigma2=10)) # similar means and std print(worker(mu1= 10.1, sigma1=1, mu2= 10.2, sigma2=1)) # slightly different means, same std print(worker(mu1= 10.1, sigma1= 1, mu2= 10.8, sigma2= 1)) # different in mu eater by large std print(worker(mu1= 10.1, sigma1= 10, mu2= 10.8, sigma2= 1))
def gradient(train, labels, coef, bias, learn_rate, nepoch): for epoch in range(nepoch): sum_error = 0.0 for index in range(len(train)): pred = predict(train[index], coef, bias) sum_error += (labels[index] - pred) bias = (bias + learn_rate * sum_error * pred * (1 - pred)) for i in range(len(coef)): coef[i] = (coef[i] + learn_rate * sum_error * pred * (1 - pred) * train[index][i]) return coef, bias #generate standard normal distribution #TODO the function random.gauss() can not generate stable distribution which causes diffusion gradient
def move(self, turn, forward): if forward < 0: raise ValueError, 'Cant move backwards' self.orientation = self.orientation + turn + random.gauss(0.0, self.turn_noise) self.orientation %= 2*pi dist = forward + random.gauss(0.0, self.forward_noise) self.x = self.x + dist*cos(self.orientation) self.y = self.y - dist*sin(self.orientation) self.x %= world_size self.y %= world_size temp = robot() temp.set_noise(0.001, 0.1, 0.1) temp.set(self.x, self.y, self.orientation) temp.set_noise(self.forward_noise, self.turn_noise, self.sense_noise) return temp
def generateRandomData(self, event=None): print "X-Direction:", self.distribution[0] print "Y-Direction:", self.distribution[1] dx = 3 dy = 3 for i in range(int(self.num_pts.get())): if self.distribution[0] == "Uniform": x = random.randint(dx, self.canvas.winfo_width() - dx) else: # According to Adam Carlson, there's 99.8% chance that data in a normal distribution is within 3 standard deviations of the mean. # mu = mean, sigma = standard deviation. Look and infer. x = random.gauss(mu=(self.canvas.winfo_width() - dx) / 2, sigma=self.canvas.winfo_width() / 6) if self.distribution[1] == "Uniform": y = random.randint(dy, self.canvas.winfo_height() - dy) else: y = random.gauss(mu=(self.canvas.winfo_height() - dy) / 2, sigma=self.canvas.winfo_height() / 6) # make sure that the coords are not out of bounds! x %= self.canvas.winfo_width() - dx / 2 y %= self.canvas.winfo_height() - dy / 2 pt = self.canvas.create_oval(x - dx, y - dy, x + dx, y + dy, fill=self.colorOption.get(), outline='') self.objects.append(pt) # handle the clear command
def _generate_gradient(self): # Generate a random unit vector at each grid point -- this is the # "gradient" vector, in that the grid tile slopes towards it # 1 dimension is special, since the only unit vector is trivial; # instead, use a slope between -1 and 1 if self.dimension == 1: return (random.uniform(-1, 1),) # Generate a random point on the surface of the unit n-hypersphere; # this is the same as a random unit vector in n dimensions. Thanks # to: http://mathworld.wolfram.com/SpherePointPicking.html # Pick n normal random variables with stddev 1 random_point = [random.gauss(0, 1) for _ in range(self.dimension)] # Then scale the result to a unit vector scale = sum(n * n for n in random_point) ** -0.5 return tuple(coord * scale for coord in random_point)
def generate_random_gaussian_validator_set( protocol, num_validators=5, mu=60, sigma=40, min_weight=20 ): """Generates a random validator set.""" # Give the validators random weights in 0.,BIGINT; # this "big" integer's job is to guarantee the "tie-breaking property" # that no two subsets of validator's total weights are exactly equal. # In prod, we will add a random epsilon to weights given by bond amounts, # however, for the purposes of the current work, this will suffice. BIGINT = 1000000000000 names = set(range(num_validators)) weights = { i: max(min_weight, r.gauss(mu, sigma)) + 1.0/(BIGINT + r.uniform(0, 1)) + r.random() for i in names } return ValidatorSet(weights, protocol)
def validator_generator(config, protocol): if config['gen_type'] == 'gauss': def gauss_generator(): return generate_random_gaussian_validator_set( protocol, config['num_validators'], config['mu'], config['sigma'], config['min_weight'] ) return gauss_generator if config['gen_type'] == 'weights': jitter_weights = { i: weight + r.random() for i, weight in enumerate(config['weights']) } def weights_generator(): return ValidatorSet(jitter_weights, protocol) return weights_generator
def find_paste_location(self, bbox, already_pasted_bboxes): while True: x_derivation = random.gauss(0, self.variance) * (self.image_size // 2) y_derivation = random.gauss(0, self.variance) * (self.image_size // 2) center = Point(x=self.image_size // 2, y=self.image_size // 2) bbox.left = max(min(center.x + x_derivation, self.image_size), 0) bbox.top = max(min(center.y + y_derivation, self.image_size), 0) if bbox.left + bbox.width > self.image_size: bbox.left = self.image_size - bbox.width if bbox.top + bbox.height > self.image_size: bbox.top = self.image_size - bbox.height if not any(intersects(bbox, box) for box in already_pasted_bboxes): return bbox
def _provisioning_timer(self, timeout): # REVISIT(ivc): consider integrating with Retry interval = 3 max_interval = 15 with timeutils.StopWatch(duration=timeout) as timer: while not timer.expired(): yield timer.leftover() interval = interval * 2 * random.gauss(0.8, 0.05) interval = min(interval, max_interval) interval = min(interval, timer.leftover()) if interval: time.sleep(interval)
def brownian(cls, dt): return random.gauss(0, math.sqrt(dt))
def next(self, message, backoff_exchange_name): total_attempts = 0 for deadlettered in message.headers.get('x-death', ()): if deadlettered['exchange'] == backoff_exchange_name: total_attempts += int(deadlettered['count']) if self.limit and total_attempts >= self.limit: expired = Backoff.Expired( "Backoff aborted after '{}' retries (~{:.0f} seconds)".format( self.limit, self.max_delay / 1000 ) ) six.raise_from(expired, self) expiration = self.get_next_schedule_item(total_attempts) if self.random_sigma: randomised = int(random.gauss(expiration, self.random_sigma)) group_size = self.random_sigma / self.random_groups_per_sigma expiration = round_to_nearest(randomised, interval=group_size) # Prevent any negative values created by randomness expiration = abs(expiration) # store calculation results on self. self._next_expiration = expiration self._total_attempts = total_attempts return expiration
def test(): for j in xrange(1000): vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10 s = 0 for i in range(200): v = gauss(0, random()) ** 7 - s s += v vals.append(v) shuffle(vals) assert msum(vals) == lsum(vals) == dsum(vals) == frsum(vals) == lsum_26(vals) print '.', print 'Tests Passed'
def generateMaze(seed = None): if not seed: seed = random.randint(1,MAX_DIFFERENT_MAZES) random.seed(seed) maze = Maze(16,16) gapfactor = min(0.65,random.gauss(0.5,0.1)) skip = make_with_prison(maze, depth=0, gaps=3, vert=True, min_width=1, gapfactor=gapfactor) maze.to_map() add_pacman_stuff(maze, 2*(maze.r*maze.c/20), 4, skip) return str(maze)
def h(self,xk,uk): #--------------- y = xk[0] y += random.gauss(0.0,self.noisestd) return y #=======================
def output(self): if self._params['mu'] is None: mu = self.DEFAULT_MU else: mu = self._params['mu'] if self._params['sigma'] is None: sigma = self.DEFAULT_SIGMA else: sigma = self._params['sigma'] return random.gauss(mu, sigma)
def mutate_response(self): self.response = random.gauss(0.5 , 0.15)
def _fix(self): return int(round(random.gauss(self.mu, self.sigma)))
def randomize_time(mean): allowed_range = mean * STDEV stdev = allowed_range / 3 # 99.73% chance to be in the allowed range t = 0 while abs(mean - t) > allowed_range: t = gauss(mean, stdev) return t
def test_sharpe_noise(self, small, large): index = pd.date_range('2000-1-30', periods=1000, freq='D') smaller_normal = pd.Series( [random.gauss(.01, small) for i in range(1000)], index=index ) larger_normal = pd.Series( [random.gauss(.01, large) for i in range(1000)], index=index ) assert self.empyrical.sharpe_ratio(smaller_normal, 0.001) > \ self.empyrical.sharpe_ratio(larger_normal, 0.001) # Regressive downside risk tests
def test_downside_risk_std(self, smaller_std, larger_std): less_noise = pd.Series( [random.gauss(0, smaller_std) for i in range(1000)], index=pd.date_range('2000-1-30', periods=1000, freq='D') ) more_noise = pd.Series( [random.gauss(0, larger_std) for i in range(1000)], index=pd.date_range('2000-1-30', periods=1000, freq='D') ) assert self.empyrical.downside_risk(less_noise) < \ self.empyrical.downside_risk(more_noise) # Regressive sortino ratio tests
def _gauss(mean, sigma) -> int: return int(random.gauss(mean, sigma))
def make_control_vectors(num_cv, pos_stddev, angle_stddev, scale_stddev): """ Argument num_cv is the approximate number of control vectors to create Arguments pos_stddev, angle_stddev, and scale_stddev are the standard deviations of the controls effects of position, angle, and scale. Returns pair of control_vectors, control_sdr The control_vectors determines what happens for each output. Each control is a 4-tuple of (X, Y, Angle, Scale) movements. To move, active controls are summed and applied to the current location. control_sdr contains the shape of the control_vectors. """ cv_sz = int(round(num_cv // 6)) control_shape = (6*cv_sz,) pos_controls = [ (random.gauss(0, pos_stddev), random.gauss(0, pos_stddev), 0, 0) for i in range(4*cv_sz)] angle_controls = [ (0, 0, random.gauss(0, angle_stddev), 0) for angle_control in range(cv_sz)] scale_controls = [ (0, 0, 0, random.gauss(0, scale_stddev)) for scale_control in range(cv_sz)] control_vectors = pos_controls + angle_controls + scale_controls random.shuffle(control_vectors) control_vectors = np.array(control_vectors) # Add a little noise to all control vectors control_vectors[:, 0] += np.random.normal(0, pos_stddev/10, control_shape) control_vectors[:, 1] += np.random.normal(0, pos_stddev/10, control_shape) control_vectors[:, 2] += np.random.normal(0, angle_stddev/10, control_shape) control_vectors[:, 3] += np.random.normal(0, scale_stddev/10, control_shape) return control_vectors, SDR(control_shape)
def mutate_standard(self, percent, population): """ Randomly change some parameters. The change in value uses the populations standard deviation. """ def mutate_value(value, pop_values): if random.random() > percent: return value pop_values = [v for v in pop_values if v is not None] if len(np.unique(pop_values)) < 3: # Use alternative method when diversity is very low. return value * 1.5 ** (random.random()*2-1) else: std = np.std(pop_values) return float(random.gauss(value, std)) for param in self.parameters: value = getattr(self, param) pop_values = [getattr(indiv, param) for indiv in population] if value is None: continue # cant mutate. elif isinstance(value, Parameters): value.mutate_standard(percent, pop_values) elif isinstance(value, tuple): new_tup = [] for index, value_indexed in enumerate(value): pop_values_indexed = [v[index] for v in pop_values] new_value = mutate_value(value_indexed, pop_values_indexed) new_tup.append(new_value) setattr(self, param, tuple(new_tup)) else: # Mutate a floating point or boolean number. setattr(self, param, mutate_value(value, pop_values))