Random Number Generation within a range

I'm trying to generate a random number (data type double, so decimal) between the values -2, and 2. (i.e. [-2,2] including the ends). Inside my RandomSearchMaximum() function at the top you will see my attempt at this. I really don't know what I'm doing with my random_device rd, mt19937, or uniform_real_distribution. Any help on this would be appreciated.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <random>
#include <stdlib.h> 
#include <iomanip>
#include <cmath>
#include <ctime>


double f(double x, double y){
	return 4 * x + 2 * y + pow(x, 2) - 2 * pow(x, 4) + 2 * x*y - 3 * pow(y, 2);
}


void RandomSearchMaximum(int maxit, int stepsize){
	std::random_device rd;
	std::mt19937 gen(rd());
	std::uniform_real_distribution<double> dis(-2, 2);

	double x = 0;
	double y = 0;
	double biggest = 0;
	int iterations = 0;
	
	std::cout << "-------Random Search Method: 4x + 2y + x^2 - 2x^4 + 2xy - 3y^2-------" << std::endl;
	std::cout << "Iterations           X            Y           f(x,y)          Biggest" << std::endl;
	do{
	x = -2 + (2 - (-2))*dis(gen); // dis(gen) is the random number 
	y = -2 + (2 - (-2))*dis(gen); // dis(gen) is the random number
	if (biggest < f(x, y)); {
		biggest = f(x, y);
	}

	if (iterations % stepsize == 0 && iterations != 0){
		std::cout << iterations << "             ";
		std::cout << x << "      ";
		std::cout << y << "      ";
		std::cout << f(x, y) << "        ";
		std::cout << biggest << std::endl;
	}
	iterations++;
	} while (iterations <= maxit);

}

int main(){
	
	RandomSearchMaximum(10000, 1000);

	system("pause");
	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <random>
#include <ctime>

int main()
{
    std::mt19937 gen(time(NULL));
    std::uniform_real_distribution<double> dis(-2, 2);
    for (int i = 0; i < 10; ++i)
        std::cout << dis(gen) << std::endl;
    return 0;
}
-0.387274
1.35675
-0.119817
0.0297828
-0.825002
1.76383
1.59239
-1.6191
1.24281
1.43742
Topic archived. No new replies allowed.