473,799 Members | 2,950 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems Generating Random Numbers

I have a quick Question and I Hope some one can help or at least explain.

What is happening is that I am trying to use random numbers in an application, as per the sample test code below. When I run this code the random numbers that are displayed are all the same for abot 25 cycles and then randomize as normal.

Can some one tell me why this is or at least tell me what I am doing wrong.

Regards Glenn

Module Module1

Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop, RollPercent)
Next
Console.ReadLin e()
End Sub

Public Function RollPercent() As Integer
Dim tmpRandom As New Random(Environm ent.TickCount)
Return tmpRandom.Next( 1, 101)
End Function

End Module
Nov 20 '05 #1
10 1699
Environment.Tic kCount returns milliseconds, which aren't granular enough for the way you're going about this. So essentially you are creating multiple random numbers with the same seed, which of course means that they're not random at all.

You should change your tmpRandom to a private member of the class and initialize it only once. Then call tmpRandom.Next as you are doing now.
Nov 20 '05 #2
I beleive it has to do with the variable scope, if you create the variable
inside the function and initiate the value to environment.tic k the SEED will
remain the same until the next tick, same seed causes same "random" number.
Try the same example with a module level random like this:

Module Module1

Dim tmprandom As New System.Random(N ow.Millisecond)
Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop, RollPercent)
Next
Console.ReadLin e
End Sub

Public Function RollPercent() As Integer
'Dim tmpRandom As New Random(Now.Mill isecond)
Return tmpRandom.Next( 1, 101)
End Function
End Module
"Glenn Wilson" <Gl*********@di scussions.micro soft.com> wrote in message
news:CA******** *************** ***********@mic rosoft.com...
I have a quick Question and I Hope some one can help or at least explain.

What is happening is that I am trying to use random numbers in an
application, as per the sample test code below. When I run this code the
random numbers that are displayed are all the same for abot 25 cycles and
then randomize as normal.

Can some one tell me why this is or at least tell me what I am doing
wrong.

Regards Glenn

Module Module1

Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop, RollPercent)
Next
Console.ReadLin e()
End Sub

Public Function RollPercent() As Integer
Dim tmpRandom As New Random(Environm ent.TickCount)
Return tmpRandom.Next( 1, 101)
End Function

End Module

Nov 20 '05 #3
Thanks will give it a go

"Jared" wrote:
I beleive it has to do with the variable scope, if you create the variable
inside the function and initiate the value to environment.tic k the SEED will
remain the same until the next tick, same seed causes same "random" number.
Try the same example with a module level random like this:

Module Module1

Dim tmprandom As New System.Random(N ow.Millisecond)
Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop, RollPercent)
Next
Console.ReadLin e
End Sub

Public Function RollPercent() As Integer
'Dim tmpRandom As New Random(Now.Mill isecond)
Return tmpRandom.Next( 1, 101)
End Function
End Module
"Glenn Wilson" <Gl*********@di scussions.micro soft.com> wrote in message
news:CA******** *************** ***********@mic rosoft.com...
I have a quick Question and I Hope some one can help or at least explain.

What is happening is that I am trying to use random numbers in an
application, as per the sample test code below. When I run this code the
random numbers that are displayed are all the same for abot 25 cycles and
then randomize as normal.

Can some one tell me why this is or at least tell me what I am doing
wrong.

Regards Glenn

Module Module1

Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop, RollPercent)
Next
Console.ReadLin e()
End Sub

Public Function RollPercent() As Integer
Dim tmpRandom As New Random(Environm ent.TickCount)
Return tmpRandom.Next( 1, 101)
End Function

End Module


Nov 20 '05 #4
It's because the function calls are happening so fast that they're occurring
between tick counts. That's why you're getting duplicate values.

"Glenn Wilson" <Gl*********@di scussions.micro soft.com> wrote in message
news:CA******** *************** ***********@mic rosoft.com...
I have a quick Question and I Hope some one can help or at least explain.

What is happening is that I am trying to use random numbers in an application, as per the sample test code below. When I run this code the
random numbers that are displayed are all the same for abot 25 cycles and
then randomize as normal.
Can some one tell me why this is or at least tell me what I am doing wrong.
Regards Glenn

Module Module1

Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop, RollPercent) Next
Console.ReadLin e()
End Sub

Public Function RollPercent() As Integer
Dim tmpRandom As New Random(Environm ent.TickCount)
Return tmpRandom.Next( 1, 101)
End Function

End Module

Nov 20 '05 #5
yEaH rIgHt,
Try the example for yourself. I realize what you are saying and I too
beleive this, but, I think it has to do with the scope of the variable. If
you instantiate the random generator inside the function the tick count may
be very well be the same for may cycles, resulting in duplicate numbers.
That is way I said if you instantiate the variable at a different level the
SEED has already been assigned resulting in a "non-duplicating" random
number. If I'm way off, someone please correct me.
Jared
"yEaH rIgHt" <nospam@haha> wrote in message
news:10******** *****@corp.supe rnews.com...
It's because the function calls are happening so fast that they're
occurring
between tick counts. That's why you're getting duplicate values.

"Glenn Wilson" <Gl*********@di scussions.micro soft.com> wrote in message
news:CA******** *************** ***********@mic rosoft.com...
I have a quick Question and I Hope some one can help or at least explain.

What is happening is that I am trying to use random numbers in an

application, as per the sample test code below. When I run this code the
random numbers that are displayed are all the same for abot 25 cycles and
then randomize as normal.

Can some one tell me why this is or at least tell me what I am doing

wrong.

Regards Glenn

Module Module1

Sub Main()
Dim rLoop As Integer
For rLoop = 1 To 100
Console.WriteLi ne("Return Value {0} - {1}", rLoop,

RollPercent)
Next
Console.ReadLin e()
End Sub

Public Function RollPercent() As Integer
Dim tmpRandom As New Random(Environm ent.TickCount)
Return tmpRandom.Next( 1, 101)
End Function

End Module


Nov 20 '05 #6
Declare the Random as static and only create it once.

Public Function RollPercent() As Integer
Static tmpRandom As Random
'Random uses time based seed by default so no need to specify.
If tmpRandom Is Nothing Then tmpRandom = New Random()
Return tmpRandom
End Function
--
Mick Doherty
http://homepage.ntlworld.com/mdaudi1...nate/home.html
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.701 / Virus Database: 458 - Release Date: 07/06/2004
Nov 20 '05 #7
I don't think I am explaining this right. I am trying to say that when Glenn
was creating the variable inside the function the seed value was the same,
causing duplicate numbers. This was all relitave to the scope of the
variable in THIS example. I am not saying the only way to do this is make a
module level variable. I need to quit trying to help people, I am no expert,
and, instead of building on a post people seem to try to "one-up" or
"out-do" another poster; there are many ways to do any single task. My way
is not better, I was only explaining why I believed the value was
duplicating at the request in the original post. Everyone else is just
giving examples of how to correct the problem, which is fine, but if Glen
doesn't know what he is doing "wrong" how can he prevent this in the future?
"Mick Doherty"
<EX***********@ AND.REMOVE.SQUA REBRACKETS.[mdaudi100#ntlwo rld.com]> wrote in
message news:ey******** ******@TK2MSFTN GP11.phx.gbl...
Declare the Random as static and only create it once.

Public Function RollPercent() As Integer
Static tmpRandom As Random
'Random uses time based seed by default so no need to specify.
If tmpRandom Is Nothing Then tmpRandom = New Random()
Return tmpRandom
End Function
--
Mick Doherty
http://homepage.ntlworld.com/mdaudi1...nate/home.html
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.701 / Virus Database: 458 - Release Date: 07/06/2004

Nov 20 '05 #8
Of course it was the way he was seeding the Random class that was causing
the problem. I wasn't disputing that. Take a couple of deep breaths. It's
going to be o.k.
"Jared" <VB***********@ email.com> wrote in message
news:10******** *****@corp.supe rnews.com...
I don't think I am explaining this right. I am trying to say that when Glenn was creating the variable inside the function the seed value was the same,
causing duplicate numbers. This was all relitave to the scope of the
variable in THIS example. I am not saying the only way to do this is make a module level variable. I need to quit trying to help people, I am no expert, and, instead of building on a post people seem to try to "one-up" or
"out-do" another poster; there are many ways to do any single task. My way
is not better, I was only explaining why I believed the value was
duplicating at the request in the original post. Everyone else is just
giving examples of how to correct the problem, which is fine, but if Glen
doesn't know what he is doing "wrong" how can he prevent this in the future?

"Mick Doherty"
<EX***********@ AND.REMOVE.SQUA REBRACKETS.[mdaudi100#ntlwo rld.com]> wrote in message news:ey******** ******@TK2MSFTN GP11.phx.gbl...
Declare the Random as static and only create it once.

Public Function RollPercent() As Integer
Static tmpRandom As Random
'Random uses time based seed by default so no need to specify.
If tmpRandom Is Nothing Then tmpRandom = New Random()
Return tmpRandom
End Function
--
Mick Doherty
http://homepage.ntlworld.com/mdaudi1...nate/home.html
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.701 / Virus Database: 458 - Release Date: 07/06/2004


Nov 20 '05 #9
I was not disagreeing with you. I just posted an alternative solution. I did
not need to explain the cause of the problem since you had already done
that.

--
Mick Doherty
http://homepage.ntlworld.com/mdaudi1...nate/home.html
"Jared" <VB***********@ email.com> wrote in message
news:10******** *****@corp.supe rnews.com...
I don't think I am explaining this right. I am trying to say that when Glenn was creating the variable inside the function the seed value was the same,
causing duplicate numbers. This was all relitave to the scope of the
variable in THIS example. I am not saying the only way to do this is make a module level variable. I need to quit trying to help people, I am no expert, and, instead of building on a post people seem to try to "one-up" or
"out-do" another poster; there are many ways to do any single task. My way
is not better, I was only explaining why I believed the value was
duplicating at the request in the original post. Everyone else is just
giving examples of how to correct the problem, which is fine, but if Glen
doesn't know what he is doing "wrong" how can he prevent this in the

future?

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.701 / Virus Database: 458 - Release Date: 07/06/2004
Nov 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
7292
by: eric.gagnon | last post by:
In a program randomly generating 10 000 000 alphanumeric codes of 16 characters in length (Ex.: "ZAZAZAZAZAZAZ156"), what would be an efficient way to ensure that I do not generate duplicates? STL set, map? Could you give me a little code example? Thank you.
1
30937
by: Intaek LIM | last post by:
generally, we use srand(time(0)) to generate random numbers. i know why we use time(0), but i can not explain how it operates. first, see example source below. --------------------------------------------- #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv)
16
12082
by: Leon | last post by:
I need a program that generate 5 non-duplicates random number between 1-10 as string values store in an array. Do anybody know of any good books or websites that explain how to generator random numbers using asp.net? I know about the random namespace within .net, but I need a reference to some code that do the similar stated function above. Plus If you have any coding practice ideas for the above defined project please share them.
2
2742
by: randomcz | last post by:
hi, i need help with generating random numbers; The task is to generate hundreds of random vectors, like 1,3,5,6,7 2,4,5,4,8 ... I used the current time as the random seed, but it turns out
1
2677
by: Velhari | last post by:
Hi, I am a beginner. Please tell me, For generating Random Numbers, Initially why we are going for seed method. And another question is that, I want to print unique random number how to print by using rand() method to print unique random number. And finally i want to know, If a program generate random numbers and the same program will execute after 100 or some days, it will not to generate the old random number (i.e the random number...
8
25482
by: kiranchahar | last post by:
Hey all, How do I generate random numbers with Uniform distribution Uniform(a,b) using C-programming? I want to generate uniform random numbers which have mean following Uniform(p,q) and also variance as Uniform(s,t)? any suggestion would be really appreciated. Thanks, Kay
0
26053
SammyB
by: SammyB | last post by:
These are some "random" thoughts about generating random numbers in Visual Basic. Wikipedia will give a better introduction than I, see http://en.wikipedia.org/wiki/Random_number_generator. The key point is that you need to start the random number generator with a seed. Doing it in the form load with the number of milliseconds since midnight is an easy way to start. The VB.Net version This demo project will be as simple as I can...
12
2979
by: 9966 | last post by:
Greetings, This is my second post till now. Thanks for all the advice given to me for the first post. Now I'm having problem with generating random numbers. I know if we want to generate a random number, we can use: int tempNUM = rand(); But, once I execute the program, the generated number is always similar, and I found this from the internet. It says need to add this line to make the numbers generated differently:
26
7921
by: bilgekhan | last post by:
What is the correct method for generating 2 independent random numbers? They will be compared whether they are equal. What about this method: srand(time(0)); int r1 = rand(); srand(rand()); int r2 = rand(); bool f = r1 == r2;
0
9686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9540
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10475
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10250
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10026
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.