Why do I get different output?

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.
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
Topic archived. No new replies allowed.