[英]Hey! Why my Javascript code is not working
I tried to create a function in Javascript that will give a random integer between two integers (including both).我试图在 Javascript 中创建一个 function ,它将在两个整数(包括两者)之间给出一个随机的 integer 。 But, unfortunately this is not including the first integer.
但是,不幸的是,这不包括第一个 integer。 The code is as follows:
代码如下:
const randomEjector = (num1,num2) => {return Math.ceil(Math.random() * (num2 - num1)) + num1}
I am considering the analogy of inequality.我正在考虑不平等的类比。
++ Let's consider, ( Math.random()
will output a no. between 0( including ) and 1( excluding )). ++ 让我们考虑一下,(
Math.random()
将 output 一个介于 0(包括)和 1(不包括)之间的数字)。
Let's say x = Math.random()
, then x∈[0,1)假设
x = Math.random()
,那么x∈[0,1)
So, 0 ≤ x < 1
所以,
0 ≤ x < 1
0 * (num2-num1) ≤ x * (num2-num1) < 1 * (num2-num1)
Again, x*(num2-num1)∈[0,1*(num2-num1))
同样,
x*(num2-num1)∈[0,1*(num2-num1))
Now opening Math.ceil()
part:现在打开
Math.ceil()
部分:
But, Math.ceil()
is like greatest integer function :但是,
Math.ceil()
就像最大的 integer function :
So, for (0,1] it will return 1 .因此,对于(0,1] 它将返回 1 。
for 0 => 0对于0 => 0
and for interval ((num2-num1)-1,(num2-num1))
,it will return (num2-num1) .对于
interval ((num2-num1)-1,(num2-num1))
,它将返回(num2-num1) 。
So, After Math.ceil()
is executed, we should be left with an interval [0,(num2-num1)] .因此,在执行
Math.ceil()
之后,我们应该留下一个区间[0,(num2-num1)] 。
Now, x*num2-num1
∈ [0,(num2-num1)]现在,
x*num2-num1
∈ [0,(num2-num1)]
Finally, let y = x*(num2-num1)
最后,
let y = x*(num2-num1)
So, 0 ≤ y ≤ (num2-num1)
所以,
0 ≤ y ≤ (num2-num1)
So, 0 + num1 ≤ y + num1 ≤ (num2-num1) + num1
所以,
0 + num1 ≤ y + num1 ≤ (num2-num1) + num1
Which will give num1 ≤ y + num1 ≤ num2
这将给出
num1 ≤ y + num1 ≤ num2
Let, z = y + num1
让,
z = y + num1
So, z ∈ [num1,num2]
所以,
z ∈ [num1,num2]
Then, why my function is excluding 1st term and making it like (num1,num2]?那么,为什么我的 function 不包括第一个术语并使其像(num1,num2)?
Where's the problem?问题出在哪里?
For instance for console.log(randomEjector(3,4))
, it will always give 4 and never 3.例如对于
console.log(randomEjector(3,4))
,它总是给出 4 而从不给出 3。
It's unspeakably unlikely that Math.random()
will ever return exactly 0, so Math.ceil(Math.random())
will unspeakably likely always return 1. Math.random()
不太可能准确地返回 0,因此Math.ceil(Math.random())
可能总是返回 1。
In other words, randomEjector(3,4)
will, once in a very, very blue moon, give you 3.换句话说,
randomEjector(3,4)
会在非常非常蓝的月亮中给你 3。
It returns 4 because you are always ceiling the result, if you want it to return 4 then you need to floor the result.它返回 4,因为您总是对结果进行上限,如果您希望它返回 4,那么您需要对结果进行下限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.