fork(1) download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // Definicja funkcji
  7. double f(double x)
  8. {
  9. return 0.25 * x * x - 2.0;
  10. }
  11.  
  12. int main()
  13. {
  14. double x0 = 2.0;
  15. double x1 = 4.0;
  16. double eps = 1e-6;
  17. int maxIter = 100;
  18. int iter = 0;
  19. double x2;
  20.  
  21. // Sprawdzenie, czy w przedziale jest miejsce zerowe
  22. if (f(x0) * f(x1) > 0)
  23. {
  24. cout << "Brak miejsca zerowego w przedziale [2,4]." << endl;
  25. return 0;
  26. }
  27.  
  28. // Metoda siecznych
  29. do
  30. {
  31. x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
  32.  
  33. x0 = x1;
  34. x1 = x2;
  35.  
  36. iter++;
  37.  
  38. } while (fabs(f(x2)) > eps && iter < maxIter);
  39.  
  40. cout << "Miejsce zerowe: x = " << x2 << endl;
  41. cout << "Liczba iteracji: " << iter << endl;
  42.  
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
Miejsce zerowe: x = 2.82843
Liczba iteracji: 5