fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // Definicja funkcji
  7. double f(double x) {
  8. return 0.25 * x * x - 2.0;
  9. }
  10.  
  11. int main() {
  12. double x0 = 2.0; // pierwszy punkt
  13. double x1 = 3.0; // drugi punkt
  14. double eps = 1e-6; // dokładność
  15. int maxIter = 100;
  16. double x2;
  17.  
  18. cout << "f(2) = " << f(x0) << endl;
  19. cout << "f(3) = " << f(x1) << endl;
  20.  
  21. for (int i = 0; i < maxIter; i++) {
  22. if (fabs(f(x1) - f(x0)) < 1e-12) {
  23. cout << "Dzielenie przez zero!" << endl;
  24. return 1;
  25. }
  26.  
  27. // wzór metody siecznych
  28. x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
  29.  
  30. if (fabs(x2 - x1) < eps) {
  31. cout << "Miejsce zerowe: x = " << x2 << endl;
  32. cout << "Liczba iteracji: " << i + 1 << endl;
  33. return 0;
  34. }
  35.  
  36. x0 = x1;
  37. x1 = x2;
  38. }
  39.  
  40. cout << "Nie osiagnieto zadanej dokladnosci." << endl;
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
f(2) = -1
f(3) = 0.25
Miejsce zerowe: x = 2.82843
Liczba iteracji: 5