Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <stdlib.h>
- #define _USE_MATH_DEFINES
- #include <math.h>
- #include <time.h>
- #include <string.h>
- double func(double x, double y) {
- return sin(x) - cos(2 * y);
- }
- double gradientX(double x) {
- return cos(x);
- }
- double gradientY(double y) {
- return 2 * sin(2 * y);
- }
- double calcVx(double x) {
- return cos(x) / sin(x);
- }
- double calcVy(double y) {
- return -0.5 * tan(2 * y);
- }
- double randOnRange(double min, double max) {
- double f = (double)rand() / RAND_MAX;
- return min + f * (max - min);
- };
- double distGradient(const double &gradientX, const double &gradientY) {
- return sqrt(pow(gradientX, 2) + pow(gradientY, 2));
- }
- int main() {
- puts("Really minimum f(x,y) = sin(x)-cos(2y) is -2");
- srand(time(0));
- double arrX[100] = { 0 };
- double arrY[100] = { 0 };
- double eps = 0.01;
- double t = 0;
- double count = 0;
- for (int i = 0; i < 100; i++) {
- arrX[i] = randOnRange(-10, 10);
- arrY[i] = randOnRange(-10, 10);
- }
- for (int i = 0; i < 100; i++) {
- double x = arrX[i];
- double y = arrY[i];
- for (; sqrt(pow(gradientX(x), 2) + pow(gradientY(y), 2) > eps); ) {
- if (gradientX(x) * calcVx(x) + gradientY(y) * calcVy(y) > 0) {
- t = -1;
- }
- else {
- t = 1;
- }
- while (func(x + t * calcVx(x), y + t * calcVy(y)) >= func(x, y) + 3 / 4 * t * (gradientX(x) * calcVx(x) + gradientY(y) * calcVy(y))) {
- t /= 2;
- }
- x = x + t * calcVx(x);
- y = y + t * calcVy(y);
- }
- arrX[i] = x;
- arrY[i] = y;
- }
- for (int i = 0; i < 100; i++) {
- count += func(arrX[i], arrY[i])- func(3 / 2 * M_PI, 0);
- }
- printf("Average accuracy: %.6lf\n", count/100);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement