JS generate random boolean(JS 生成随机布尔值)
问题描述
简单的问题,但我对这里的细微差别很感兴趣.
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 到 1 的范围内,包括 0,但不包括 1").您可以将范围分为 [0, 0.5) 和 [0.5, 1).
You can compare Math.random() to 0.5 directly, as the range of Math.random() is [0, 1) (this means 'in the range 0 to 1 including 0, but not 1'). You can divide the range into [0, 0.5) and [0.5, 1).
var random_boolean = Math.random() < 0.5;
// Example
console.log(Math.random() < 0.1); //10% probability of getting true
console.log(Math.random() < 0.4); //40% probability of getting true
console.log(Math.random() < 0.5); //50% probability of getting true
console.log(Math.random() < 0.8); //80% probability of getting true
console.log(Math.random() < 0.9); //90% probability of getting true
这篇关于JS 生成随机布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JS 生成随机布尔值
基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
