JS生成随机布尔值 [英] JS generate random boolean
问题描述
简单的问题,但我对这里的细微差别很感兴趣。
Simple question, but I'm interested in the nuances here.
我正在使用我自己提出的以下方法生成随机布尔值:
I'm generating random booleans using the following method I came up with myself:
const rand = Boolean(Math.round(Math.random()));
每当 random()
出现时,它似乎总有一个陷阱 - 它不是真正的随机,它被某些东西或其他东西等所妥协。所以,我想知道:
Whenever random()
shows up, it seems there's always a pitfall - it's not truly random, it's compromised by something or other, etc. So, I'd like to know:
a)以上是最佳实践方式吗?
a) Is the above the best-practice way to do it?
b)我是否在思考问题?
b) Am I overthinking things?
c)我是否解开了事情?
c) Am I underthinking things?
d)我不知道有更好/更快/更优雅的方式吗?
d) Is there a better/faster/elegant-er way I don't know of?
(如果B和C是互斥的,也有点兴趣。)
(Also somewhat interested if B and C are mutually exclusive.)
更新
如果它有所不同,我用它来移动AI字符。
If it makes a difference, I'm using this for movement of an AI character.
推荐答案
从技术上讲,代码看起来很好,但有点太复杂了。
您可以直接将Math.random()与0.5进行比较,因为Math.random()的范围是[0,1]。您可以将范围分为[0,0.5)和[0.5,1]。
Technically, the code looks fine, but just a bit too complex. You can compare "Math.random()" to "0.5" directly, as the range of Math.random() is [0, 1). You can divide the range into [0, 0.5) and [0.5, 1).
var random_boolean = Math.random() >= 0.5;
这篇关于JS生成随机布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!