Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <iomanip>
- using namespace std;
- struct GenAl
- {
- double x;
- double y;
- double f;
- };
- double function(const double& x, const double& y)
- {
- return sin(x)/(1 + x*x + y*y);
- }
- double probability(const double& f1, const double& f2, const double& f3, const double& f4)
- {
- return 1 - f1 / (f1 + f2 + f3 + f4);
- }
- int crossover(const double& p1, const double& p2, const double& p3, const double& p4)
- {
- double value = rand()/(RAND_MAX/(p1 + p2 + p3 + p4));
- if (value < p1) return 0;
- if (value > p1 && value < (p1 + p2)) return 1;
- if (value > (p1 + p2) && value < (p1 + p2 + p3)) return 2;
- if (value > (p1 + p2 + p3) && value < (p1 + p2 + p3 + p4)) return 3;
- }
- double mutation(const double& gen)
- {
- if (gen >= 0) return gen - 0.05;
- else return gen + 0.05;
- }
- int main()
- {
- double ax = -2, bx = 2, ay = -2, by = 2;
- int n = 1;
- vector <GenAl> g(4);
- for (auto i = 0; i < 4; i++)
- {
- g[i].x = rand()/(RAND_MAX/2.0) - 2;
- g[i].y = rand() / (RAND_MAX / 2.0) - 2;
- g[i].f = function(g[i].x, g[i].y);
- }
- double avg = 0;
- cout << "0" << endl;
- cout << " x y f(x,y)" << endl;
- sort(g.begin(), g.end(), [](auto a, auto b) { return a.f < b.f; });
- for (auto i : g)
- {
- cout << fixed << setprecision(4) << setw(7) << i.x << " " << setw(7) << i.y << " " << setw(7) << i.f << " " << endl;
- avg += i.f;
- }
- avg /= 4;
- cout << endl << "max: " << g[3].f << " average: " << avg << endl << endl;
- while (n <= 50)
- {
- vector <double> prob(4);
- prob[0] = probability(g[0].f, g[1].f, g[2].f, g[3].f);
- prob[1] = probability(g[1].f, g[0].f, g[2].f, g[3].f);
- prob[2] = probability(g[2].f, g[1].f, g[0].f, g[3].f);
- prob[3] = probability(g[3].f, g[1].f, g[2].f, g[0].f);
- int i = crossover(prob[0], prob[1], prob[2], prob[3]);
- g.erase(g.begin() + i);
- g.push_back({});
- vector <GenAl> g_copy = g;
- g[0].x = g_copy[2].x;
- g[1].x = g_copy[2].x;
- g[2].x = g_copy[0].x;
- g[3].x = g_copy[1].x;
- g[0].y = g_copy[1].y;
- g[1].y = g_copy[0].y;
- g[2].y = g_copy[2].y;
- g[3].y = g_copy[2].y;
- for (auto i = 0; i < 4; i++)
- {
- if (rand() % 2 == 0) g[i].x = g[i].x - 0.05;
- else g[i].y = g[i].y - 0.05;
- }
- for (auto i = 0; i < 4; i++) g[i].f = function(g[i].x, g[i].y);
- double avg = 0;
- cout << n++ << " " << endl;
- cout << " x y f(x,y)" << endl;
- sort(g.begin(), g.end(), [](auto a, auto b) { return a.f < b.f; });
- for (auto i : g)
- {
- cout << fixed << setprecision(4) << setw(7) << i.x << " " << setw(7) << i.y << " " << setw(7) << i.f << " " << endl;
- avg += i.f;
- }
- avg /= 4;
- cout << endl << "max: " << g[3].f << " average: " << avg << endl << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement