Why do I get different output?
May 24, 2014 at 11:37am UTC
Hi, I am really curious as to why I'm getting two different results with the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
double uniform();
double normal();
int main(){
srand(time(NULL));
for (int i=0;i<5;i++)
cout << normal() << endl;
return 0;
}
double uniform(){
return ((double )(rand()) + 1.)/((double )(RAND_MAX) + 1.);
}
double normal(){
double u1;
u1 <- uniform();
return u1;
}
The code above gives the following output:
6.80115e+257
8.48798e-314
8.48798e-314
8.48798e-314
8.48798e-314
However, the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
double uniform();
double normal();
int main(){
srand(time(NULL));
for (int i=0;i<5;i++)
cout << normal() << endl;
return 0;
}
double uniform(){
return ((double )(rand()) + 1.)/((double )(RAND_MAX) + 1.);
}
double normal(){
double u1= uniform();
return u1;
}
gives me a different output:
1 2 3 4 5 6
0.414185
0.273132
0.545807
0.831024
0.210205
The only difference is the normal() function. Any insights would be appreciated.
May 24, 2014 at 11:57am UTC
1 2 3 4 5 6 7 8 9
double normal(){
//Declares double value. For now it is filld with junk
double u1;
//Does nothing. Essentually you are comparing junk with negated value returned by uniform() and throwing out result
//is the same as u1 < (-uniform() )
u1 <- uniform();
//return junk
return u1;
}
Last edited on May 24, 2014 at 11:58am UTC
Topic archived. No new replies allowed.