I have the following program:
int main(int argc, char** argv){
unsigned long int mean=0;
for(int i=1;i<10;i++){
mean+=poisson(12);
cout<<mean<<endl;
}
cout<<"Sum of poisson: "<< mean;
return 0;
}
when I run it, I get the output:
15
26
41
56
73
82
92
106
116
Sum of poisson: 116
However, if I comment the line " cout<<mean<<endl; ", I get the following unexpected output
Sum of poisson: 22
What is going on? Why the "cout" line is affecting the variable mean?
I'm using linux, with the following commands
Compile: g++ -Wall -c "%f"
Build: g++ -Wall -o "%e" "%f"
gcc version: 4.4.1
Below is the complete code with the poisson function.
untitle.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
#define RAND_UNIFORM (double)rand()/(double)RAND_MAX
unsigned long int poisson(double lambda){
double g,p=exp(-lambda);
double u=RAND_UNIFORM;
unsigned long int k=0;
while (u>g){
p*=(lambda/(double)(++k));
g+=p;
};
return k;
};
int main(int argc, char** argv){
unsigned long int mean=0;
for(int i=1;i<10;i++){
mean=mean+poisson(12);
cout<<mean<<endl;
}
cout<<"Sum of poisson: "<< mean;
return 0;
}
Any help would be much appreciated.
santiagorf