如何使用np.random.randint()
生成随机整数,但正态分布为0。
np.random.randint(-10, 10)
返回具有离散均匀分布的整数
np.random.normal(0, 0.1, 1)
返回具有正态分布的浮点数
我想要的是两种功能之间的一种组合。
答案 0 :(得分:23)
获得看起来像正态分布的离散分布的另一种可能方法是从多项分布中绘制,其中概率是从正态分布计算的。
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]中选择一个整数。选择元素(例如0)的概率由p(-0.5
答案 1 :(得分:11)
有可能从Truncated Normal Distribution生成一个类似的分布,该分布被四舍五入为整数。这是scipy truncnorm()的一个例子。
import numpy as np
from scipy.stats import truncnorm
import matplotlib.pyplot as plt
scale = 3.
range = 10
size = 100000
X = truncnorm(a=-range/scale, b=+range/scale, scale=scale).rvs(size=size)
X = X.round().astype(int)
让我们看看它的样子
bins = 2 * range + 1
plt.hist(X, bins)
答案 2 :(得分:1)
这里接受的答案有效,但是我尝试了Will Vousden的解决方案,并且效果很好:
import numpy as np
# Generate Distribution:
randomNums = np.random.normal(scale=3, size=100000)
randomInts = np.round(randomNums)
# Plot:
axis = np.arange(start=min(randomInts), stop = max(randomInts) + 1)
plt.hist(randomInts, bins = axis)
答案 3 :(得分:0)
首先,我们从bell curve获取值。
CODE:
<dependency>
<groupId>com.sample.project</groupId>
<artifactId>Project-B</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>com.sample.project</groupId>
<artifactId>Project-C</artifactId>
<version>1.6.0</version>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
<exclude>META-INF/LICENSE</exclude>
<exclude>LICENSE</exclude>
<exclude>*:*</exclude> // exclude all artifacts
<exclude>com.sample.manual:*</exclude> // exclude specific artifact
</excludes>
<includes>
<include>com.sample.project:*</include> //include only com.sample.project related artifacts
</includes>
</artifactSet>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>jar-with-dependencies</shadedClassifierName>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
</plugin>
输出:
<exclude>com.sample.project:*.xml</exclude>
<include>com.sample.project:{project.artifactId}:*.xml</include>