473,545 Members | 2,095 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Same random numbers being created every time the loop goes around

1 New Member
Hi. I am a beginner at C++ and for one of my project involves loop inside loops and creating random numbers. Here is what I have so far:#include <iostream>
Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <iomanip>
  5. #include <cstdio>
  6. #include<random>
  7.  
  8. using namespace std;
  9.  
  10. int main()
  11. {    
  12.     srand((unsigned int)time(0));
  13.  
  14.     {
  15.         cout << "Name of reservoir: ";
  16.         string reservior_name;
  17.         cin >> reservior_name;
  18.  
  19.         cout << "Capacity in MAF: ";
  20.         double capacity;
  21.         cin >> capacity;
  22.  
  23.         cout << "Maximum inflow in MAF: ";
  24.         int max;
  25.         cin>> max;
  26.  
  27.         cout << "minimum inflow in MAF: ";
  28.         int min;
  29.         cin >> min;
  30.         if(min>max)
  31.         {cout<<endl<<"Error: The minimum inflow is higher than the maximum inflow."<<endl
  32.              << "Please re-enter your minimum inflow: ";
  33.         cin>>min;
  34.         }
  35.         double inflow_range= max-min;
  36.  
  37.         cout <<"required outflow in MAF: ";
  38.         double required;
  39.         cin >> required;
  40.         if (required > 0.9 * (min + max)/2)
  41.         {
  42.             cout<<endl<< "Warning: required ouflow is over 90% of the average inflow."<<endl
  43.                 << "Returning to main menu ";
  44.         }
  45.         else
  46.         { const     int simulations = 10;
  47.                     int water_level = 0;
  48.                     int years = 1;
  49.                     cout << "Running simulation..." << endl;
  50.                     for (int i = 1; i <= simulations; i++) 
  51.                     {
  52.                         int x = (rand()% (max-min + 1)) + min;
  53.  
  54.                         while (water_level < capacity)
  55.                         {
  56.                             //double r = rand() * 1.0 / RAND_MAX;
  57.                             //double x = min + inflow_range * r;
  58.                             //int x = (rand()% (max-min + 1)) + min;
  59.                             if (water_level + x > required)
  60.                             {
  61.                             water_level = water_level + x - required;
  62.                             }
  63.                             else
  64.                             {
  65.                                 water_level= 0;
  66.                             }
  67.                             years++;
  68.  
  69.                         }   
  70.                     cout <<"Simulations"<< i << "took" << years <<" to finish"<< endl;
  71.                     }
  72.         }
  73.     }
  74. system ("pause");
  75. return 0;        
  76. }

So my main question is I'm running into a wall concerning setting up the for loops underneath "Running simulation" where I need to set up the first for loop to run the internal for loop 10 times, with each of those 10 iterations of the internal for loop coming up with random numbers for the range of acceptable results from the query for a random value. I've been told that the idea is to use the Monte Carlo method, i.e. I put in here both the Monte Carlo method and the normal random number generating method. Here it is:
Expand|Select|Wrap|Line Numbers
  1.  for (int i = 1; i <= simulations; i++) 
  2.                     {
  3.                         int x = (rand()% (max-min + 1)) + min;
  4.  
  5.                         while (water_level < capacity)
  6.                         {
  7.                             //double r = rand() * 1.0 / RAND_MAX;
  8.                             //double x = min + inflow_range * r;
  9.                             //int x = (rand()% (max-min + 1)) + min;
so the program will create a random value for the inflow. The idea is that the internal for loop will continue to run until the fill_level of the reservoir, which starts at 0, hits the capacity. The process of simulating how many years (each iteration of the internal for loop representing a year) is to be repeated 10 times by the parent for loop of the water_level simulation for loop.

The problem is that the random number that is supposed to created are the same number. THey are different every time I run it, but they are the same every time the loops repeat to make a new simulation. I have tried to figure out what the problem is for hours and still stuck. Any help is very appreciated.
May 20 '13 #1
3 1654
Rabbit
12,516 Recognized Expert Moderator MVP
That's because you're seeding the RNG with the same number every time on line 12.
May 20 '13 #2
Oralloy
988 Recognized Expert Contributor
[Rabbit] It looks like he is seeding the random number generator off of the current time. This should work, unless his clock is broken.

[khangho] What you are saying is that x is constant for all simulations?

Look at line 52, which generates x, which is apparently your inflow rate. This is going to be constant across the water level loop at line 54, so if the inflow is less than the required amount, the lake will ultimately drop to zero and stay there. Probably not what you want.

Why are lines 56 through 58 commented out? These look to be the correct place to generate your random value, not outside the loop.

Hopefully that helps a little,
Oralloy
May 20 '13 #3
donbock
2,426 Recognized Expert Top Contributor
The resolution of the time_t value returned by time() [line 12] is implementation defined. It might be microseconds, milliseconds, seconds, minutes, hours, days, or anything. You can't be sure that two successive calls to time() will return different values.

time() returns -1 if there is a problem with the operating system timekeeping facility. If there were a problem then every call to time() is sure to return the same value.
Jun 7 '13 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
5324
by: AndyW | last post by:
hey folks, Just have some code as follows:- for( int i=0; i<10; i++) { Random randomNumberGenerator; randomNumberGenerator = new Random(); int num = randomNumberGenerator.nextInt(10); System.out.println( num ); }
1
30892
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)
3
24511
by: JoelPJustice | last post by:
I am working through a VBA book by myself to help and try and improve my skills. However, the book does not give you solutions to certain problems. I have worked through this problem up until bullet point 3. Here is the code I came up with up until now. Function RandomNormal(Mean As Double, StdDev As Double) As Double Application.Volatile...
3
1191
by: clsmith66 | last post by:
I'm hoping someone can help me with a problem I'm having using the random class. I need to return a "random" number between 0 and 15, so i did this Dim r as new Random() Return r.Next(0, 15) When I run my application, I call this code 12 times, one right after another, but it keeps retuning the same number. If I put a break point in and...
5
1292
by: Anthony | last post by:
For Some reason, i get the same value everytime... Ive tested the RND Function with msgboxes and labels, they all have no influence on the RND Function... It still doesnt work... Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim count As Integer Dim rndNumber(5) As Integer Dim...
6
2117
by: Pao | last post by:
My code works in this way: I declared a static array in a class (public static int GVetRandom = new int;) that in a for cycle I fill with random numbers. The array gets cleared (clear method) and refilled at each turn of cycle. On my developing pc, the same sequence of random numbers was repeated from on turn of cycle to the other; I put...
8
5681
by: Aspidus | last post by:
Hi, I wrote a function that generates a ulong I use it 3 times, one after the other, but it generates always the same numbers. At the end i get always 3 equal arrays. Any idea?
4
13135
by: Buckaroo Banzai | last post by:
Hi, I'm trying to generate 3 random numbers inside a while loop. The problem I encountered is that I always get the same 3 numbers even after I reseed the number using srand((unsigned)time(NULL)); while (J < 3) { srand((unsigned)time(NULL)); //Seed the random number generator. int Rand1 = rand() % 100 +...
14
2623
Deathwing
by: Deathwing | last post by:
Hi everyone, I'm fairly new with python and as such am playing around alot with just basic coding/scripting. I've spent the better part of today working with random numbers. Thanks for all your comments and advice it's really helped me to learn. I have a new question that I an thinking about right now, I have an idea of how to proceed but wanted...
26
7875
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
7396
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...
0
7805
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...
0
5968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5323
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4943
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...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1874
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
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
700
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...

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.