Vladislav_Bezruk

3 lab

Oct 4th, 2021 (edited)
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. struct Vector {
  7.     double x, y, z;
  8.     Vector() {x = y = z = 0.;}
  9.     Vector(double a, double b, double c) : x(a), y(b), z(c) {}
  10.     Vector operator * (const double k) {
  11.         Vector c(x * k, y * k, z * k);
  12.         return c;
  13.     }
  14.     Vector operator - (const Vector &a) {
  15.         Vector c(x - a.x, y - a.y, z - a.z);
  16.         return c;
  17.     }
  18. };
  19.  
  20. double f(double x, double y, double z) { // u(x, y, z)
  21.     double a = 4 * x - 5 * pow(y, 2) + z - 3.75;
  22.     double b = 3 * pow(x, 2) + 2 * y - 2 * z - 3;
  23.     double c = x + y + 2 * pow(z, 2) - 3.5;
  24.     return pow(a, 2) + pow(b, 2) + pow(c, 2);
  25. }
  26.  
  27. Vector df(double f(double x, double y, double z), Vector a) {
  28.     const double d = 1e-10;
  29.     Vector grad;
  30.    
  31.     grad.x = (f(a.x + d, a.y, a.z) - f(a.x, a.y, a.z)) / d;
  32.     grad.y = (f(a.x, a.y + d, a.z) - f(a.x, a.y, a.z)) / d;
  33.     grad.z = (f(a.x, a.y, a.z + d) - f(a.x, a.y, a.z)) / d;
  34.     return grad;
  35. }
  36.  
  37. double kNorma(Vector a) {
  38.     return sqrt(pow(a.x, 2)) + (pow(a.y, 2)) + (pow(a.z, 2));
  39. }
  40.  
  41. void solve(double u(double x, double y, double z), double EPS, double L) {
  42.     Vector prevX, x;
  43.     int i = 0;
  44.     double d;
  45.    
  46.     do {
  47.         prevX = x;
  48.         d = kNorma(df(u, x));
  49.         x = prevX - df(u, prevX) * L;
  50.        
  51.         cout << "Iteration :: " << i << "\t   >>\tx = {" << x.x << ", " << x.y << ", " << x.z << "}";
  52.         cout << "\t   >>\td = " << d;
  53.         if (d < EPS) cout << " < EPS";
  54.         cout << endl;
  55.  
  56.         i++;
  57.     } while (d >= EPS);
  58.     return;
  59. }
  60.  
  61. int main() {
  62.    
  63.     solve(f, 1e-4, 1e-3);
  64.    
  65.     return 0;
  66. }
Add Comment
Please, Sign In to add comment