Advertisement
Guest User

Untitled

a guest
Nov 24th, 2015
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. //random2.cpp (N.Thomas 2012)
  2. //Simple random-number generator based on Numerical Recipes 'ranqd2'
  3. //Constructs a histogram for distribution of pseudorandom numbers between 0 and 1
  4.  
  5. #include <iostream> //Header for C++ output stream 'cout'
  6. #include <conio.h> //Header for console I/O _getch()
  7. #include <ctime> //Header for time functions
  8. using namespace std;
  9.  
  10. int main(void)
  11. {
  12. const unsigned IM=1664525; //Integer constant for RNG algorithm
  13. const unsigned IC=1013904223; //Integer constant for RNG algorithm
  14. const double zscale=1.0/0xFFFFFFFF; //Scaling factor for random double between 0 and 1
  15. unsigned iran=9999; //Seeds the random-number generator
  16. double z; //Holds random double between 0 and 1
  17. const int nbin=201; //Number of bins in histogram
  18. const int nsteps=nbin*1000000; //Number of steps
  19. int hist[201]; //Array for histogram
  20.  
  21. clock_t start,end; //Variables for timing the program
  22.  
  23. //Uncomment the following line to use a random seed:
  24. //iran=time(0); //Seeds the RNG from the system time
  25.  
  26. //Initialize the histogram:
  27. for(int i=0;i<nbin;i++)hist[i]=0;
  28.  
  29.  
  30. //////THE IS THE BIT WHERE THE MAGIC HAPPEN
  31. //create an array of ONE MILLION things
  32. start=clock(); //Records the start time
  33. for(int j = 1; j <= 1000000; j++)
  34. {
  35. //do a walk
  36. int x = 0;
  37. for (int i = 1; i <= 100; i++)
  38. {
  39. if (zscale*double(iran = IM*iran + IC) < 0.5) x++;//step forward
  40. else x--;//step back
  41. }
  42. hist[x + 100]++;
  43. }
  44. end=clock(); //Records the finish time
  45. //////I think we must expect great things from you, Mr Potter
  46.  
  47.  
  48. //Write to the console using cout:
  49. cout<<"Seed = "<<iran<<endl; //Prints the RNG seed
  50. cout<<"Calculating the histogram for "<<nbin<< " million random numbers..."<<endl;
  51.  
  52. //start=clock(); //Records the start time
  53. ////Construct the histogram:
  54. //for(int i=1;i<=nsteps;i++)hist[int(nbin*zscale*double(iran=IM*iran+IC))]++;
  55. //end=clock(); //Records the finish time
  56.  
  57. //Print the histogram on the screen:
  58. cout<<"bin\tcount"<<endl;
  59. for(int i=-100;i<nbin-100;i++)cout<<i<<"\t"<<hist[i+100]<<endl;
  60.  
  61. cout<<"Time taken = "<<(end-start)/double(CLOCKS_PER_SEC)<<" seconds\n"; //Prints the time taken
  62.  
  63. cout<<"Press any key to exit...";
  64. _getch(); //Wait for a key to be pressed
  65.  
  66. return 1;
  67. } //End of main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement