总和为 1 的概率权重的有效随机数组

编程入门 行业动态 更新时间:2024-10-28 05:19:06
本文介绍了总和为 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)

说明:

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

    总和为 1 的概率权重的有效随机数组

    本文发布于:2023-11-30 11:15:15,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649777.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:权重   数组   总和   概率

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!