Random Number Generation with Well44497a in C++ - c++

Sorry to bother again, but as I am new C++ I am having a lot of weird and silly problems.
I am programing a MCMC method. I read in this forum that the WELL RNG was a good alternative to generate random numbers so I am trying to make it work. So here the questions:
I am compiling the "Well44497a.c" within my c++ project without further modifications. It compiled. Is that right or should I make any change?
I am using the following scheme inside my code but it is just generating a cycle of 3 RN
SOLVED: The problem was that InitWELLRNG44497a(state) should be placed outside the function. I was re initiating the generator every time I was generating a sample. For the whole run the generator has to be initialized just once.
int* sampler(PARAMETERS) { //this function returns a sample
int k;
unsigned int state[1391];
for (k = 0; k < 1391; ++k)
{
state[k] = k;
}
InitWELLRNG44497a(state); //THIS SHOULD GO ON THE CALLER FUNCTION NOT HERE
double value_first = valuate(first_state); // this function valuates one of two possible states
double value_second = valuate(second_state);
double rand_number = WELLRNG44497a()
if(rand_number > value_first / (value_first + value_second))
return second_state;
else
return first_state;
}

Your function appears to initialise the state array with the same values every time you call your sampler() function. The idea of the state array is that it holds the current state of the random number generator, and that you don't fiddle with the contents of state between calls to the RNG.
Make the state array global in your program, initialise it once, and don't touch it after initialisation.

Related

Adding expected calls in a loop

This is what I want to achieve. In my test fixture I want to call a helper functions with a parameter n to tell the test fixture how many initialization sequences should be expected. Some parameters used in the sequences are stored in three std::vector containers; fileDescriptor, handle, selectionObject.
What I have written is this:
void MyTest::init_Ok(uint32_t n)
{
for (uint32_t i = 0; i < n; ++i)
{
fileDescriptor.push_back(i); // FDs starting at 0
handle.push_back(reinterpret_cast<void*>(18 + i)); // handles starting at 18
selectionObject.push_back(555 + i); // SOs starting at 555
EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
.WillOnce(DoAll(SetArgPointee<0>(handle[i]),
Return(INIT_OK)));
EXPECT_CALL(MyMockApi::getApi(), selectionObjectGet(handle[i], Pointee(nullptr)))
.WillOnce(DoAll(SetArgPointee<1>(selectionObject[i]),
Return(SELECTION_OK)));
EXPECT_CALL(MyMockApi::getApi(), finalize(handle[i]))
.WillOnce(Return(FINAL_OK));
}
}
I know why it's not working. It is expected that all calls to initialize will be identical but yet I want to perform different actions (parameter depending on loop counter i) for the first, second, third, ..., nth call. The current implementation will only expect one call to initialize no matter parameter n. Is it possible to fix this and keep it a loop somehow, or do I have to add the actions with a WillOnce line for each i? This would mean i have to check n and add different number of WillOnce lines for different possible values of n, which i really want to avoid.
One way could be to use Invoke. You can write a function which will have access to the handles container and a running member/static variable(lets say counterVar) which will indicate the number of times the function is hit. Based on the value of counterVar, you can decide the logic.
.WillRepeatedly(Invoke(<your function>))
Something like:
EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
.WillRepeatedly(Invoke(successfulInitialize));
ReturnCode successfulInitialize(void* op, std::string msg)
{
static int counterVar = 0;
*op = handles[counterVar++];
return INIT_OK;
}

Vector of class pointers

I know that there are several similar questions previously asked. But none of them are answered with wide recognition and the vector of pointers are still very confusing to me.
Here is the code:
Imagine we have a:
vector<member*> vector_member;
for (int i = 0; i < n; i++){
member* mem = new member(i); //constructor
mem->init(); //This function use a random number generator to give the member some randomness
vector_member.push_back(mem);
}
After executing this code, I find that the all the random number for vector_member[i] are the same!
Any experts have any idea about this?
I'd have to see your init method, but my guess would be that your random function is using a seed value like the current time (eg in milliseconds since the epoch) to initialize itself, and your code is executing so quickly that the time hasn't changed between calls, so it returns the same random number.

Sequential program that accesses the whole of the array

I'm working on threads, however before I use threads I am to write 2 programs.
Set up an array and write a sequential program that accesses the whole of the array and performs some simple task on the contents.
Modify the program so that it is still sequential but accesses the array by a series of calls to a function. Each call to that function will process a number of rows of the array as defined by a parameter passed to the function.
I'm having problems understanding the questions, it seems so simple but yet I can't seem to get my head around it. I am to write the programs based on the above two questions before I start creating a program that will allow the processing to be carried out in one or more threads. Each thread should access a different set of rows of the array.
For the first question, the code I have written so far is
#include <iostream>
#include <stdio.h>
int main()
{
int array [20][20];
int i, j;
/* output each array element's value */
for ( i = 0; i < 20; i++ )
{
for ( j = 0; j < 20; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j] );
}
}
system ("PAUSE");
return 0;
}
I want to know if the above program is a sequential program? I have run the program and it access the whole array and perform one tasks which is to print out all data in the arrays.
I researched on on-line what it means by sequential program and I found it means the following statement: perform task a before task b but not at the same time. Is this right?
For the second part I have done the following:
#include <iostream>
#include <stdio.h>
void print_array(int array[20][20]);
int main()
{
int array [20][20];
int i, j;
print_array(array);
system ("PAUSE");
return 0;
}
// Output data in an array
void print_array(int array)
{
int i, j;
for ( i = 0; i < 20; i++ )
{
for ( j = 0; j < 20; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j] );
}
}
}
Am I going in the right direction? As I also got to write a version of the program that will allow the processing to be carried out in one or more threads.
EDIT: I am to use 2D arrays, sorry it wasn't clear above
I don't think you're going in the right direction, but you're not far off. What the instructions are asking for are some of the preliminary steps needed to take the work of processing an array sequentially and make it run in parallel. When writing a parallel program, it is often useful to start with a working sequential program and slowly transform it into a parallel program. Following the instructions is a way to do this.
Let's consider the parts of the question separately:
Set up an array and write a sequential program that accesses the whole of the array and performs some simple task on the contents.
The simple task that you chose for your array is to print the contents, but this isn't a suitable task, because it has no functional result. A more suitable task would be the sum the elements in the array. Other tasks might be count the elements that meet some condition, or to multiple each element by two.
So, first try to modify your initial program to sum the elements instead of printing them.
(In your code you are using a two-dimensional array. I would suggest using a 1-dimensional array for simplicity.)
Modify the program so that it is still sequential but accesses the array by a series of calls to a function. Each call to that function will process a number of rows of the array as defined by a parameter passed to the function.
In this part what you are trying to do is break up the functionality into small pieces of work. (Eventually you will send these units of work to threads for processing, but you are just doing the preliminary steps now.) If we did a sum in part 1, then here you might write a function which is int sumKitems(int *array, int startIndex, int numItems). The main program would then call this on each set of (say) 10 items in the array, and combine the full results by summing the results from each sumKitems call.
So, if there are 100 items in the array, you could make 10 calls to sumKitems(...), telling the function to process 0...9, 10...19, ..., 90...99. This would be in place of doing the sum on all 100 items individually.
--
To summarize, part one would be a simple for loop, not too differently from what you've written, just with some computation being performed.
The second part should do exactly the same computation and return exactly the same result, just using another function call which handles k items at time. (If you pass the number of items to handle at a time as a parameter you will be able to balance the cost of communication vs work being done when moving to a threaded implementation.)
In the end, you will probably be asked to replace the call to sumKitems(...) with a queue that sends work to the threads to do independently.
I believe that if you are not creating separate threads in any way then you are in fact writing a sequential program. There is no part of your code where you jump into a new thread to do some operation while the main thread does something else.
Summary: your code runs on a single thread - it is sequential
You must pass the array not as an integer but as a double pointer -> int array[][] or int** array
To perform operations on the array sequentially would be to start at the first place in the array and increment through the array performing operations as you go
array[10] = {0,1,2,3,4,5,6,7,8,9}
iterate through array with some action such as adding +5
array [10] = {5,6....}
To make this multi-threaded you need to have different threads operate on different segments of the array such as places 0-4,5-9 and perform the action so it can be done in less time. If you're doing it this way you will not need to worry about mutexes.
So Thread one increments through array[10] {0,1,2,3}
Thread two increments through array[10] {4,5,6,7}
Each increment one place at a time and both threads run concurrently

add elements to vector in a loop

the code I have problem is:
vector<int> steps_list;
steps_list.reserve(runs);
for (int i=0;i<runs;i++){
int steps=0;
bool in_con=false;
srand(time(0));
int init_pos=rand()%mylat;
while (in_con==false) {
srand(time(0));
int step=2*(rand()%2)-1;
init_pos+=step;
init_pos=init_pos%grid.size();
if (grid[init_pos]==0){
in_con=true;
}
steps+=1;
}
steps_list.push_back(steps);
}
for (int i=0;i<mylat;i++){
cout<<steps_list[i]<<" ";
}
I want to store in steps_list vector all the different steps ,but instead of that it stores only one step and it fills the vector with that.
I can't figure where is my problem.I am not familiar with vectors.
You need to move this line
srand(time(0));
outside the loop, and preferably do this once at the beginning of your program.
You are seeding the random number generator, and my guess is the time you obtain has second resolution. The loop iterations take less than a second, so you are always seeding with the same value and obtaining the same random numbers.
I'm guessing but the error might be that you call srand(time(0)) before each call of rand(). That's a very good way to make your random numbers completely unrandom.
Could that be an explanation for what you see?
In any case call srand(time(0)) once at the beginning of the program and nowhere else.

C++ recursive function, calling current depth

I'm writing a function for calculating integrals recursively, using the trapezoid rule. For some f(x) on the interval (a,b), the method is to calculate the area of the big trapezoid with side (b-a) and then compare it with the sum of small trapezoids formed after dividing the interval into n parts. If the difference is larger than some given error, the function is called again for each small trapezoid and the results summed. If the difference is smaller, it returns the arithmetic mean of the two values.
The function takes two parameters, a function pointer to the function which is to be integrated and a constant reference to an auxiliary structure, which contains information such as the interval (a,b), the amount of partitions, etc:
struct Config{
double min,max;
int partitions;
double precision;
};
The problem arises when I want to change the amount of partitions with each iteration, for the moment let's say just increment by one. I see no way of doing this without resorting to calling the current depth of the recurrence:
integrate(const Config &conf, funptr f){
double a=conf.min,b=conf.max;
int n=conf.partitions;
//calculating the trapezoid areas here
if(std::abs(bigTrapezoid-sumOfSmallTrapezoids) > conf.precision){
double s=0.;
Config configs = new Config[n];
int newpartitions = n+(calls);
for(int i=0; i < n;++i){
configs[i]={ a+i*(b-a)/n , a+(i+1)*(b-a)/n , newpartitions};
s+=integrate(configs[i],f);
}
delete [] configs;
return s; }
else{
return 0.5*(bigTrapezoid+sumOfSmallTrapezoids);}
}
The part I'm missing here is of course a way to find (calls). I have tried doing something similar to this answer, but it does not work, in fact it freezes the pc until makefile kills the process. But perhaps I'm doing it wrong. I do not want to add an extra parameter to the function or an additional variable to the structure. How should I proceed?
You cannot "find" calls, but you can definitely pass it yourself, like this:
integrate(const Config &conf, funptr f, int calls=0) {
...
s+=integrate(configs[i],f, calls+1);
...
}
It seems to me that 'int newpartitions = n + 1;' would be enough, no? At every recursion level, the number of partitions increases by one. Say conf.partitions starts off at 1. If the routine needs to recurse down a new level, newpartitions is 2, and you will build 2 new Config instances each with '2' as the value for partitions. Recursing down another level, newpartitions is 3, and you build 3 Configs, each with '3' as 'partitions', and so on.
The trick here is to make sure your code is robust enough to avoid infinite recursion.
By the way, it seems inefficient to me to use dynamic allocation for Config instances that have to be destroyed after the loop. Why not build a single Config instance on the stack inside the loop? Your code should run much faster that way.