【问题标题】:Python error in generating and sorting 4 cases of random variablesPython 生成和排序随机变量的 4 例错误
【发布时间】:2012-11-11 00:34:56
【问题描述】:

我正在尝试在 Python 中模拟连续随机生成的数字分布,并找到组合数字(其中 y=x1+x2)在 p(0.9

n = 10000
x11 = [random.random() for i in range(n)]
x12 = [random.random() for i in range(n)]
x21 = [-0.5*(log(1-random.random())) for i in range(n)]
x22 = [-0.5*(log(1-random.random())) for i in range(n)]
x31 = [random.random() for i in range(n)]
x32 = [random.uniform(0,2) for i in range(n)]
x41 = [0.25 if random.random() < 0.8 else 1.5 for r in range(n)]
x42 = [0.25 if random.random() < 0.8 else 1.5 for r in range(n)]

x11 到 x42 是我试图获得它们介于 0.9 和 1.8 之间的概率的情况,其中生成的列表对被组合然后对其进行操作。所以将 x11 和 x12 组合起来,然后找到期望值、方差和 0.9 到 1.8 p(x)。

def test():
  x1,x2,c = 0.0,0.0,0.0
  for i in range(10000):
    if random.random()< 0.8:
      x1 += 0.25
    else:
      x2 += 1.5
    y = x1 + x2
    if y>0.9 and y<=1.8:
      c = c + 1
  return x1,x2,c

print "test: ",test()

def sim(a,b):
  #pyab1 = sum([a for a in a if a>0.9 and a<=1.8])/10000
  #pyab2 = sum([b for b in b if b>0.9 and b<=1.8])/10000
  #print "*****",float(pyab1+pyab2)
  #print a+b
  #array1 = [[a],[b]]
  array1 = a+b
  #array1.extend(a)
  #array1.extend(b)
  #c = 0
  #for y in array1:
    #if y>0.9 and y<=1.8:
      #c = c + 1
  pyab = sum([y for y in array1 if y>0.9 and y<=1.8])/10000
  print("P(a < x <= b) : {0:8.4f}".format(pyab))

我只计算概率 P(0.9

y~u(0,1) = 0.575

y~exp(2) = 0.3371

x1~u(0,1) x2~u(0,2)

P(y=0.25)=0.8 P(y=1.5)=0.2 = 0.2

这是输出,后面是它应该给出的值,但这显示了结果有多远。

case 1: P(a < x <= b) : 0.7169 #should be 0.575 
case 2: P(a < x <= b) : 0.4282 #should be 0.3371 
case 3: P(a < x <= b) : 0.5966 #should be 0.4413 
case 4: P(a < x <= b) : 0.5595 #should be 0.2 

我对 Python 很陌生,所以如果我的问题似乎有我错过的明显解决方案,请耐心等待。

【问题讨论】:

  • 我完全不明白你需要什么。 sim()是怎么调用的,能不能放一段sn-p的代码,显示它是怎么调用的,期望的输出,然后是实际的输出。
  • 刚刚添加。它切断了我进入目的的代码上方的顶部。我会在这里重申它,使其可见。
  • 我正在尝试在 Python 中模拟连续随机生成的数字分布,并找到组合数字(其中 y=x1+x2)在 p(0.9

标签: python random


【解决方案1】:

很可能你最好更换

pyab = sum([y for y in array1 if y>0.9 and y<=1.8])/10000

与

pyab = len([y for y in array1 if y>0.9 and y<=1.8])/len(array1)

因为您需要概率,而不是实际值的总和。另外,len(array1) 很可能不是 10000,而是两个数组的总长度。

【讨论】:

  • 抱歉,除了 x21,x22 对(在编辑之前也是正确的)之外,它仍然给出了所有不正确的值。它在我的代码之前切断了我帖子的顶部,我说它是 2 个独立生成的数字,它们相加(y = x1 + x2),因此对于 for 循环的每次通过,'y' 被比较为介于 0.9 和 1.8 之间.
  • array1 = a+b 不对数组求和,您应该改用array1 = [sum(i) for i in zip(a,b)]
  • 不抱歉,仍然给出了错误的值。我担心代码的逻辑可能有问题。
  • 你能展示你得到的结果和你想要得到的结果吗?否则我无法遵循您的代码...
  • 这些是理论值的近似值,但显示结果与实际相差多远。 case 1: P(a
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多