Advertisement
mikolajmki

aan_lab13

Jan 10th, 2022
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. float f(float x)
  8. {
  9.     return x * x * x - 71;
  10. }
  11.  
  12. float f_prim(float x)
  13. {
  14.     return 3 * x * x;
  15. }
  16.  
  17. void metodaBisekcji(float a, float b, float s, float ap)
  18. {
  19.     int i = 0;
  20.  
  21.     if (f(a) * f(b) < 0)
  22.     {
  23.         while (abs(f(s)) > ap)
  24.         {
  25.             s = (a + b) / (float)2;
  26.             //cout << a << endl;
  27.             //cout << b << endl;
  28.             //cout << s << endl;
  29.             //cout << f(a) * f(s) << endl;
  30.             if (f(a) * f(s) < 0) b = s;
  31.             else a = s;
  32.             i ++;
  33.         }
  34.     }
  35.     cout << endl << "Rozwiazanie metoda bisekcji jest rowne: "
  36.          << (a + b) / (float)2 << endl
  37.          << "Wartosc funkcji: " << f((a + b) / (float)2) << endl
  38.          << "Ilosc iteracji: " << i << endl << endl;
  39. }
  40.  
  41.  
  42. void metodaNewtona(float a, float b, float s, float x0, float ap)
  43. {
  44.     float x = 1;
  45.     int i = 0;
  46.  
  47.     if (f_prim(x0) != 0)
  48.     {
  49.         while (abs(f(x0) > ap))
  50.         {
  51.             x = x0 - f(x0) / f_prim(x0);
  52.             x0 = x;
  53.             i ++;
  54.         }
  55.     }
  56.     cout << "Rozwiazanie metoda Newtona jest rowne: " << x << endl
  57.          << "Wartosc funkcji: " << f(x) << endl
  58.          << "Ilosc iteracji: " << i << endl;
  59. }
  60.  
  61.  
  62. int main()
  63. {
  64.     float a = 4;
  65.     float b = 5;
  66.     float x0 = 5;
  67.     float s = 1;
  68.     float ap = 0;
  69.  
  70.     cout << "Wprowadz dokladnosc: ";
  71.     cin >> ap;
  72.  
  73.     //  x^3 - 71 = 0
  74.  
  75.     metodaBisekcji(a, b, s, ap);
  76.     metodaNewtona(a,b, s, x0, ap);
  77.  
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement