Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. double func(double x, double y) {
  8.   return 6*x*x  - x*y + 12*y + y*y - 8*x;
  9. }
  10.  
  11. double funcdx(double x, double y) {
  12.   return -y + 12*x - 8;
  13. }
  14.  
  15. double funcdy(double x, double y) {
  16.   return 2*y - x + 12;
  17. }
  18.  
  19. void gradient(double x0, double y0, double h0, unsigned n) {
  20.   double x = x0, y = y0, h = h0;
  21.  
  22.   double xn, yn;
  23.  
  24.   cout << 0 << "\t" << x << "\t" << y << "\t" << func(x, y) << "\t" << funcdx(x, y) << "\t" << funcdy(x, y) << "\t" << endl;
  25.  
  26.   for (unsigned i = 1; i <= n; i++) {
  27.     xn = x - h*funcdx(x, y);
  28.     yn = y - h*funcdy(x, y);
  29.  
  30.     if (func(xn, yn) >= func(x, y)) {
  31.       h = h/2;
  32.     } else {
  33.       x = xn;
  34.       y = yn;
  35.       h = h*2;
  36.     }
  37.  
  38.     cout << i << "\t" << x << "\t" << y << "\t" << func(x, y) << "\t" << funcdx(x, y) << "\t" << funcdy(x, y) << "\t" << endl;
  39.   }
  40. }
  41.  
  42. int main() {
  43.   cout << setprecision(5) << fixed;
  44.  
  45.   const double x0 = 0;
  46.   const double y0 = 0;
  47.   const double h = 0.25;
  48.   const unsigned num_it = 1;
  49.  
  50.   gradient(x0, y0, h, num_it);
  51.  
  52.   return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement