Anuncios

Tambien hay una version en castellano de este post, click aca.

Anuncios

Welcome to this post, we’ll talk how to create random numbers.

Anuncios

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"
Anuncios

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:

Anuncios

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"
Anuncios

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:

Anuncios

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"
Anuncios

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:

Anuncios

Now, in this video we’ve a most realistic example where we obtain numbers that we can use in our codes.

Anuncios

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:

Anuncios

Donatión

It’s for site maintenance, thanks!

$1.50