如何模拟有偏差的硬币翻转?

发布于 2024-07-13 06:07:31 字数 287 浏览 8 评论 0原文

在无偏硬币翻转中,H 或 T 出现的次数为 50%。

但我想模拟硬币,它给出 H 的概率为“p”,T 的概率为“(1-p)”。

像这样的东西:

def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]

In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.

something like this:

def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

围归者 2024-07-20 06:07:31

random.random() 返回 [0, 1) 范围内的均匀分布伪随机浮点数。 该数字小于 [0,1) 范围内给定数字 p 的概率为 p。 因此:

def flip(p):
    return 'H' if random.random() < p else 'T'

一些实验:

>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999  # Approximately 20% of the coins are heads

>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999  # Better approximation 

random.random() returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given number p in the range [0,1) with probability p. Thus:

def flip(p):
    return 'H' if random.random() < p else 'T'

Some experiments:

>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999  # Approximately 20% of the coins are heads

>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999  # Better approximation 
友欢 2024-07-20 06:07:31

您希望“偏差”基于对称分布吗? 或者也许是指数分布? 高斯有人吗?

好吧,这是从随机文档本身中提取的所有方法。

首先,一个三角分布的例子:

print random.triangular(0, 1, 0.7)

random.triangle(低、高、模式)

返回一个随机浮点数N,使得low <= N
与这些之间的指定模式
界限。 界限
默认为模式
参数默认为中点
在边界之间,给出对称的
分布。

random.betavariate(alpha, beta)

测试版分布。 参数的条件是 alpha > 。 0 和
测试版> 0 。 返回值范围在 01 之间。

random.expovariate(lambd)

指数分布。 lambd1.0
除以所需的平均值。 它应该
非零。 (参数将是
称为“lambda”,但这是一个
Python 中的保留字。)返回
值范围从 0正数
如果 lambd 为正,则无穷大

如果lambd,则从负无穷0
为负数。

random.gammavariate(alpha, beta)

伽马分布。 (不是伽玛
功能!)的条件
参数为 alpha > 0beta > 0.

random.gauss(mu, sigma):

高斯分布。 mu 为平均值,sigma 为标准
偏差。 这个稍微快一点
normalvariate() 函数
定义如下。

random.lognormvariate(mu, sigma)

对数正态分布。 如果你采取
这个的自然对数
分布,你会得到一个正常的
均值 mu 和标准分布
偏差sigmamu 可以有任何
值,并且sigma必须大于

random.normalvariate(mu, sigma)

正态分布。 mu 是平均值,
sigma 是标准差。

random.vonmisesvariate(mu, kappa)

mu 是平均角度,表示为
02*pi 之间的弧度,以及 kappa
是浓度参数,其中
必须大于或等于
如果kappa等于,则
分布减少到均匀
02*pi 范围内的随机角度。

random.paretovariate(alpha)

帕累托分布。 alpha
形状参数。

random.weibullvariate(alpha, beta)

威布尔分布。 alpha
比例参数和 beta 是形状
参数。

Do you want the "bias" to be based in symmetric distribuition? Or maybe exponential distribution? Gaussian anyone?

Well, here are all the methods, extracted from random documentation itself.

First, an example of triangular distribution:

print random.triangular(0, 1, 0.7)

random.triangular(low, high, mode):

Return a random floating point number N such that low <= N < high and
with the specified mode between those
bounds. The low and high bounds
default to zero and one. The mode
argument defaults to the midpoint
between the bounds, giving a symmetric
distribution.

random.betavariate(alpha, beta):

Beta distribution. Conditions on the parameters are alpha > 0 and
beta > 0. Returned values range between 0 and 1.

random.expovariate(lambd):

Exponential distribution. lambd is 1.0
divided by the desired mean. It should
be nonzero. (The parameter would be
called “lambda”, but that is a
reserved word in Python.) Returned
values range from 0 to positive
infinity
if lambd is positive, and
from negative infinity to 0 if lambd
is negative.

random.gammavariate(alpha, beta):

Gamma distribution. (Not the gamma
function!) Conditions on the
parameters are alpha > 0 and beta > 0.

random.gauss(mu, sigma):

Gaussian distribution. mu is the mean, and sigma is the standard
deviation. This is slightly faster
than the normalvariate() function
defined below.

random.lognormvariate(mu, sigma):

Log normal distribution. If you take
the natural logarithm of this
distribution, you’ll get a normal
distribution with mean mu and standard
deviation sigma. mu can have any
value, and sigma must be greater than
zero.

random.normalvariate(mu, sigma):

Normal distribution. mu is the mean,
and sigma is the standard deviation.

random.vonmisesvariate(mu, kappa):

mu is the mean angle, expressed in
radians between 0 and 2*pi, and kappa
is the concentration parameter, which
must be greater than or equal to zero.
If kappa is equal to zero, this
distribution reduces to a uniform
random angle over the range 0 to 2*pi.

random.paretovariate(alpha):

Pareto distribution. alpha is the
shape parameter.

random.weibullvariate(alpha, beta)

Weibull distribution. alpha is the
scale parameter and beta is the shape
parameter.

池予 2024-07-20 06:07:31

怎么样:

import numpy as np
n, p = 1, .33  # n = coins flipped, p = prob of success
s = np.random.binomial(n, p, 100)

How about:

import numpy as np
n, p = 1, .33  # n = coins flipped, p = prob of success
s = np.random.binomial(n, p, 100)
爱*していゐ 2024-07-20 06:07:31
import random
def flip(p):
    return (random.random() < p)

这将返回一个布尔值,然后您可以使用它来选择所需的 H 或 T(或在任意两个值之间进行选择)。 您还可以在方法中包含选择:

def flip(p):
    if random.random() < p:
        return 'H'
    else:
        return 'T'

但这种方式通常不太有用。

import random
def flip(p):
    return (random.random() < p)

That returns a boolean which you can then use to choose H or T (or choose between any two values) you want. You could also include the choice in the method:

def flip(p):
    if random.random() < p:
        return 'H'
    else:
        return 'T'

but it'd be less generally useful that way.

挽清梦 2024-07-20 06:07:31

也可以使用 sympyX ~ Bernoulli(p) 分布 nsamples 次进行采样:

from sympy.stats import Bernoulli, sample_iter
list(sample_iter(Bernoulli('X', 0.8), numsamples=10)) # p = 0.8 and nsamples=10
# [1, 1, 0, 1, 1, 0, 1, 1, 1, 1]

返回 'H''T' 代替使用

def flip(p, n):
    return list(map(lambda x: 'H' if x==1 else 'T', sample_iter(Bernoulli('X', p), numsamples=n)))

print(flip(0.8, 10)) # p = 0.8 and nsamples=10
# ['H', 'H', 'T', 'H', 'H', 'T', 'H', 'H', 'H', 'H']

One can sample from the X ~ Bernoulli(p) distribution nsamples times using sympy too:

from sympy.stats import Bernoulli, sample_iter
list(sample_iter(Bernoulli('X', 0.8), numsamples=10)) # p = 0.8 and nsamples=10
# [1, 1, 0, 1, 1, 0, 1, 1, 1, 1]

Return 'H' or 'T' instead using

def flip(p, n):
    return list(map(lambda x: 'H' if x==1 else 'T', sample_iter(Bernoulli('X', p), numsamples=n)))

print(flip(0.8, 10)) # p = 0.8 and nsamples=10
# ['H', 'H', 'T', 'H', 'H', 'T', 'H', 'H', 'H', 'H']
落花浅忆 2024-07-20 06:07:31
  • 导入 0 - 1 之间的随机数(可以使用 randrange 函数)

  • 如果数字大于 (1-p) ,返回尾数。

  • 否则,返回头部

  • Import a random number between 0 - 1 (you can use randrange function)

  • If the number is above (1-p), return tails.

  • Else, return heads

千里故人稀 2024-07-20 06:07:31
import random
def flip():
    return ["H" if random.randint(0,3) <= 2 else "T" for i in range(10)]

此时正面的概率是 75%,反面的概率是 25%(0,1,2 都是正面,只有 3 是反面)。 通过使用 random.randint() ,您可能会出现任何偏差,同时仍保持随机性。

import random
def flip():
    return ["H" if random.randint(0,3) <= 2 else "T" for i in range(10)]

Right now probability of Head is 75% and tails is 25% (0,1,2 are all Heads and only 3 is Tails) . By using random.randint() you could have any probability of bias while still maintaining randomness.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文