◐ Shell
clean mode source ↗

Data types - Numbers by kooshan75 · Pull Request #18 · javascript-tutorial/fa.javascript.info

@@ -1,6 +1,6 @@ # The simple but wrong solution # جواب ساده اما اشتباه
The simplest, but wrong solution would be to generate a value from `min` to `max` and round it: جواب اشتباه اما ساده این است که مقداری از `min` تا `max` رو تولید کنیم و رندش کنیم:
```js run function randomInteger(min, max) { Expand All @@ -11,23 +11,22 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ```
The function works, but it is incorrect. The probability to get edge values `min` and `max` is two times less than any other. این تابع کار میکند اما غلط است. احتمال اینکه مقادیر لبه `min` و `max` را در نتیجه بگیریم، نصف بقیه‌ست.
If you run the example above many times, you would easily see that `2` appears the most often. اگر شما مثال بالا را به کرات اجرا کنید، میبینید که عدد ۲ اکثر اوقات ظاهر می‌شود.
That happens because `Math.round()` gets random numbers from the interval `1..3` and rounds them as follows: به این علت است که `Math.round()` اعداد تصادفی از بازه `1..3` را میگیرد و به شکل زیر رند می‌کند.
```js no-beautify values from 1 ... to 1.4999999999 become 1 values from 1.5 ... to 2.4999999999 become 2 values from 2.5 ... to 2.9999999999 become 3 ```
Now we can clearly see that `1` gets twice less values than `2`. And the same with `3`. حالا میتوانیم به وضوح ببینیم که عدد ۲، دو برابر عدد یک مقادیر به آن نسبت داده میشود. همینطور هم برای عدد ۳. # راه حل صحیح
# The correct solution
There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from `0.5 to 3.5`, thus adding the required probabilities to the edges: راه حال‌های صحیح زیادی وجود دارد. یکی از آنها تنظیم نقاط مرزی‌ست. برای اطمینان یافتن از ازینکه بازه‌ها برابرند میتوانیم مقادیر را از `0.5 تا 3.5` تولید کنیم، سپس احتمال لازم صحیح را به حالات لبه نسبت دهیم:
```js run *!* Expand All @@ -41,7 +40,7 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ```
An alternative way could be to use `Math.floor` for a random number from `min` to `max+1`: راه دیگر میتواند استفاده از `Math.floor` باشد برای یک عدد تصادفی از `min` تا `max+1`:
```js run *!* Expand All @@ -55,12 +54,12 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ```
Now all intervals are mapped this way: حال، تمام بازه ها بدین شکل می‌شوند:
```js no-beautify values from 1 ... to 1.9999999999 become 1 values from 2 ... to 2.9999999999 become 2 values from 3 ... to 3.9999999999 become 3 ```
All intervals have the same length, making the final distribution uniform. همه ی بازه‌ها الان طول یکسانی دارند و در نهایت توزیع یکسانی دارند.