为javascript编写一个真正包容的随机方法 [英] Write a truly inclusive random method for javascript

查看:92
本文介绍了为javascript编写一个真正包容的随机方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript的MATH对象有一个随机方法,从set [0,1)0返回,包括1,exclusive。有没有办法返回一个包含1的真正随机方法。

Javascript's MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

例如

var rand = MATH.random()*2;

if(rand > 1)
{
   rand = MATH.floor(rand);
}

return rand; 

虽然这总是从集合[0,1]返回一个数字,但它并不是真正随机的。 / p>

While this always returns a number from the set [0,1] it is not truly random.

推荐答案

它是否包含边界应该无关紧要;事实上,严格来说,你要做的事情并没有多大意义。请记住,在连续概率分布下,获得特定值的概率无论如何都是无穷小的,所以从数学上讲,你永远不会看到1的确切值。

Whether it's inclusive of the boundaries shouldn't matter; indeed, strictly speaking what you're trying to do doesn't really make sense. Remember that under a continuous probability distribution, the probability of getting a specific value is infinitesimal anyway, so mathematically speaking, you'll never see the exact value of 1.

当然,在计算机世界中,RNG的分布并不是真正连续的,所以你可能会遇到一个特定的价值(无论这意味着什么),但事实上你依赖于一个限制如何存储实数,暗示您解决任何问题的方法存在问题。

Of course, in the world of computers, the distribution of an RNG isn't truly continuous, so it's "possible" that you'll encounter a specific value (whatever that means), but the fact that you're relying on an a limitation of how real numbers are stored hints at problems with your approach to whatever problem you're trying to solve.

这篇关于为javascript编写一个真正包容的随机方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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