Advertisement
Guest User

Untitled

a guest
Oct 8th, 2015
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. struct vector2d {
  7.     float x1;
  8.     float x2;
  9. };
  10.  
  11. float f(vector2d v) {
  12.     return (v.x1-4)*(v.x1-4) + 20 * (v.x2 - 100) * (v.x2 - 100);
  13. }
  14.  
  15. float f(float x1, float x2) {
  16.     return (x1-4)*(x1-4) + 20 * (x2 - 100) * (x2 - 100);
  17. }
  18.  
  19. vector2d min (vector2d v1, vector2d v2, vector2d v3, vector2d v4, vector2d v5) {
  20.     vector2d v = min(f(v1), f(v2))==f(v1)?v1:v2;
  21.     v = min(f(v), f(v3))==f(v)?v:v3;
  22.     v = min(f(v), f(v4))==f(v)?v:v4;
  23.     v = min(f(v), f(v5))==f(v)?v:v5;
  24. }
  25.  
  26. float getRandom()  {
  27.     int sign = rand()%2==0?-1:1;
  28.     return ((double) rand() / (RAND_MAX)) * sign;
  29. }
  30.  
  31. vector2d getRandomVector (vector2d v, float step){
  32.     vector2d result;
  33.     result.x1 = step*getRandom() + v.x1;
  34.     result.x2 = step*getRandom() + v.x2;
  35.     return result;
  36. }
  37.  
  38. int main() {
  39.     vector2d v_p; v_p.x1 = 7; v_p.x2 = 95;
  40.     vector2d v_n;
  41.     float step = 1.0f;
  42.     float eps = 0.0001;
  43.     srand(time(0));
  44.     int iterations = 0;
  45.     while (true) {
  46.         vector2d v1, v2, v3, v4, v5;
  47.         v1 = getRandomVector(v_p, step);
  48.         v2 = getRandomVector(v_p, step);
  49.         v3 = getRandomVector(v_p, step);
  50.         v4 = getRandomVector(v_p, step);
  51.         v5 = getRandomVector(v_p, step);
  52.         v_n = min(v1, v2, v3, v4, v5);
  53.  
  54.         if (f(v_n) >= f(v_p)) {
  55.             if (fabs(f(v_n) - f(v_p)) <= eps && iterations > 0) {
  56.                 break;
  57.             }
  58.             step*=0.1;
  59.         }
  60.  
  61.         v_p = v_n;
  62.  
  63.         iterations++;
  64.     }
  65.     cout << "x1 = " << v_n.x1 << " x2 = " << v_n.x2 << endl;
  66.     cout << "f(x1, x2) = " << f(v_n) << endl;
  67.     cout << "iterations: " << iterations << endl;
  68.     cout << "step: " << step << endl;
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement