Advertisement
HabKaffee

Untitled

May 24th, 2020
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. #include <time.h>
  6. #include <string.h>
  7.  
  8. double func(double x, double y) {
  9.     return sin(x) - cos(2 * y);
  10. }
  11.  
  12. double gradientX(double x) {
  13.     return cos(x);
  14. }
  15. double gradientY(double y) {
  16.     return 2 * sin(2 * y);
  17. }
  18.  
  19. double calcVx(double x) {
  20.     return cos(x) / sin(x);
  21. }
  22.  
  23. double calcVy(double y) {
  24.     return -0.5 * tan(2 * y);
  25. }
  26.  
  27. double randOnRange(double min, double max) {
  28.     double f = (double)rand() / RAND_MAX;
  29.     return min + f * (max - min);
  30. };
  31.  
  32. double distGradient(const double &gradientX, const double &gradientY) {
  33.     return sqrt(pow(gradientX, 2) + pow(gradientY, 2));
  34. }
  35.  
  36. int main() {
  37.     puts("Really minimum f(x,y) = sin(x)-cos(2y) is -2");
  38.     srand(time(0));
  39.     double arrX[100] = { 0 };
  40.     double arrY[100] = { 0 };
  41.     double eps = 0.01;
  42.     double t = 0;
  43.     double count = 0;
  44.     for (int i = 0; i < 100; i++) {
  45.         arrX[i] = randOnRange(-10, 10);
  46.         arrY[i] = randOnRange(-10, 10);
  47.     }
  48.  
  49.     for (int i = 0; i < 100; i++) {
  50.         double x = arrX[i];
  51.         double y = arrY[i];
  52.         for (; sqrt(pow(gradientX(x), 2) + pow(gradientY(y), 2) > eps); ) {
  53.             if (gradientX(x) * calcVx(x) + gradientY(y) * calcVy(y) > 0) {
  54.                 t = -1;
  55.             }
  56.             else {
  57.                 t = 1;
  58.             }
  59.             while (func(x + t * calcVx(x), y + t * calcVy(y)) >= func(x, y) + 3 / 4 * t * (gradientX(x) * calcVx(x) + gradientY(y) * calcVy(y))) {
  60.                 t /= 2;
  61.             }
  62.             x = x + t * calcVx(x);
  63.             y = y + t * calcVy(y);
  64.         }
  65.         arrX[i] = x;
  66.         arrY[i] = y;
  67.     }
  68.     for (int i = 0; i < 100; i++) {
  69.         count += func(arrX[i], arrY[i]);
  70.     }
  71.     printf("Average accuracy: %.6lf\n", count / 100);
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement