fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <fstream>
  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. // Metoda bisekcji
  13. double bisekcja(double a, double b, double eps) {
  14. double c;
  15.  
  16. if (f(a) * f(b) >= 0) {
  17. cout << "Warunek f(a)*f(b) < 0 nie jest spełniony!" << endl;
  18. return NAN;
  19. }
  20.  
  21. while ((b - a) / 2 > eps) {
  22. c = (a + b) / 2;
  23.  
  24. if (f(c) == 0.0)
  25. return c;
  26. else if (f(a) * f(c) < 0)
  27. b = c;
  28. else
  29. a = c;
  30. }
  31.  
  32. return (a + b) / 2;
  33. }
  34.  
  35. int main() {
  36. double a = 2.0;
  37. double b = 4.0;
  38. double eps = 1e-6;
  39.  
  40. cout << "f(2) = " << f(a) << endl;
  41. cout << "f(4) = " << f(b) << endl;
  42.  
  43. double zero = bisekcja(a, b, eps);
  44.  
  45. cout << "Miejsce zerowe (metoda bisekcji): x = " << zero << endl;
  46.  
  47. // Zapis danych do pliku
  48. ofstream file("dane.dat");
  49. for (double x = 0; x <= 5; x += 0.05) {
  50. file << x << " " << f(x) << endl;
  51. }
  52. file.close();
  53.  
  54. // Wywołanie gnuplota
  55. system("gnuplot -p -e \"plot 'dane.dat' using 1:2 with lines title 'f(x)=1/4x^2-2', \
  56. 0 with lines title 'y=0'\"");
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout #stderr 0s 5328KB
stdin
Standard input is empty
stdout
f(2) = -1
f(4) = 2
Miejsce zerowe (metoda bisekcji): x = 2.82843
stderr
sh: 1: gnuplot: not found