Hello,
How to Generate Random Numbers within Range
for example:input numbers are 1 and 5 then generate 4.365
It is important that the answer is in decimals, not whole numbers.
Thanks for helping me
function getRandomDecimal(min, max) {
return min + (max - min) * Math.random();
}
let random = getRandomDecimal(1, 5);
return (random); // Example: 4.365
Ps: replace 1 and 5 with p1 and p2 in the JavaScript column.
Do you want the random number to be repeated on multiple rows or it has to be unique on each row?
Hello @Kemal1973
In additon to @HTML’s response, there is also a two steps method using Computed columns:
-
Create a
Random Number
(Random Number) column. It will generate a value between 0 and 1 by default, based on a seed. Useful if your pseudorandom number generator must be deterministic (i.e.: if you use the same seed, you’ll get the same result)
-
Create a
Random Number in range
(Math) with this formularandom * (max - min) + min
. For the explanation, it’s quite logic:
- with
min
= 1 andmax
= 5 - if random provides 0, you have
0 * 4 + 1
= 1 - if random provides 1, you have
1 * 4 + 1
= 5 - anything between 0 and 1 will cover the range inbetween
You will obtain the following table:
Hope that’s useful
I would add to Nicolas’ answer that should the Seed
of the Random Number
column be based off a timestamp (like a Date
column) and in particular one that changes constantly (or every 10 seconds like the Now
value in a Math
column) then you can have random numbers that are consistently different and constantly changing every 10 seconds. I am not sure 100% but I believe “consistently” here is correct.
That would give you the same value on every row, which may or may not be what is desired.
If instead a different value on every row is desired, I would use a RowID as the seed, and then apply the formula given by @Nicolas_Joseph
I think it really depends on the use case and the UX in the app:
-
If I needed a list of random numbers then I would use Row IDs as the seed as Nicolas suggested.
-
And if I needed one random number only, such as one generated by the click of a button, I would do this in a single row, probably in a user-specific column, and I’d use date-time as a seed to simulate changing row IDs.
Thank you for everybody’s response.@nathanaelb and @Nicolas_Joseph .I used this method.
Hello,
I tried this but it didn’t work.I think because of my free plan and JavaScript column doesn’t support.Am i right?
JavaScript is available on all plans. If you show us how you configured the column we may be able to point out where it is wrong.
It will work on any plan, maybe you did not set it up correctly:
copy and paste this code:
function getRandomDecimal(min, max) {
return min + (max - min) * Math.random();
}
let random = getRandomDecimal(p1, p2);
if(!p1 || !p2) {return 0}
else {
return (random)}
Thank you @HTML