我试图使用javascript来实现PCFG的内-外算法。但我有一堆随机数据。
假设我需要10个随机数,我需要:
我不知道该怎么做。
目前,我只能落实其中一项。谢谢你们所有人。
发布于 2015-07-10 09:17:22
查看此页面(random.asp)
Math.random();会给你一个介于0到1之间的数字。
假设您对数字值没有任何限制,并且只能实现这两点中的一个,一种想法可以是在0到0.25之间生成4个数字(n1到n4)。你只有很少的零钱才能得到4乘以0.25 = 1,你的第五个数字将仅仅是1- (n1+n2+n3+n4)。
现在如何得到0到0.25之间的随机数?可能除以4 Math.random()?(小心除以0 !)
同样的想法也适用于你的第二个问题,有6个数字,除以6(得到0到1/6之间的每个数字,最后提醒得到1)。
编辑:
检查这个并改进它!
<html>
<head>
<title>Stackoverflow question 31336708</title>
</head>
<body>
<script type="text/javascript">
// Solve rule #2
var n3=Math.random()/6;
var n4=Math.random()/6;
var n5=Math.random()/6;
var n8=Math.random()/6;
var n9=Math.random()/6;
var n10=1-(n3+n4+n5+n8+n9); // filling the cup for rule #1
// limit case for rule #1 : n3=n4=n5 = 1/6 and n8=n9 = 0. n10 = 0.5 ==> spread 0.5 on n6 and n7 ==> random/4
// other limit case for rule #1 : n3=n4=n5 = 0 and n8=n9 = 1/6. n10 = 4/6=2/3 ==> spread 1/3 on n6 and n7 ==> random/6
// ==> cut the apple in two ==> use random/5 for n2
var n2=Math.random()/5;
var n1=1-(n2+n3+n4+n5); // filling the cup for rule #2
var R1=n1+n2+n3+n4+n5;
var R2=n3+n4+n5+n8+n9+n10;
//checking :
alert("Checking rule #1 = <"+R1+"> with\n n1="+n1+"\n n2="+n2+"\n n3="+n3+"\n n4="+n4+"\n n5="+n5);
alert("Checking rule #2 = <"+R1+"> with\n n3="+n3+"\n n4="+n4+"\n n5="+n5+"\n n8="+n8+"\n n9="+n9+"\n n10="+n10);
</script>
</body>
</html>发布于 2015-07-10 18:10:44
我会试着分两步做
x1 = sample in the range [0...1-(3+4+5)] x2 = 1-(3+4+5) - x1第二,对6、7、8、9、10采取同样的办法
y1 = sample in the range [0...1-(8+9+10)]
y2 = 1-(8+9+10) - y1https://stackoverflow.com/questions/31336708
复制相似问题