Tambien hay una version en castellano de este post, click aca.
Welcome to this post, we’ll talk how to create random numbers.
But the computers don’t generate real random numbers because they’re not prepared to create them from nothing. Actually, the computer has an established list of numbers and the function that «generates» random numbers returns a number from this list but this has one inconvenient. Let’s watch the following example:
dim output
for a = 1 to 5
output = output & rnd() & vbcrlf
next
msgbox output,,"Random Numbers"
First, we declare a variable. Then, we use a for to make 5 cycles to generate a random number with rnd and store each result in the above variable. Finally, we show the final result of output. Let’s watch how it works with the following video:
On the video, we watch that everytime we execute the script, this returns all the same values but we can fix it. Let’s take the above example and change it in the following way:
randomize timer
dim output
for a = 1 to 5
output = output & rnd() & vbcrlf
next
msgbox output,,"Random Numbers"
In this case, it’s the same code but we add a new statement, randomize timer, and this make that rnd doesn’t start in the same position every time that we call it. This will generate a sensation that we’re «randomizing» numbers. Let’s watch how it works now:
Now, the numbers are differents on every call to rnd. This code generates random numbers but we can improe the above code in the following way:
randomize timer
dim output
dim number
for a = 1 to 5
number = int(rnd() * 10) + 1
output = output & number & vbcrlf
next
msgbox output,,"Random Numbers"
We add a new variable to store our random number. In the loop, we take the rnd function and we multiply by 10. This make that the number generated it goes from 1 to 10. Not begins from 0 because we add a plus 1 outside the int. And the int function only returns the integer part eliminating the decimals from the number generated. Then, we store the above variable on the output variable, just we did in the other examples, and finally we show it. Let’s watch how it works:
Now, in this video we’ve a most realistic example where we obtain numbers that we can use in our codes.
In summary, we talk about random numbers, how it works, how we can make it really random, a few examples to watch how it works. I hope you’ve found it useful. You can follow me on this social networks:


Donatión
It’s for site maintenance, thanks!
$1.50
