Advertisement
HabKaffee

Untitled

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