fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <iomanip>
  4.  
  5. using namespace std;
  6.  
  7. // Definicja funkcji
  8. double f(double x) {
  9. return 0.25 * x * x - 2.0;
  10. }
  11.  
  12. int main() {
  13. double x0 = 2.0;
  14. double x1 = 4.0;
  15. double eps = 0.00001;
  16. double x2;
  17. int iteracje = 0;
  18.  
  19. if (f(x0) * f(x1) >= 0) {
  20. cout << "Brak gwarancji zbieznosci metody siecznych." << endl;
  21. return 0;
  22. }
  23.  
  24. // Metoda siecznych
  25. do {
  26. x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
  27. x0 = x1;
  28. x1 = x2;
  29. iteracje++;
  30. } while (fabs(f(x2)) > eps);
  31.  
  32. cout << fixed << setprecision(6);
  33. cout << "Miejsce zerowe funkcji: x = " << x2 << endl;
  34. cout << "Wartosc funkcji w tym punkcie: f(x) = " << f(x2) << endl;
  35. cout << "Liczba iteracji: " << iteracje << endl;
  36.  
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
Miejsce zerowe funkcji: x = 2.828423
Wartosc funkcji w tym punkcie: f(x) = -0.000006
Liczba iteracji: 4