最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何生成整数的随机正态分布

SEO心得admin62浏览0评论
本文介绍了如何生成整数的随机正态分布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

与np.random.randint()一样如何生成随机整数,但正态分布在0附近.

How to generate a random integer as with np.random.randint(), but with a normal distribution around 0.

np.random.randint(-10, 10)返回具有离散均匀分布的整数 np.random.normal(0, 0.1, 1)返回具有正态分布的浮点数

np.random.randint(-10, 10) returns integers with a discrete uniform distribution np.random.normal(0, 0.1, 1) returns floats with a normal distribution

我想要的是两种功能之间的一种组合.

What I want is a kind of combination between the two functions.

推荐答案

获得正态分布看起来像的离散分布的另一种可能方法是从概率为从正态分布计算得出.

One other possible way to get a discrete distribution that looks like the normal distribution is to draw from a multinomial distribution where the probabilities are calculated from a normal distribution.

import scipy.stats as ss import numpy as np import matplotlib.pyplot as plt x = np.arange(-10, 11) xU, xL = x + 0.5, x - 0.5 prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3) prob = prob / prob.sum() #normalize the probabilities so their sum is 1 nums = np.random.choice(x, size = 10000, p = prob) plt.hist(nums, bins = len(x))

在这里,np.random.choice从[-10,10]中选择一个整数.通过p(-0.5 <x <0.5)来计算选择元素(例如0)的概率,其中x是均值为零且标准差为3的正态随机变量.开发.之所以设为3,是因为p(-10

Here, np.random.choice picks an integer from [-10, 10]. The probability for selecting an element, say 0, is calculated by p(-0.5 < x < 0.5) where x is a normal random variable with mean zero and standard deviation 3. I chooce std. dev. as 3 because this way p(-10 < x < 10) is almost 1.

结果如下:

发布评论

评论列表(0)

  1. 暂无评论