Tilted Forum Project Discussion Community  

Go Back   Tilted Forum Project Discussion Community > Interests > Tilted Technology


 
 
LinkBack Thread Tools
Old 12-14-2003, 10:30 PM   #1 (permalink)
Riiiiight........
 
C++ crashes..... after it executes the last line in main()

so I have my C++ program, everything works fine. It even gives me output.

the last lines of my code in main() are

char x;
cin>>x;

its just to keep the window open until i press a key to allow the program to close.

but when i enter a character and press enter, it crashes.. or rather. windows says it crashes...

when i delete the cin, it just crashes on termination,

WHY??!!!!

thanks....... just about going crazy with this...
dimbulb is offline  
Old 12-14-2003, 11:36 PM   #2 (permalink)
Junkie
 
Location: North Hollywood
something else is going on cin>>x; probably isn't the cause, probably a stack overwrite, or buffer overrun.


while (!kbhit()); // Waits for keystroke

will also work or getch use conio.h

but replacing the cin will likely just cover up the real cause.
charliex is offline  
Old 12-14-2003, 11:48 PM   #3 (permalink)
In Your Dreams
 
Latch's Avatar
 
Location: City of Lights
Are you using Visual Studio? I had this problem before as well. Unfortunately, I can't remember why it was doing that. Try returning a value at the end of the function. That may fix it.
Latch is offline  
Old 12-14-2003, 11:53 PM   #4 (permalink)
kel
WARNING: FLAMMABLE
 
Location: Ask Acetylene
Could it be a destructor for one of your classes being called?
__________________
"It better be funny"
kel is offline  
Old 12-15-2003, 01:22 AM   #5 (permalink)
Pure Chewing Satisfaction
 
Moskie's Avatar
 
Location: can i use bbcode [i]here[/i]?
Quote:
Originally posted by Latch
Are you using Visual Studio? I had this problem before as well. Unfortunately, I can't remember why it was doing that. Try returning a value at the end of the function. That may fix it.
That was the first thing that came to my mind. Is main() a void function? Or an int? Not sure how you're compiler works, but having a return statement ('return;' for a void function, 'return 0;' if it's an int) before the function ends might help.
__________________
Greetings and salutations.
Moskie is offline  
Old 12-15-2003, 07:42 AM   #6 (permalink)
I am Winter Born
 
Pragma's Avatar
 
Location: Alexandria, VA
As I posted in the same thread in Knowledge:

I've had this sort of thing happen to me when I've got dynamic memory allocated that I never properly clean up after. Make sure if you allocate dynamic memory in your program, you free/delete it properly before the end of the program, and that all of the destructors for your classes are working properly.
__________________
Eat antimatter, Posleen-boy!
Pragma is offline  
Old 12-15-2003, 09:29 AM   #7 (permalink)
Riiiiight........
 
Thanks guys. I tried returning values at the end of main, but it still doesnt help.

Even though I'm pretty new at this, I've been careful to clear delete objects my pointers are pointing to before i reassign or delete the pointers.

Here's a bit more information.

the size of my vectors and arrays are mostly equal to a parameter i enter in, "totalPeriods". Now, the program works fine up to totalPeriods=20. then the funny termination error creeps in when i increase it beyond that.

I read in command line arguments to run my program, and i check that the arguments are correct. (well.. they should be, since the program runs and writes the output to a text file and all. )

I don't think anyone wants to wade through my 1000 lines of code right? Any volunteers are most welcome though...
dimbulb is offline  
Old 12-15-2003, 12:23 PM   #8 (permalink)
Banned
 
Location: 'bout 2 feet from my iMac
dimbulb: I think it might help find the solution. feel free to e-mail it to me, i'll take a look. lemme know what compiler you're using, too!
cheerios is offline  
Old 12-15-2003, 12:31 PM   #9 (permalink)
Junkie
 
Location: North Hollywood
i don't think its return types on a main, that won't crash VC, technically only int is a valid return type, but VC allows void happily, neither will not releasing memory. releasing memory twice might cause a crash, or releasing the wrong block of memory.

I'm betting its stack corruption, if its crashing at the end of main and its not in a destructor, the stack has probably been upset.

What does the debugger say ?, it should stop you exactly at the point it crashes with hopefully a useable stack trace, if you don't know how to debug, run it in the debugger, switch on the call stack, registers etc and take a readable screen shot and post it

Are you using local variables of a fixed size to read data into ?

I'll also be happy to help you if needed, perhaps zip up your project and post it somewhere if you can

Last edited by charliex; 12-15-2003 at 12:35 PM..
charliex is offline  
Old 12-15-2003, 05:18 PM   #10 (permalink)
kel
WARNING: FLAMMABLE
 
Location: Ask Acetylene
Just post the whole source already we could spot it in 30 seconds if we could actually see it.
__________________
"It better be funny"
kel is offline  
Old 12-15-2003, 06:06 PM   #11 (permalink)
Riiiiight........
 
PHP Code:
/*
C:\Fall2003Henderson\WorkFolder\IpaVar3.exe 1.5  2 150 5 4 11 17 20 20 17 0.5 1 1.3 1.5 1.3 1.1
C:\Fall2003Henderson\WorkFolder\IpaVar5.exe 1.5  999 1440 24 4 11    20    15    15    26    20    22    22    23    27    27    27    27    27    33    34    51    38    43    43    32    38    30    29    0.6    0.7    0.8    0.9    1    1.1    1.2    1.3    1.3    1.3    1.3    1.3    1.45    1.6    1.75    1.9    2.05    2.05    2.05    2.05    2.05    1.95    1.85    1.75    1.65
*/
/*

This version implements version 2 of the IPA algorithm

*/

#include<stdio.h>
#include "RNG.h"
#include "RngStream.h"
#include<math.h>
#include<fstream.h>
#include<vector>
#include<list>
#include "Customer.hpp"

using namespace std;
// 3 types of events- ARRIVAL = 0, COMPLETION = 1, ........
enum Event {ARRIVALCOMPLETIONPERIODEND};

/**********************Functions***********************************************/
void ReadCommandLine(char *pArgs[]);
void CalculateStats();
void WriteStatsFile();
void Simulate();
double RateFunct(double time);
void Initialize();
Event Transition();
void Arrival();
void Completion();
void PeriodEnd();
void Termination();
void UpdateIPA();
double Integral(double adouble b);
double NHPP(RngStream &generatordouble time);
double Exponential(RngStream &generatordouble lambda);
void ShowParameters();
void MakeTrace(Event event);
void PeriodEndTrace();
void ErrorTrace(fstream &DataFile);
void CheckIPACounters();
typedef unsigned short int USHORT;
typedef unsigned long int ULONG;



bool traceOn false;            //boolean to turn on and off trace. TRUE to turn trace on.
fstream TraceFile("Trace.txt",ios::in ios::out |ios::trunc);
double maxArrivalRate;          // maximum of arrival rate function over entire simulation
vector<doublearrivalRate;        //holds piecewise arrival rate, arrivalRate[i] = arrival rate at END of period i
vector<intnumServers;            //number of servers in each period
USHORT maxServers;                    //max number of servers in any period
double serviceRate;               // mu, the rate of service (services per minute)
double simTime 0;               // simulation time in minutes
double maxWait;                     //maximum waiting time in minutes to count as success
double endTime 0;               // time that simulation terminates (in minutes from start of sim)
ULONG numCallsTotal 0;          // number of incoming calls in total
ULONG numCallsServiced 0;       // number of calls that have started service
ULONG numCallsInSystem 0;       // number of calls in system now
double timeToPeriodEnd;            //time to end of period
double periodLength;              // length of each period in minutes
USHORT currentPeriod 1;         //current period
USHORT totalPeriods;               // total number of periods
USHORT totalReplications;          // number of replications
USHORT currentReplication =1;        // current replication
double timeToNextArrival 0;         // time to next arrival
USHORT serverLeastWork 0;          //index of server with least amount of work among all busy servers,
                                     //=0 if all servers free

vector<doubleworkRemain;          //holds remaining work time of each server
vector vector<double> > delta;    //holds accumulated infite delay, delta[server][period]
vector<doubleT;        //time that server i last completed a service, even if server i busy
vectorvector<double> > delKs;         //array of nperiods partial derivatives for call Ks. delKs[Ks][period]
vector<doublexiKs;            //holds time when a server became available to serve call Ks
vector<doubleAk;             //holds time of kth arrival

vectorvector<double> > meanIPAGrad;   //the mean of the IPA gradients obtained over all replications
vectorvector<double> > varIPAGrad;


vector<ULONGsuccessCounter;       //number of successful services during period during each replication
vector<ULONGnumCalls;             //number of arrivals during each period during each replication
vector<doublemeanSuccess;          //average number of succeses during each period
vector<doublevarSuccess;          //variance of the number of successes during each period
vector<doublemeanNumCalls;        //average number of arrivals during each period
list<Customer*> queue;               //the arrival queue, list of pointers to Customers in queue

// Random number Streams
RngStream arrivalStream;        // stream used for generating interarrival times in NHPP
RngStream workStream;           // stream used for generating exp(1) r.v for workload





int main(int argcchar *pArgs[])
{
  
//Read in values from command line arguments
  //This version takes in command line arguments
  // 1st Arg: maximum wait time
  // 2nd Arg: Number of Replications
  // 3rd Arg: end_time: length in minutes of simulated period
  // 4th Arg: Number of Periods
  // 5th Arg: Service Rate (services per HOUR per server) HOUR!!! not minutes!!!
  //  Vector containing number of servers in real life  (n entries)
  //  Vector containing piecewise arrival rate function (n+1 entries)

  //ReadCommandLine(*argv[0]);

  
maxWait atof(pArgs[1]);

  
totalReplications atoi(pArgs[2]);

  
endTime atof(pArgs[3]);

  
totalPeriods atoi(pArgs[4]);

  
periodLength=endTime/totalPeriods;

  
timeToPeriodEnd periodLength;

  
serviceRate atof(pArgs[5])/60.0//convert it into (services/minutes)/server

  
numServers.resize(totalPeriods+1);
  
cout<<"NumServersSize: "<<numServers.size()<<endl;
  for(
int i=0i<totalPeriods;i++){
    
cout<<i+1<<"\t"<<pArgs[i+6]<<endl;
    
numServers[i]=atoi(pArgs[i+6]);
    
cout<<i+1<<"\t"<<numServers[i]<<endl;
    if(
numServers[i]>maxServersmaxServers numServers[i];
  }

  
//resize arrivalRate[] and initialize values
  //assign value to maxArrivalRate
  
arrivalRate.resize(totalPeriods+1);
  for(
int i=0i<totalPeriods+1;i++){
    
arrivalRate[i]=atof(pArgs[i+totalPeriods+6]);
    if(
arrivalRate[i]>maxArrivalRate){maxArrivalRate arrivalRate[i]; }
  }
  
// Resizing statistic counters
  
successCounter.resize(totalPeriods);
  
meanSuccess.resize(totalPeriods);
  
varSuccess.resize(totalPeriods);
  
meanNumCalls.resize(totalPeriods);
  
numCalls.resize(totalPeriods);
  
workRemain.resize(maxServers);
  
T.resize(maxServers);
  
delta.resize(maxServers);
  for(
int i=0i<maxServers;i++){
    
delta[i].resize(totalPeriods);
  }
  
vector<doublezeroVect(totalPeriods,0);

  
meanIPAGrad.resize(totalPeriods);
  
varIPAGrad.resize(totalPeriods);

  for(
int i=0;i<totalPeriods;i++){
        
meanIPAGrad[i]=zeroVect;
        
varIPAGrad[i]=zeroVect;
   }

  
ShowParameters();

  
char duh ;

  
cin>>duh;


  
//***************END of Parameter initialization***************//


  //this is the main simulation loop that loops through all the simulations.

  
for(; currentReplication<=totalReplications;currentReplication++){
   
Simulate();
   
CalculateStats();
  }

  
TraceFile.close();
  
WriteStatsFile(); 
  
Initialize();
  
meanIPAGrad.clear();
  
varIPAGrad.clear();
  
meanNumCalls.clear();
  
varSuccess.clear();
  
meanSuccess.clear();

  
cout<<"DONE"<<endl;
  
cin>>duh;
  return 
1;
//End Main
/******************************************************************************/
void CalculateStats(){
    
//This function updates the current mean and variance of successful services
    //in each period.
    //One pass variance/mean calculation algorithms obtained from
    //http://mathworld.wolfram.com/SampleVarianceComputation.html
    
double OldMean;
    
double OldArrivalMean;
    
//accumulate service level stats
    
for(int l=0;l<totalPeriods;l++){

        if(
currentReplication==1){
           
meanSuccess[l]=successCounter[l];          //used for 1st moment
           
meanNumCalls[l]=numCalls[l];
        }
        else {
           
OldMean meanSuccess[l];

           
OldArrivalMean meanNumCalls[l];


           
meanSuccess[l]=((currentReplication-1)*OldMean+successCounter[l])/(currentReplication); //Sample mean after (repnumber+1)th replication
           
meanNumCalls[l]=((currentReplication-1)*OldArrivalMean+numCalls[l])/(currentReplication); //Sample mean after (repnumber+1)th replication

           
varSuccess[l] = (1.00-(1.00/(currentReplication-1)))*varSuccess[l] + (currentReplication)*pow((meanSuccess[l]-OldMean),2);

        }
    }
}
//End CalculateStats()
/******************************************************************************/


void Simulate(){

  
Event nextEvent;       // type of the next event
  
Initialize();
  
MakeTrace(nextEvent);
  while(
simTime endTime || numCallsInSystem != 0){
    
nextEvent Transition();
    switch(
nextEvent){
      case 
ARRIVAL:
        
Arrival();
        
MakeTrace(nextEvent);
        break;
      case 
COMPLETION:
        
Completion();
        
MakeTrace(nextEvent);
        break;
      case 
PERIODEND:
        
PeriodEnd();
        
MakeTrace(nextEvent);
        break;

      default:
      
cout<<"NO SUCH EVENT!!!!"<<endl;
    }  
//end Switch

  
//End While

  
UpdateIPA();
  
// do the neccessary data collection here....

// End Simulate
/******************************************************************************/

void Initialize(){
  
//Initialize values

  
simTime 0;
  
numCallsTotal 0;
  
numCallsServiced 0;
  
timeToPeriodEnd periodLength;
  
currentPeriod 1;
  
numCallsInSystem 0;
  
timeToNextArrival NHPP(arrivalStreamsimTime);


  for(
int j=0;j<maxServers;j++){
        
workRemain[j] = 0;
        
T[j] = 0;
        for(
int i=0;i<totalPeriods;i++){
             
delta[j][i] = 0;
        }
  }

  
//Initialize Service Level Variables
  
for(int i=0;i<totalPeriods;i++){
       
successCounter[i] = 0;
       
numCalls[i] = 0;
  }

  
//Clear customer queue
  //some new fast way to do this?
  // delete customer objects that Customer* is pointing to.

  
for(list<Customer*>::iterator i =queue.begin() ;i!=queue.end();i++){
    
delete *i;
    *
i=0;
  }

  
delKs.clear();    // clear vector of derivatives
  
xiKs.clear();
  
Ak.clear();
  
queue.clear();    // clear the list of all pointers
  
if(!queue.empty()){
    
cout<<"Queue is not EMPTY!!!"<<endl;
  }

// End Initialize

/******************************************************************************/

Event Transition(){
  
double timeToNextEvent;       //time in minutes from simTime to next event
  
double timeToNextCompletion;  //time to next service completion
  
Event nextEvent;              //type of event to return
  
serverLeastWork 0;      //holds index of busy server with the least work
  
char dummy;

  
//get the index serverLeastWork of the server with the least amount of work
  //among the set of busy servers B, serverLeastWork = 0 if all servers free,
  //we assume that workRemain[j] = 0 indicates that server j is free, this holds
  //with probability 1

  
for(int i=0;i<numServers[currentPeriod-1];i++){
          
//if server i is in B, i is a candidate for serverLeastWork
          
if(workRemain[i] > 0){
                  if(
workRemain[serverLeastWork] == 0) {serverLeastWork i;}
                  else if(
workRemain[i] < workRemain[serverLeastWork]) {serverLeastWork i;}

          }
  }
  
//cout<<"Server with least work: "<<serverLeastWork<<", Remaining Work: "<<workRemain[serverLeastWork]<< endl;
  //cin>>dummy;
  //if all servers are free, set timeToNextCompletion to infinity
  
if(workRemain[serverLeastWork] == 0) {timeToNextCompletion 999999;}

  
//otherwise, set timeToNextCompletion
  
else {timeToNextCompletion workRemain[serverLeastWork];}
  
//cout<<"timeToNextCompletion: "<<timeToNextCompletion<<endl;
  //cout<<"timeToPeriodEnd: "<<timeToPeriodEnd<<endl;
  //cout<<"timeToNextArrival: "<<timeToNextArrival<<endl;

  
if(timeToNextCompletion<=timeToPeriodEnd && timeToNextCompletion<=timeToNextArrival){
    
nextEvent Event(1);
    
//cout<<"Next Event is a Service Completion"<<endl;
    
timeToNextEvent timeToNextCompletion;
    }
  else if(
timeToNextArrival<timeToPeriodEnd && timeToNextArrival<timeToNextCompletion){
    
nextEvent Event(0);
    
//cout<<"Next Event is an Arrival"<<endl;
    
timeToNextEvent timeToNextArrival;
    }
  else{
    
nextEvent Event(2);
    
//cout<<"Next Event is a end of Period"<<endl;
    
timeToNextEvent timeToPeriodEnd;
    }
  
//Update simulation clock
  
simTime += timeToNextEvent;
  
timeToNextArrival -= timeToNextEvent;
  
timeToPeriodEnd -= timeToNextEvent;

  
// Update remaining work in busy servers    Step 1.vi
  // Update delay at busy servers Step 1.vii
  
for(int i=0;i<numServers[currentPeriod-1];i++){
          
//if server i is in B, update remaining work, update the delay
          
if(workRemain[i] > 0){
                  
workRemain[i] -= timeToNextEvent;
                  
delta[i][currentPeriod-1] -= (timeToNextEvent/serviceRate);
          }
  }



  return 
nextEvent;

//End Transition
/******************************************************************************/

void Arrival(){
  
numCalls[currentPeriod-1]++; //increment no. of calls in this period
  
numCallsTotal++; //increment no. of incoming calls
  
Ak.push_back(simTime);
  
timeToNextArrival NHPP(arrivalStreamsimTime)-simTime//update time until next call
  
double newWork Exponential(workStreamserviceRate);
  
bool serverIsAssigned false;
  
//if queue is empty and there are free servers, then there is a server
  //available to answer the call immediately
  
if(numCallsInSystem numServers[currentPeriod-1]){
       
successCounter[currentPeriod-1]++; //this is a successful service
       
int assignedServer 0//index of server assigned to this call

       //make default assignedServer to be the first free server
       
for(int j=0j<numServers[currentPeriod-1];j++){
            if(
workRemain[j]==0){
                
serverIsAssigned true;
                
assignedServer=j;
                break;
            }
        }
       
//assign call to server who has been available for service the longest
       //among all free servers
       
for(int i=assignedServer;i<numServers[currentPeriod-1];i++){
            if(
workRemain[i] == && T[i] <T[assignedServer]) {
            
assignedServer i;
            }
       }
       if(
serverIsAssigned!=true){
            
cout<<"SERVER NOT ASSIGNED. Replication: "<<currentReplication<<", simTime: "<<simTime<<endl;
            
ErrorTrace(TraceFile);
       }
       
numCallsServiced++; //increment no. of calls that have started service
       
workRemain[assignedServer] = newWork;  //assign service time and mark server busy

       //2.b.iv.f: assign value to xiKs = T[assignedServer]
       
xiKs.push_back(T[assignedServer]);
       
//2.b.iv.g: assign values to delKs =delta[assignedServer][]
       
delKs.push_back(delta[assignedServer]);

       
//2.b.iv.h: reset delta[assignedServer][] to 0
       //reset the accumulated delay of assignedServer to zero
       
for(int i=0;i<totalPeriodsi++){
           
delta[assignedServer][i] = 0;
       }
  }

  
//if there are no free servers to answer call immediately, put
  //customer in the queue
  
else {
       
Customer *pNewcust= new Customer(simTimenumCallsTotalnewWorkcurrentPeriod); //create new customer
       
queue.push_back(pNewcust);//add customer to the queue w/id
  
}
  
CheckIPACounters();
  
numCallsInSystem++; //increment no. calls in sys

//End Arrival
/******************************************************************************/

void Completion(){
  
T[serverLeastWork] = simTime//record the time the server became free

  
if(numCallsInSystem numServers[currentPeriod-1]){
        
//there are calls waiting to be answered, answer the next call in queue
        
numCallsServiced++; //increment no. of calls that have started service
        
Customer pNextCust = *(queue.begin());

        if(
simTime pNextCust->attribute <= maxWait) {
             
successCounter[pNextCust->arrivalPeriod-1]++;
        }

        
workRemain[serverLeastWork] = pNextCust->workload;
        
queue.pop_front(); //remove customer from queue
        
delete pNextCust;  // memory management. delete object pointer is
        
pNextCust 0;     // referring to, then reassign pointer to NULL


        //assign T[serverLeastWork] to xiKs
        
xiKs.push_back(T[serverLeastWork]);
        
//assign delKs
        
delKs.push_back(delta[serverLeastWork]);
  }
  
/* deleted in version2 of the IPA algorithm
  else{
       //reset the accumulated delay
       for(int i=0;i<totalPeriods; i++){
           delta[serverLeastWork][i] = 0;
       }
  }
  */
  
CheckIPACounters();
  
numCallsInSystem--;

}  
//End Completion
/******************************************************************************/

void PeriodEnd(){
  
// Case i(more periods remaining)
  
if(currentPeriod totalPeriods) {     // if 1
        
if(traceOnTraceFile<<"\t PeriodEnd-CASEI"<<endl;
       
//There are more periods
       
currentPeriod++;
       
timeToPeriodEnd periodLength;

       if(
numServers[currentPeriod-1] < numServers[currentPeriod-2]){
            if(
traceOn)TraceFile<<"\t PeriodEnd-CASE I- Need to reduce servers"<<endl;
            
PeriodEndTrace();
            
//we need to reduce the number of servers
            //let l be a vector such that l(i) is the index of the server with
            //the ith most remaining work
            //reorder T, delta, and workRemain according to l
            
int index;
            
double temp;
            for(
int i=0;i<maxServers-1;i++ ){
                 
index i;
                 for(
int j=i+1;j<maxServers;j++){
                      if(
workRemain[j]>workRemain[index]) {index j;}
                 }

                 if(
index i){
                      
//swap workRemain values
                      
temp workRemain[index];
                      
workRemain[index] = workRemain[i];
                      
workRemain[i] = temp;

                      
//swap T values
                      
temp T[index];
                      
T[index] = T[i];
                      
T[i] = temp;

                      
//swap delta values for each period
                      
for(int k=0;k<totalPeriods;k++){
                           
temp delta[index][k];
                           
delta[index][k] = delta[i][k];
                           
delta[i][k] = temp;
                      } 
// end for
                 
//end if
            
// end for

            //clean up remaining service
            
for(int r=numServers[currentPeriod-1]+1r<=numServers[currentPeriod-2];r++){
                 
//call extends to next period, effectively one more server
                 
if(workRemain[r-1]>timeToPeriodEnd) {numServers[currentPeriod-1]++;}
                 else if(
workRemain[r-1]>0){
                      
numCallsInSystem--;
                      
workRemain[r-1] = 0;
                 }
            } 
//end for
       
PeriodEndTrace();
       } 
//end if
       
if(numServers[currentPeriod-1] > numServers[currentPeriod-2]){
            if(
traceOn)TraceFile<<"\t PeriodEnd-CASE I- need to increase Servers"<<endl;
            
//we need to increase the number of servers
            
for(int r=numServers[currentPeriod-2]+1r<=numServers[currentPeriod-1];r++){
                 
T[r-1] = simTime;
                 for(
int i=0;i<totalPeriods;i++){
                      
delta[r-1][i] = 0;
                 }
                 
//if a call is waiting to be served
                 
if(traceOn)TraceFile<<"\t r: "<<r<<", NumCallsInSystem: "<<numCallsInSystem<<endl;
                 if(
numCallsInSystem >= r){
                      if(
traceOn)TraceFile<<"Allocating waiting customer to incoming Server"<<endl;
                      
numCallsServiced++; //increment no. calls to start service
                      
Customer pNextCust = *queue.begin();

                      if(
simTime pNextCust->attribute <= maxWait) {
                           
successCounter[pNextCust->arrivalPeriod-1]++;
                      }

                      
workRemain[r-1] = pNextCust->workload;
                      
queue.pop_front(); //remove customer from queue
                      
delete pNextCust;  // deleting Customer object
                      
pNextCust 0;     // assigning pointer to NULL

                      //assign values to xiKs
                      
xiKs.push_back(T[r-1]);
                      
//assign values to delKs
                      
delKs.push_back(delta[r-1]);
                 } 
//end if
            
// end for
       
}  //end of if 3

  
//End 1st If

  //Case ii (end of last period)
  
else if(currentPeriod ==totalPeriods) {
        if(
traceOn)TraceFile<<"\t PeriodEnd-CASE II"<<endl;
       
//we have reached the end of the last period
       
currentPeriod++;
       
timeToPeriodEnd maxWait;
       
numServers[currentPeriod-1] = numServers[currentPeriod-2];
  }
  
//Case iii (time to terminate)
  
else if(currentPeriod>totalPeriods){
       if(
traceOn)TraceFile<<"\t PeriodEnd-CASE III"<<endl;
      
//then we terminate the simulation
      //currentPeriod > totalPeriods implies simTime > endTime
      
Termination();
      
numCallsInSystem 0;  //this will terminate the simulation
  
}

}
//End PeriodEnd
/******************************************************************************/

void Termination(){
    
vector<doubletemp(totalPeriods,0); //create a 1 by p vector of zeros
    
if(!queue.empty()){
        
//queue is not empty which implies that
        //no servers available. Set xiKs=infinity and DelKs=0 for all remaining
        //customers in the queue

        //Update IPA counters for each customer in the queue, and for an imaginary 'next customer'
        
for(int i 0;i<queue.size()+1;i++){
            
xiKs.push_back(99999);
            
delKs.push_back(temp);// add a 1xp zero vector
            
numCallsServiced++;
        }
   }
   else {
        
//assign the IPA counters
        //for the imaginary 'next customer', the (NumCallsTotal+1)th customer
        
bool serverIsAssigned false;
        
int assignedServer 0//index of server assigned to this call
        //if queue is empty and there are free servers, then there is a server
        //available to answer the next call immediately


        //make default assignedServer to be the first free server
        
for(int j=0j<numServers[totalPeriods-1];j++){
            if(
workRemain[j]==0){
                
serverIsAssigned true;
                
assignedServer=j;
                break;
                }
            }
        
//assign call to server who has been available for service the longest
        //among all free servers
        
for(int i=assignedServer;i<numServers[currentPeriod-1];i++){
            if(
workRemain[i] == && T[i] <T[assignedServer]) {
                
assignedServer i;
            }
        }

        if(
serverIsAssigned!=true){
            
//the case when the queue is empty, and all servers are busy
            
xiKs.push_back(99999);
            
delKs.push_back(temp);// add a 1xp zero vector
        
}
        else{
            
//there is a server available to service the next 'imaginary' incoming call
            
xiKs.push_back(T[assignedServer]);
            
delKs.push_back(delta[assignedServer]);
        }
        
numCallsServiced++;
    }
    
CheckIPACounters();
    if(
numCallsServiced!=(numCallsTotal+1)){
        
cout<<"ACCOUNTING ERROR in Termination of replication "<<currentReplication<<endl;
    }
}
// End Termination()
/******************************************************************************/
void UpdateIPA(){
    
//update the mean IPA gradients
    
vector<doublezeroVect(totalPeriods,0);
    
//dJik_dMu is the IPA gradient obtained from this particular replication
    
vectorvector<double> > dJik_dMu(totalPeriods,zeroVect); // this creates a totalPeriods by totalPeriods matrix of zeros
    
double dFdU 0;
    
double A;

    
//Sum up Jik for this replication from k=1 to k=numCallsTotal+1=NumCallsServiced
    
CheckIPACounters();

    for(
int k=1;k<=numCallsServiced;k++){

        for(
int i=1i<=totalPeriods;i++){
            for(
int j 1j<=totalPeriods;j++){

                if(  (
periodLength*(i-1)+maxWait)< xiKs[k-1] && xiKs[k-1]<(periodLength*(i)+maxWait)){
                    if(
k==1){0;}
                    else{ 
Ak[k-2]; }
                    
dJik_dMu[i-1][j-1] += -exp(-Integral(A,xiKs[k-1]-maxWait))* delKs[k-1][j-1];
                }
                else{
                    
//do nothing. this is equivalent to adding zero.
                
}

            }
//end looping through j periods
        
//end looping through i periods
    
}//end looping through each call


    //Update the mean and variance of the IPA gradient with the results
    //of this replication
    //One pass variance/mean calculation algorithms obtained from
    //http://mathworld.wolfram.com/SampleVarianceComputation.html
    
double OldMean;


    for(
int l=0;l<totalPeriods;l++){
        for(
int j=0j<totalPeriods;j++){
            if(
currentReplication==1){
                
meanIPAGrad[l][j]=dJik_dMu[l][j];          //used for 1st moment
            
}
            else {
            
OldMean meanIPAGrad[l][j];
            
meanIPAGrad[l][j]=((currentReplication-1)*OldMean+dJik_dMu[l][j])/(currentReplication); //Sample mean after (repnumber+1)th replication
            
varIPAGrad[l][j] = (1.00-(1.00/(currentReplication-1)))*varIPAGrad[l][j] + (currentReplication)*pow((meanIPAGrad[l][j]-OldMean),2);

            }
        }
//End loop through j periods
    
}//end loop through k periods


}// End UpdateIPA()
/******************************************************************************/
double Integral(double adouble b){
    if (
a>b){
       
double temp b;
       
a;
       
atemp;
    }

    
int periodA=int(ceil(periodLength));
    
int periodB=int(ceil(periodLength));

    
double fA = ((a-(periodA-1)*periodLength)*(arrivalRate[periodA]-arrivalRate[periodA-1])/periodLength)+arrivalRate[periodA-1];
    
double fB = ((b-(periodB-1)*periodLength)*(arrivalRate[periodB]-arrivalRate[periodB-1])/periodLength)+arrivalRate[periodB-1];

    
double area 0;

    if(
periodA == periodB){
        
area 0.5*(b-a)*(fA+fB);
    }
    else{
       
area =  0.5 * ( (periodA*periodLength-a)*(arrivalRate[periodA]+fA)+ (b-(periodB-1)*periodLength)*(arrivalRate[periodB-1]+fB)) ;

       if(
periodB-periodA>1){
          for(
int i periodA+1;i<periodB;i++){
            
area += periodLength*0.5*(arrivalRate[i-1]+arrivalRate[i]);
          } 
//end for
       
}  //end if
    
//end else

   
return area;
}
//end of Integral
/******************************************************************************/
double NHPP(RngStream &generatordouble time){

  
//this function returns the time (from start of simulation) of the next arrival
  //"time" is the current simulation time
  
bool realArrival false;   // has a real arrival been generated from thinning?
  
double nextTime time;  // the next possible arrival time, used in thinning
  
double currentArrivalRate;  // actual arrival rate at nextTime
  
double thinning;            // U(0,maxArrivalRate), for thinning

  //thinning algorithm
  
while(!realArrival){
    
//generate an arrival time, based on maxArrival rate
    
nextTime+= -(1.0/maxArrivalRate)*log(1-generator.RandU01());
    
//TraceFile<<"NHPP-nextTime: "<<nextTime<<endl;
    // generate thinning variable
    
thinning maxArrivalRate*generator.RandU01();

    
// Determine if the thinning variable is less than current arrival rate
    // if so, accept the current nextTime
    
currentArrivalRate RateFunct(nextTime);
    if(
thinning<=currentArrivalRate){
      
realArrival true;
    }
  }

  
// return next arrival time
  
if(nextTime>endTime){
    
nextTime 999999;
  }

  return 
nextTime;
//End NHPP
/******************************************************************************/

// returns the rate function from a piecewise linear rate function at any given time
double RateFunct(double time){
    
int periodA=int(ceil(time periodLength)); //period that 'time' falls into
    
if(periodA>totalPeriods){
        return 
999999;
     }
    
//returns the arrival rate at this particular time
    
return ((time-(periodA-1)*periodLength)*(arrivalRate[periodA]-arrivalRate[periodA-1])/periodLength)+arrivalRate[periodA-1];
}
//End RateFunct
/******************************************************************************/

 //returns an exp(lambda) r.v. using a specified stream
double Exponential(RngStream &generatordouble lambda){
    
double variable;
    
variable = -(1.0/lambda)*log(1-generator.RandU01());
    return 
variable;
}
//End Exponential
/******************************************************************************/

void ShowParameters(){
    
cout<<"Number of Periods: "<<totalPeriods<<endl;
    
cout<<"Number of Replications: "<<totalReplications<<endl;
    
cout<<"ServiceRate(services/min): "<<serviceRate<<endl;
    
cout<<"Length of Period: "<<periodLength<<endl;
    
cout<<"Maximum wait time(minutes): "<<maxWait<<endl;
    
cout<<"Maximum number of Servers: "<<maxServers<<endl;

    
cout<<"Number of Servers in each period:"<<endl;
    for(
int i=0i<totalPeriods;i++){
        
cout<<i+1<<" " <<numServers[i]<<endl;
    }
    
cout<<"Max. Arrival Rate: "<<maxArrivalRate<<endl;
    
cout<<"Arrival Rate at the end of each period:"<<endl;
    for(
int i=0i<totalPeriods+1;i++){
        
cout<<i<<" " <<arrivalRate[i]<<endl;
    }
//End ShowParameters()
/******************************************************************************/
void WriteStatsFile(){
    
fstream StatsFile("Stats.txt",ios::in ios::out |ios::trunc);
    for(
int i 0;i<totalPeriods;i++){
        
StatsFile<<meanSuccess[i]<<endl;
    }
    for(
int i 0;i<totalPeriods;i++){
        
StatsFile<<varSuccess[i]<<endl;
    }
    for(
int i 0;i<totalPeriods;i++){
        
StatsFile<<meanNumCalls[i]<<endl;
    }
    
StatsFile.close();

    
fstream GradFile("Gradient.txt",ios::in ios::out |ios::trunc);
    for(
int i=0;i<totalPeriods;i++){
        for(
int j=0;j<totalPeriods;j++){
            
GradFile<<meanIPAGrad[i][j]<<"\t";
        }
        
GradFile<<endl;
    }
    
GradFile.close();

}
//End WriteStatsFile()
/******************************************************************************/

void MakeTrace(Event event){
    if(
traceOn==false||currentReplication!=2) return;


    if (!
TraceFile.is_open()) { // check for successful opening
       
cout << "Trace.txt file could not be opened!" << endl;
    }
    
TraceFile<<"********************************************************"<<endl;
    
TraceFile<<"\t Next EventType: "<<event<<endl;
    
TraceFile<<"\t Current Replication: "<<currentReplication<<endl;
    
TraceFile<<"\t Current Period: "<<currentPeriod<<endl;
    
TraceFile<<"\t Total Periods: "<<totalPeriods<<endl;
    
TraceFile<<"\t Current Simulation Time: "<<simTime<<endl;
    
TraceFile<<"\t delKs.size()="<<delKs.size()<<endl;
    
TraceFile<<"\t xiKs.size()="<<xiKs.size()<<endl;
    
TraceFile<<"\t Ak.size()="<<Ak.size()<<endl;
    
TraceFile<<"\t Number of Calls in Total: "<<numCallsTotal<<endl;
    
TraceFile<<"\t Number of Calls that have started Service: "<<numCallsServiced<<endl;
    
TraceFile<<"\t Number of Calls in System : "<<numCallsInSystem<<endl;
    
TraceFile<<"\t Number of Servers in this Period: "<<numServers[currentPeriod-1]<<endl;
    
TraceFile<<"\t Number of Customers in the queue: "<<queue.size()<<endl;
    
TraceFile<<"\t Time to end of Period: "<<timeToPeriodEnd<<endl;
    
TraceFile<<"\t Time to next arrival: "<<timeToNextArrival<<endl;
    
TraceFile<<endl;
    
TraceFile<<"\t Work Remaining at each Server: "<<endl;
    for(
int i=0i<maxServers;i++){
        
TraceFile<<"\t "<< i+<<"\t"<< workRemain[i]<<endl;
    }
    
TraceFile<<endl;
    
TraceFile<<"\t Time server became free:"<<endl;
    for(
int i =0i<maxServers;i++){
        
TraceFile<<"\t " <<i+1<<"\t"<<T[i]<<endl;
    }
}
//End MakeTrace()
/******************************************************************************/
void PeriodEndTrace(){
    if(
traceOn==false||currentReplication!=2) return;

    if (!
TraceFile.is_open()) { // check for successful opening
       
cout << "Trace.txt file could not be opened!" << endl;
    }
    
TraceFile<<"*******Tracing Vector ReOrdering***********"<<endl;
    for(
int i=0i<maxServers;i++){
        
TraceFile<<"\t "<< i+<<"\t"<< workRemain[i]<<"\t"<<T[i]<<endl;
    }
    for(
int i=0;i<maxServers;i++){
        
TraceFile<<"\t "<< i+;
        for(
int j=0;j<totalPeriods;j++){
            
TraceFile<<"\t "<<delta[i][j];
        }
        
TraceFile<<endl;
    }

//End PeriodEndTrace()
/*******************************************************************************/
void ErrorTrace(fstream &DataFile){
    if (!
TraceFile.is_open()) { // check for successful opening
       
cout << "ErrorTrace file could not be opened!" << endl;
       return;
    }

    
DataFile<<"****************ERROR TRACE START************************"<<endl;

    
DataFile<<"\t Current Replication: "<<currentReplication<<endl;
    
DataFile<<"\t Current Period: "<<currentPeriod<<endl;
    
DataFile<<"\t Total Periods: "<<totalPeriods<<endl;
    
DataFile<<"\t Current Simulation Time: "<<simTime<<endl;
    
DataFile<<"\t Number of Calls in Total: "<<numCallsTotal<<endl;
    
DataFile<<"\t Number of Calls that have started Service: "<<numCallsServiced<<endl;
    
DataFile<<"\t Number of Calls in System : "<<numCallsInSystem<<endl;
    
DataFile<<"\t Number of Servers in this Period: "<<numServers[currentPeriod-1]<<endl;
    
DataFile<<"\t Number of Customers in the queue: "<<queue.size()<<endl;
    
DataFile<<"\t Time to end of Period: "<<timeToPeriodEnd<<endl;
    
DataFile<<"\t Time to next arrival: "<<timeToNextArrival<<endl;
    
DataFile<<endl;
    
DataFile<<"\t Work Remaining at each Server: "<<endl;
    for(
int i=0i<maxServers;i++){
        
DataFile<<"\t "<< i+<<"\t"<< workRemain[i]<<endl;
    }
    
DataFile<<endl;
    
DataFile<<"\t Time server became free:"<<endl;
    for(
int i =0i<maxServers;i++){
        
DataFile<<"\t " <<i+1<<"\t"<<T[i]<<endl;
    }
    
DataFile<<"****************ERROR TRACE END**************************"<<endl;
}
//End ErrorTrace()
/******************************************************************************/ 

Last edited by cheerios; 12-16-2003 at 10:23 PM..
dimbulb is offline  
Old 12-15-2003, 06:15 PM   #12 (permalink)
Riiiiight........
 
PHP Code:
void CheckIPACounters(){
    if(
delKs.size()!=numCallsServiced||xiKs.size()!=numCallsServiced||Ak.size()!=numCallsTotal){
        
cout<<"Error in number of IPA counters!!! Replication: "<<currentReplication<<", simTime: "<<simTime<<endl;
        
cout<<"delKs.size()="<<delKs.size()<<endl;
        
cout<<"xiKs.size()="<<xiKs.size()<<endl;
        
cout<<"Ak.size()="<<Ak.size()<<endl;
        
cout<<"numCallsServiced="<<numCallsServiced<<endl;
        
cout<<"numCallsTotal="<<numCallsTotal<<endl;
        
char a;
        
cin>>a;
    }


Last edited by cheerios; 12-16-2003 at 10:24 PM..
dimbulb is offline  
Old 12-15-2003, 06:16 PM   #13 (permalink)
Riiiiight........
 
for some reason the code tags don't like the things i put between < >.

sorry for using so many global variables. I know I should have encapsulated them a whole lot more, and written "safer" code, but we were in a big hurry....
so if anyone gets irritated reading the code, heh.. apologies in advance...

Last edited by dimbulb; 12-15-2003 at 06:20 PM..
dimbulb is offline  
Old 12-15-2003, 10:54 PM   #14 (permalink)
Junkie
 
Location: North Hollywood
the code didn't survive the post, a lot of it is removed, and you have to dig out of the html source. eg see the if statements
charliex is offline  
Old 12-15-2003, 11:04 PM   #15 (permalink)
kel
WARNING: FLAMMABLE
 
Location: Ask Acetylene
Ay caramba, it's bigger then I thought!
Okay, have you tried it out in the debugger? I wouldn't be able to spot the problem in something this big that uses libraries I can't see (ie I don't know the function headers).

Off the cuff your main should return 0. If a function in c/c++ returns an integer to indicate success then it should be zero. A non-zero integer is usually used to mean failure. That isn't the issue though.

What type of crash do you get? The exact error message? And can you post the full code somewhere so I can copy/paste and run it? What is the output you get? We still don't have enough info to easily spot it.
__________________
"It better be funny"
kel is offline  
Old 12-16-2003, 09:42 PM   #16 (permalink)
MSD
The sky calls to us ...
 
MSD's Avatar
 
Super Moderator
Location: CT
I would personally take the easy way out and just use

getch();
return 0;

The code didn't survive the copy/paste, and I don't have all the header files you included
MSD is offline  
Old 12-16-2003, 10:25 PM   #17 (permalink)
Banned
 
Location: 'bout 2 feet from my iMac
turned your code tags to php tags so that hte <>'s didn't eat stuff off to look!
cheerios is offline  
Old 12-16-2003, 10:42 PM   #18 (permalink)
Banned
 
Location: 'bout 2 feet from my iMac
ummm... you're returning 1 in main. 1 is an error. return 0 means all's well. that may very well be your issue.
cheerios is offline  
Old 12-16-2003, 11:36 PM   #19 (permalink)
Junkie
 
Location: North Hollywood
naw returning 1 from main in vc just means set dos ERRNO to 1
nothing else, good call on the php tag though cheerios, except those colours IM BLIND!!!
charliex is offline  
Old 12-16-2003, 11:49 PM   #20 (permalink)
Junkie
 
Location: North Hollywood
theres a couple of small things i see so far, not likely to crash though,

in Simulate() it says
PHP Code:
  Event nextEvent;       // type of the next event
  
Initialize();
  
MakeTrace(nextEvent); 
nextEvent is not initialized before use, depending on which mode (and which compiler) you compile it, will depend on the contents of that variable, since its a stack and not a global. (non initialized globals are always guaranteed to be 0, local/stack are not)

also it should be fstream not fstream.h, you might be getting away with that on vc7/net i'm guessing.

need customer .h too and customer.cpp if there is one.
charliex is offline  
Old 12-17-2003, 12:20 AM   #21 (permalink)
kel
WARNING: FLAMMABLE
 
Location: Ask Acetylene
Source code please, with all the extra custom libraries your using.
This can probably be solved in 5 minutes in the debugger.
__________________
"It better be funny"
kel is offline  
Old 12-17-2003, 10:01 AM   #22 (permalink)
Insane
 
Location: West Virginia
since you are using namespace std, you can use the following to easily take care of getting keypresses from the user:

system("pause");

It will automatically put in the text notifying the user a keypress is needed also.

As for the question you're asking - I dont see anything wrong so far except for the return 1 =/ Good Luck though
__________________

- Artsemis
~~~~~~~~~~~~~~~~~~~~
There are two keys to being the best:
1.) Never tell everything you know
Artsemis is offline  
Old 12-17-2003, 01:37 PM   #23 (permalink)
Riiiiight........
 
Thanks everyone. Does anyone have hosting? if not i'll just zip it up and email it to anyone who supplies me with their email.

Small problem. I inherited this program from someone else, though i basically made huuuge changes to it, and it compiles in this little compiler he passed to me as well, called Dev-C++, i think it runs off Gnu or whatever...( as you can see.. i'm a dummy at this... sigh..... i should have done this in Java or Matlab.....)

It doesn't compile in Microsoft Visual C++, it gives errors on the iostream stuff, even though i'm not sure why....

Thing is that this program works on a P2 400, on Windows NT.

It crashes when totalPeriods is set to more than 20 on machines running windows2000 or windowsXP. WHY TWENTY!!???@@!!!

well.. its the last day i'll be working on it. I'll be officially handing it over tommorrow, though i will probably try to find errors in the code.

charliex and kel and whoever, I'd appreciate it if you'd PM me your email addresses......

or if someone would host for me... =)
dimbulb is offline  
Old 12-17-2003, 01:40 PM   #24 (permalink)
Riiiiight........
 
PHP Code:
#ifndef CUSTOMER_H
#define CUSTOMER_H
//---------------------------------------------
//File:Customer Class Definition
//Models a generic customer for queing networks
//---------------------------------------------

class Customer {

      public:
             
//Constructor for Customer, initializes its ID#
             
Customer();
             
Customer(double newAttrint newIDdouble newWork,int newArrivalP);
             
int GetArrivalPeriod(double periodLength);
             
//attribute--can be used to store any value
             
double attribute;

            
//ID number for this object
            
int ID;
            
            
//workload for customer, assigned on arrival
            
double workload;
            
int arrivalPeriod//period that customer arrives in

};

//-------MEMBER FUNCTIONS--------------------------------------------

///Constructor
Customer::Customer()
{

        
attribute=0;  //set to 0 for now
        
ID=-1//give this Customer a dummy ID
        
workload 0;   //set to 0 for now
}
Customer::Customer(double newAttrint newIDdouble newWorkint newArrivalP){
    
attribute newAttr;
    
ID newID;
    
workload newWork;
    
arrivalPeriod newArrivalP;
}

int Customer::GetArrivalPeriod(double periodLength){
    
int arrivPeriod;   //arrival period of customer entering service
    
arrivPeriod int(ceil(attribute periodLength));
    return 
arrivPeriod;
}

//-------End of Customer Class-----------------------------------------

#endif 
dimbulb is offline  
Old 12-17-2003, 01:43 PM   #25 (permalink)
Riiiiight........
 
PHP Code:
#ifndef RNG_H
#define RNG_H

/***********************************************************************\
*
* File: RngStream.cpp for multiple streams of Random Numbers
* Language: C++
* Copyright: Pierre L’Ecuyer, University of Montreal
* Notice: This code can be used freely for personnal, academic,
* or non-commercial purposes. For commercial purposes,
* please contact P. L’Ecuyer at: [email]lecuyer@iro.umontreal.ca[/email]
* Date: 14 August 2001
*
\***********************************************************************/
#include <cstdlib>
#include <iostream>
#include "RngStream.h"
using namespace std;
namespace
{
const 
double m1 4294967087.0;
const 
double m2 4294944443.0;
const 
double norm 1.0 / (m1 1.0);
const 
double a12 1403580.0;
const 
double a13n 810728.0;
const 
double a21 527612.0;
const 
double a23n 1370589.0;
const 
double two17 131072.0;
const 
double two53 9007199254740992.0;
const 
double fact 5.9604644775390625e-8/* 1 / 2^24 */
// The following are the transition matrices of the two MRG components
// (in matrix form), raised to the powers -1, 1, 2^76, and 2^127, resp.
const double InvA1[3][3] = { // Inverse of A1p0
184888585.00.01945170933.0 },
1.00.00.0 },
0.01.00.0 }
};
const 
double InvA2[3][3] = { // Inverse of A2p0
0.0360363334.04225571728.0 },
1.00.00.0 },
0.01.00.0 }
};

const 
double A1p0[3][3] = {
0.01.00.0 },
0.00.01.0 },
{ -
810728.01403580.00.0 }
};
const 
double A2p0[3][3] = {
0.01.00.0 },
0.00.01.0 },
{ -
1370589.00.0527612.0 }
};
const 
double A1p76[3][3] = {
82758667.01871391091.04127413238.0 },
3672831523.069195019.01871391091.0 },
3672091415.03528743235.069195019.0 }
};
const 
double A2p76[3][3] = {
1511326704.03759209742.01610795712.0 },
4292754251.01511326704.03889917532.0 },
3859662829.04292754251.03708466080.0 }
};
const 
double A1p127[3][3] = {
2427906178.03580155704.0949770784.0 },
226153695.01230515664.03580155704.0 },
1988835001.0986791581.01230515664.0 }
};
const 
double A2p127[3][3] = {
1464411153.0277697599.01610723613.0 },
32183930.01464411153.01022607788.0 },
2824425944.032183930.02093834863.0 }
};
//-------------------------------------------------------------------------
// Return (a*s + c) MOD m; a, s, c and m must be < 2^35
//
double MultModM (double adouble sdouble cdouble m)
{
double v;
long a1;
=*+c;


if (
>= two53 || <= -two53) {
a1 static_cast<long> (two17); -= a1 two17;
a1 *s;
a1 static_cast<long> (m); -= a1 m;
two17 +*+c;
}
a1 static_cast<long> (m);
/* in case v < 0)*/
if ((-= a1 m) < 0.0) return += m; else return v;
}
//-------------------------------------------------------------------------
// Compute the vector v = A*s MOD m. Assume that -m < s[i] < m.
// Works also when v = s.
//
void MatVecModM (const double A[3][3], const double s[3], double v[3],
double m)
{
int i;
double x[3]; // Necessary if v =s
for (=0;<3; ++i) {
x[i] = MultModM (A[i][0], s[0], 0.0m);
x[i] = MultModM (A[i][1], s[1], x[i], m);
x[i] = MultModM (A[i][2], s[2], x[i], m);
}
for (
=0;<3; ++i)
v[i] = x[i];
}
//-------------------------------------------------------------------------
// Compute the matrix C = A*B MOD m. Assume that -m < s[i] < m.
// Note: works also if A =C or B =C or A =B =C.
//
void MatMatModM (const double A[3][3], const double B[3][3],
double C[3][3], double m)
{
int ij;
double V[3], W[3][3];
for (
=0;<3; ++i) {
for (
=0;<3; ++j)
V[j] = B[j][i];
MatVecModM (AVVm);
for (
=0;<3; ++j)

W[j][i] = V[j];
}
for (
=0;<3; ++i)
for (
=0;<3; ++j)
C[i][j] = W[i][j];
}
//-------------------------------------------------------------------------
// Compute the matrix B = (A^(2^e) Mod m); works also if A =B.
//
void MatTwoPowModM (const double A[3][3], double B[3][3], double mlong e)
{
int ij;
/* initialize: B =A */
if (!= B) {
for (
=0;<3; ++i)
for (
=0;<3; ++j)
B[i][j] = A[i][j];
}
/* Compute B = A^(2^e) mod m */
for (0ei++)
MatMatModM (BBBm);
}
//-------------------------------------------------------------------------
// Compute the matrix B = (A^n Mod m); works even if A =B.
//
void MatPowModM (const double A[3][3], double B[3][3], double mlong n)
{
int ij;
double W[3][3];
/* initialize: W = A; B = I */
for (=0;<3; ++i)
for (
=0;<3; ++j) {
W[i][j] = A[i][j];
B[i][j] = 0.0;
}
for (
=0;<3; ++j)
B[j][j] = 1.0;
/* Compute B = A^n mod m using the binary decomposition of n */
while (0) {
if (
2MatMatModM (WBBm);
MatMatModM (WWWm);

/=2;
}
}
//-------------------------------------------------------------------------
// Check that the seeds are legitimate values. Returns 0 if legal seeds,
// -1 otherwise.
//
int CheckSeed (const unsigned long seed[6])
{
int i;
for (
=0;<3; ++i) {
if (
seed[i] >= m1) {
cerr << "****************************************\n\n"
<< "ERROR: Seed[" << << "] >= 4294967087, Seed is not set."
<< "\n\n****************************************\n\n";
return (-
1);
}
}
for (
=3;<6; ++i) {
if (
seed[i] >= m2) {
cerr << "*****************************************\n\n"
<< "ERROR: Seed[" << << "] >= 4294944443, Seed is not set."
<< "\n\n*****************************************\n\n";
return (-
1);
}
}
if (
seed[0] == && seed[1] == && seed[2] == 0) {
cerr << "****************************\n\n"
<< "ERROR: First 3 seeds = 0.\n\n"
<< "****************************\n\n";
return (-
1);
}
if (
seed[3] == && seed[4] == && seed[5] == 0) {
cerr << "****************************\n\n"
<< "ERROR: Last 3 seeds = 0.\n\n"
<< "****************************\n\n";
return (-
1);
}
return 
0;
}
// end of anonymous namespace


//-------------------------------------------------------------------------
// Generate the next random number.
//
double RngStream::U01 ()
{
long k;
double p1p2u;
/* Component 1 */
p1 a12 Cg[1] - a13n Cg[0];
static_cast<long> (p1 m1);
p1 -= m1;
if (
p1 0.0p1 += m1;
Cg[0] = Cg[1]; Cg[1] = Cg[2]; Cg[2] = p1;
/* Component 2 */
p2 a21 Cg[5] - a23n Cg[3];
static_cast<long> (p2 m2);
p2 -= m2;
if (
p2 0.0p2 += m2;
Cg[3] = Cg[4]; Cg[4] = Cg[5]; Cg[5] = p2;
/* Combination */
= ((p1 p2) ? (p1 p2) * norm : (p1 p2 m1) * norm);
return (
anti == false) ?:(-u);
}
//-------------------------------------------------------------------------
// Generate the next random number with extended (53 bits) precision.
//
double RngStream::U01d ()
{
double u;
U01();
if (
anti) {
// Don’t forget that U01() returns 1 -u in the antithetic case
+= (U01() - 1.0) * fact;
return (
0.0) ?+1.0 :u;
} else {
+= U01() * fact;
return (
1.0) ?:(1.0);
}
}
//*************************************************************************

// Public members of the class start here
//-------------------------------------------------------------------------
// The default seed of the package; will be the seed of the first
// declared RngStream, unless SetPackageSeed is called.
//
double RngStream::nextSeed[6] =
{
12345.012345.012345.012345.012345.012345.0
};
//-------------------------------------------------------------------------
// constructor
//
RngStream::RngStream (const char *s) : name (s)
{
anti false;
incPrec false;
/* Information on a stream. The arrays {Cg, Bg, Ig} contain the current
state of the stream, the starting state of the current SubStream, and the
starting state of the stream. This stream generates antithetic variates
if anti = true. It also generates numbers with extended precision (53
bits if machine follows IEEE 754 standard) if incPrec = true. nextSeed
will be the seed of the next declared RngStream. */
for (int i 06; ++i) {
Bg[i] = Cg[i] = Ig[i] = nextSeed[i];
}
MatVecModM (A1p127nextSeednextSeedm1);
MatVecModM (A2p127, &nextSeed[3], &nextSeed[3], m2);
}
//-------------------------------------------------------------------------
// Reset Stream to beginning of Stream.
//
void RngStream::ResetStartStream ()
{
for (
int i 06; ++i)
Cg[i] = Bg[i] = Ig[i];
}
//-------------------------------------------------------------------------


// Reset Stream to beginning of SubStream.
//
void RngStream::ResetStartSubstream ()
{
for (
int i 06; ++i)
Cg[i] = Bg[i];
}
//-------------------------------------------------------------------------
// Reset Stream to NextSubStream.
//
void RngStream::ResetNextSubstream ()
{
MatVecModM(A1p76BgBgm1);
MatVecModM(A2p76, &Bg[3], &Bg[3], m2);
for (
int i 06; ++i)
Cg[i] = Bg[i];
}
//-------------------------------------------------------------------------
void RngStream::SetPackageSeed (const unsigned long seed[6])
{
if (
CheckSeed (seed)) exit (EXIT_FAILURE);
for (
int i 06; ++i)
nextSeed[i] = seed[i];
}
//-------------------------------------------------------------------------
void RngStream::SetSeed (const unsigned long seed[6])
{
if (
CheckSeed (seed)) exit (EXIT_FAILURE);
for (
int i 06; ++i)
Cg[i] = Bg[i] = Ig[i] = seed[i];
}
//-------------------------------------------------------------------------
// if e > 0, let n = 2^e + c;
// if e < 0, let n = -2^(-e) + c;
// if e = 0, let n = c.
// Jump n steps forward if n >0, backwards if n <0.
//
void RngStream::AdvanceState (long elong c)
{
double B1[3][3], C1[3][3], B2[3][3], C2[3][3];

if (
0) {
MatTwoPowModM (A1p0B1m1e);
MatTwoPowModM (A2p0B2m2e);
} else if (
0) {
MatTwoPowModM (InvA1B1m1, -e);
MatTwoPowModM (InvA2B2m2, -e);
}
if (
>= 0) {
MatPowModM (A1p0C1m1c);
MatPowModM (A2p0C2m2c);
} else {
MatPowModM (InvA1C1m1, -c);
MatPowModM (InvA2C2m2, -c);
}
if (
e) {
MatMatModM (B1C1C1m1);
MatMatModM (B2C2C2m2);
}
MatVecModM (C1CgCgm1);
MatVecModM (C2, &Cg[3], &Cg[3], m2);
}
//-------------------------------------------------------------------------
void RngStream::GetState (unsigned long seed[6]) const
{
for (
int i 06; ++i)
seed[i] = static_cast<unsigned long> (Cg[i]);
}
//-------------------------------------------------------------------------
void RngStream::WriteState () const
{
cout << "The current state of the Rngstream";
if (
name.size() > 0)
cout <<""<< name;
cout << ":\n Cg ={";
for (
int i 0;<5i++) {
cout << static_cast<unsigned long> (Cg [i]) << ", ";
}
cout << static_cast<unsigned long> (Cg [5]) << " }\n\n";
}

//-------------------------------------------------------------------------
void RngStream::WriteStateFull () const
{
int i;
cout << "The RngStream";
if (
name.size() > 0)
cout <<""<< name;
cout << ":\n anti = " << (anti "true" "false") << "\n";
cout << " incPrec = " << (incPrec "true" "false") << "\n";
cout << " Ig = { ";
for (
=0;<5i++) {
cout << static_cast<unsigned long> (Ig [i]) << ", ";
}
cout << static_cast<unsigned long> (Ig [5]) << " }\n";
cout << " Bg = { ";
for (
=0;<5i++) {
cout << static_cast<unsigned long> (Bg [i]) << ", ";
}
cout << static_cast<unsigned long> (Bg [5]) << " }\n";
cout << " Cg = { ";
for (
=0;<5i++) {
cout << static_cast<unsigned long> (Cg [i]) << ", ";
}
cout << static_cast<unsigned long> (Cg [5]) << " }\n\n";
}
//-------------------------------------------------------------------------
void RngStream::IncreasedPrecis (bool incp)
{
incPrec incp;
}
//-------------------------------------------------------------------------
void RngStream::SetAntithetic (bool a)
{
anti a;
}
//-------------------------------------------------------------------------
// Generate the next random number.
//

double RngStream::RandU01 ()
{
if (
incPrec)
return 
U01d();
else
return 
U01();
}
//-------------------------------------------------------------------------
// Generate the next random integer.
//
long RngStream::RandInt (long lowlong high)
{
return 
low static_cast<long> ((high low 1) * RandU01 ());
};

//--End of Class Implementation-------------------------------

#endif 
dimbulb is offline  
Old 12-17-2003, 01:44 PM   #26 (permalink)
Riiiiight........
 
PHP Code:
#ifndef RNGSTREAM_H
#define RNGSTREAM_H
#include <string>
class RngStream
{
public:
RngStream (const char *name "");

static 
void SetPackageSeed (const unsigned long seed[6]);

void ResetStartStream ();

void ResetStartSubstream ();


void ResetNextSubstream ();

void SetAntithetic (bool a);

void IncreasedPrecis (bool incp);
/*After calling this method with incp = true, each call to the generator (direct or indirect)
for this stream will return a uniform random number with more bits of resolution (53 bits if
machine follows IEEE 754 standard) instead of 32 bits, and will advance the state of the stream
by 2 steps instead of 1. More precisely, if s is a stream of the class RngStream, in the non-antithetic
case, the instruction “u = s.RandU01()” will be equivalent to “u = (s.RandU01()
+ s.RandU01() * fact) % 1.0” where the constant fact is equal to 2Š 24 . This also applies
when calling RandU01 indirectly (e.g., via RandInt, etc.). By default, or if this method is called
again with incp = false, each call to RandU01 for this stream advances the state by 1 step
and returns a number with 32 bits of resolution.*/

void SetSeed (const unsigned long seed[6]);
/*Sets the initial seed Ig of the stream to the vector seed. The vector seed should contain valid
seed values as described in SetPackageSeed. The state of the stream is then reset to this initial
seed. The states and seeds of the other streams are not modified. As a result, after calling this
method, the initial seeds of the streams are no longer spaced Z values apart. We discourage
the use of this method; proper use of the Reset* methods is preferable.*/

void AdvanceState (long elong c);
/*Advances the state by n steps (see below for the meaning of n), without modifying the states
of other streams or the values of Bg and Ig in the current object. If e > 0, then n =2 e + c;if
e < 0, then n = Š 2Š e +c;and if e = 0, then n = c.Note: c is allowed to take negative values.
We discourage the use of this method.*/

void GetState (unsigned long seed[6]) const;
//Returns in seed[0..5] the current state Cg of this stream. This is convenient if we want to
//save the state for subsequent use.

void WriteState () const;
//Writes (to standard output) the current state Cg of this stream.

void WriteStateFull () const;
//Writes (to standard output) the value of all the internal variables of this stream: name, anti,
//incPrec, Ig, Bg, Cg.

double RandU01 ();
/*Normally, returns a (pseudo)random number from the uniform distribution over the interval
(0, 1), after advancing the state by one step. The returned number has 32 bits of precision in
the sense that it is always a multiple of 1/(2 32
Š 208). However, if IncreasedPrecis(true) has
been called for this stream, the state is advanced by two steps and the returned number has 53
bits of precision.*/

long RandInt (long ilong j);
//Returns a (pseudo)random number from the discrete uniform distribution over the integers
//{ i, i +1,...,j } . Makes one call to RandU01.
private:

double Cg[6], Bg[6], Ig[6];
//Vectors to store the current seed, the beginning of the current block (substream) and the
//beginning of the current stream.

bool antiincPrec;
//Variables to indicate whether to generate antithetic or increased precision random numbers.

std::string name;
//String to store the optional name of the current RngStream object.

static double nextSeed[6];
//Static vector to store the beginning state of the next RngStream to be created (instantiated).

double U01 ();
//The backbone uniform random number generator.

double U01d ();
//The backbone uniform random number generator with increased precision.
};

#endif 
dimbulb is offline  
Old 12-17-2003, 01:47 PM   #27 (permalink)
Riiiiight........
 
basically the RNG and the RNGStream files are really sophisticated state of the art random number generators. The C++ ones arn't all that good..

one more question, how do you debug programs that require command line arguments??

thanks for all your patience!!
dimbulb is offline  
Old 12-17-2003, 02:34 PM   #28 (permalink)
Junkie
 
Location: North Hollywood
dimbulb, did you see my notes ? that'll allow you to at least compile what you have on visual c, the only other changes you'd have to make for compatibility is not doing

PHP Code:
{
for(
int i;i<0;i++) {}
for(
int i;i<0;i++) {}
etc..
}
instead use
{
int i;
for(
i;i<0;i++) {}
for(
i;i<0;i++) {}
etc..

which is the best approach or is the correct way of scoping, is academic since VC doesn't support the former.

if you are using gcc to compile gdb is the debugger.


also remember to turn off smiles when posting

also add the comamnd line you use to test, since its quite long apparently

yep its either freeing memory that was never allocated, corrpted or freed twice.

Last edited by charliex; 12-17-2003 at 02:55 PM..
charliex is offline  
Old 12-17-2003, 03:08 PM   #29 (permalink)
Riiiiight........
 
Here's the command line arguments....

C:\Fall2003Henderson\WorkFolder\IpaVar5.exe 1.5 100 1440 24 4 11 20 15 15 26 20 22 22 23 27 27 27 27 27 33 34 51 38 43 43 32 38 30 29 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.3 1.3 1.3 1.3 1.45 1.6 1.75 1.9 2.05 2.05 2.05 2.05 2.05 1.95 1.85 1.75 1.65
dimbulb is offline  
Old 12-17-2003, 03:37 PM   #30 (permalink)
Junkie
 
Location: North Hollywood
where to start

PHP Code:
  for(i=0;i<numServers[currentPeriod-1];i++){
          
//if server i is in B, update remaining work, update the delay
          
if(workRemain[i] > 0){
                  
workRemain[i] -= timeToNextEvent;
                  
delta[i][currentPeriod-1] -= (timeToNextEvent/serviceRate);
          }
  } 
the delta[i][] = is the prime suspect so far, check your code to make sure that you have the space you think you do for the stored data.



PHP Code:
  delta.resize(maxServers);
  for(
i=0i<maxServers;i++){
    
delta[i].resize(totalPeriods);
  } 
I can't decide if just VCs vector class trying to be clever, but in here lies a dangling pointer, since its just a resize its probably ok though.
charliex is offline  
Old 12-17-2003, 03:53 PM   #31 (permalink)
Riiiiight........
 
Quote:
Originally posted by charliex
where to start


PHP Code:
  delta.resize(maxServers);
  for(
i=0i<maxServers;i++){
    
delta[i].resize(totalPeriods);
  } 
I can't decide if just VCs vector class trying to be clever, but in here lies a dangling pointer, since its just a resize its probably ok though.
I'm not sure what you mean by a dangling pointer. This whole thing is just a vector of doubles right. no pointers anywhere??
dimbulb is offline  
Old 12-17-2003, 05:33 PM   #32 (permalink)
Riiiiight........
 
In DisAssembly

77FCCA36 mov dword ptr [ecx],eax

In Call Stack

NTDLL! 77fcca36()
dimbulb is offline  
Old 12-17-2003, 05:42 PM   #33 (permalink)
I am Winter Born
 
Pragma's Avatar
 
Location: Alexandria, VA
Quote:
Originally posted by charliex

which is the best approach or is the correct way of scoping, is academic since VC doesn't support the former.
Actually, VC (or at least VC 6 and VC.NET) support the:
Quote:
for( int i = 0; i < foo; i++ ) {
style of variable declarations. I've never run into trouble with either compiler, or any other compiler I've used (g++ and several oddball UNIX compilers).

The only instance of trouble I'd see is if you were running it through a C instead of C++ compiler - but then you'd get a lot more issues.
Pragma is offline  
Old 12-17-2003, 10:14 PM   #34 (permalink)
Junkie
 
Location: North Hollywood
Quote:
I'm not sure what you mean by a dangling pointer. This whole thing is just a vector of doubles right. no pointers anywhere??
internally in the vector class, since its resizing the array, it seems to cheat and free the ptr,use it then, reallocate it, which is what a dangling pointer is, like i said i think its VC at fault there.

Quote:
Actually, VC (or at least VC 6 and VC.NET) support the:

for( int i = 0; i < foo; i++ ) {
}
VC 6 doesn't support that. or at least in the way i mentioned

Quote:
for( int i = 0; i < foo; i++ ) {
}
for( int i = 0; i < foo; i++ ) {
}
charliex is offline  
Old 12-19-2003, 12:01 PM   #35 (permalink)
kel
WARNING: FLAMMABLE
 
Location: Ask Acetylene
Threw it in the debugger blasted Borland... can't figure out how to make it go show me what line the crash occured on. I also for some reason can't get the addresses in the debugger of all the STL classes having their objects destroyed. That is where the bug is. Did you access internal data of an STL object?

Maybe the issue is with the vectors of vectors?

I will have to move this to my laptop where I have a familiar debugger.
__________________
"It better be funny"

Last edited by kel; 12-19-2003 at 12:19 PM..
kel is offline  
 

Tags
crashes, executes, line, main

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -8. The time now is 03:47 PM.

Tilted Forum Project

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360