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 a = 2.0;
  14. double b = 4.0;
  15. double c;
  16. double eps = 0.00001;
  17. int iteracje = 0;
  18.  
  19. // Sprawdzenie warunku istnienia miejsca zerowego
  20. if (f(a) * f(b) >= 0) {
  21. cout << "Brak miejsca zerowego w podanym przedziale." << endl;
  22. return 0;
  23. }
  24.  
  25. // Metoda bisekcji
  26. while ((b - a) / 2 > eps) {
  27. c = (a + b) / 2;
  28.  
  29. if (f(c) == 0.0)
  30. break;
  31. else if (f(a) * f(c) < 0)
  32. b = c;
  33. else
  34. a = c;
  35.  
  36. iteracje++;
  37. }
  38.  
  39. cout << fixed << setprecision(6);
  40. cout << "Miejsce zerowe funkcji: x = " << (a + b) / 2 << endl;
  41. cout << "Wartosc funkcji w tym punkcie: f(x) = "
  42. << f((a + b) / 2) << endl;
  43. cout << "Liczba iteracji: " << iteracje << endl;
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
Miejsce zerowe funkcji: x = 2.828423
Wartosc funkcji w tym punkcie: f(x) = -0.000006
Liczba iteracji: 17