python类normalvariate()的实例源码

data_generator.py 文件源码 项目:py_stringsimjoin 作者: anhaidgroup 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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())
data_generator.py 文件源码 项目:py_stringsimjoin 作者: anhaidgroup 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
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])
coin.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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))
dice.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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))]
person.py 文件源码 项目:talktown 作者: james-owen-ryan 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
mind.py 文件源码 项目:talktown 作者: james-owen-ryan 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
plugin.py 文件源码 项目:simple-qq-bot 作者: ihciah 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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""
test_rosenbrock.py 文件源码 项目:csa 作者: structurely 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
test_stats.py 文件源码 项目:rectpack 作者: secnot 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
person.py 文件源码 项目:dissertation 作者: james-owen-ryan 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
mind.py 文件源码 项目:dissertation 作者: james-owen-ryan 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
gaming.py 文件源码 项目:luftwaffel 作者: exp-publishing 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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))]
gaming.py 文件源码 项目:luftwaffel 作者: exp-publishing 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
plugin.py 文件源码 项目:enigma2-plugins 作者: opendreambox 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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()
jitering.py 文件源码 项目:FCN_train 作者: 315386775 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
jitering.py 文件源码 项目:FCN_train 作者: 315386775 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
protocol.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
connection.py 文件源码 项目:neat_py 作者: NathanZabriskie 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def perturb(self):
        self.weight += random.normalvariate(0, MUTATE_POWER)
utils.py 文件源码 项目:aiomongo 作者: ZeoAlliance 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
network.py 文件源码 项目:bptc_wallet 作者: ceddie 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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))
kitti_low_input.py 文件源码 项目:KittiClass 作者: MarvinTeichmann 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 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
kitti_input.py 文件源码 项目:KittiClass 作者: MarvinTeichmann 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 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
crv_types.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def sample(self):
        return random.normalvariate(self.mean, self.std)
SimGame.py 文件源码 项目:CritterEvolution 作者: apockill 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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))
voc_seg_input.py 文件源码 项目:VOCSeg 作者: lxh-123 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
protocol.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
cso.py 文件源码 项目:SwarmPackagePy 作者: SISDevelop 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)])
support.py 文件源码 项目:joinmarket-clientserver 作者: JoinMarket-Org 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def rand_norm_array(mu, sigma, n):
    # use normalvariate instead of gauss for thread safety
    return [random.normalvariate(mu, sigma) for _ in range(n)]
bot_gen.py 文件源码 项目:pysimgrid 作者: alexmnazarenko 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
bot_gen.py 文件源码 项目:pysimgrid 作者: alexmnazarenko 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号