总和为 1 的概率权重的有效随机数组 [英] Efficient random array of probability weights that sum 1

查看:49
本文介绍了总和为 1 的概率权重的有效随机数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些非常简单的东西,在我看来,我的解决方案步骤太多(考虑到 R 是为统计而做的):

I need something very simple and it seems to me that my solution has too many steps (considering that R is done for statistics):

我只需要一个总和为 1 的 N 个概率权重数组(在 0 和 1 之间).什么是简单和/或有效的解决方案?

All I need is an array of N probability weights (between 0 and 1) that sum up to one. What would be an easy and/or efficient solution?

我的解决方案:

N <- 40
weights <- runif(40)
f <- 1/sum(weights) 
weights <- f*weights
print(sum(weights))

推荐答案

解决方案:

您可以使用 prop.table 函数和 runif 函数:

You can use prop.table function and runif function:

weights <- prop.table(runif(N))

这和跑步一样

w <- runif(N); weights <- w / sum(w)

说明:

  1. runif 函数生成 N 个范围从 0 到 1 的随机数
  2. prop.table 重新缩放它们,使 sum 等于 1(与 w/sum(w) 相同)
  1. runif function generates N random numbers in range from 0 to 1
  2. prop.table rescales them, so that sum is equal to 1 (does the same as w / sum(w))

这篇关于总和为 1 的概率权重的有效随机数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆