Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- using namespace std;
- struct vector2d {
- float x1;
- float x2;
- };
- float f(vector2d v) {
- return (v.x1-4)*(v.x1-4) + 20 * (v.x2 - 100) * (v.x2 - 100);
- }
- float f(float x1, float x2) {
- return (x1-4)*(x1-4) + 20 * (x2 - 100) * (x2 - 100);
- }
- vector2d min (vector2d v1, vector2d v2, vector2d v3, vector2d v4, vector2d v5) {
- vector2d v = min(f(v1), f(v2))==f(v1)?v1:v2;
- v = min(f(v), f(v3))==f(v)?v:v3;
- v = min(f(v), f(v4))==f(v)?v:v4;
- v = min(f(v), f(v5))==f(v)?v:v5;
- }
- float getRandom() {
- int sign = rand()%2==0?-1:1;
- return ((double) rand() / (RAND_MAX)) * sign;
- }
- vector2d getRandomVector (vector2d v, float step){
- vector2d result;
- result.x1 = step*getRandom() + v.x1;
- result.x2 = step*getRandom() + v.x2;
- return result;
- }
- int main() {
- vector2d v_p; v_p.x1 = 7; v_p.x2 = 95;
- vector2d v_n;
- float step = 1.0f;
- float eps = 0.0001;
- srand(time(0));
- int iterations = 0;
- while (true) {
- vector2d v1, v2, v3, v4, v5;
- v1 = getRandomVector(v_p, step);
- v2 = getRandomVector(v_p, step);
- v3 = getRandomVector(v_p, step);
- v4 = getRandomVector(v_p, step);
- v5 = getRandomVector(v_p, step);
- v_n = min(v1, v2, v3, v4, v5);
- if (f(v_n) >= f(v_p)) {
- if (fabs(f(v_n) - f(v_p)) <= eps && iterations > 0) {
- break;
- }
- step*=0.1;
- }
- v_p = v_n;
- iterations++;
- }
- cout << "x1 = " << v_n.x1 << " x2 = " << v_n.x2 << endl;
- cout << "f(x1, x2) = " << f(v_n) << endl;
- cout << "iterations: " << iterations << endl;
- cout << "step: " << step << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement