Advertisement
lobaev

Untitled

Mar 26th, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. #include <cmath>
  2. #include <iostream>
  3.  
  4. float solve(float (*)(float), float (*)(float), float, float);
  5.  
  6. float fx(float);
  7. float dfx(float);
  8.  
  9. int main() {
  10. const float eps = 0.0001;
  11.  
  12. float x1 = solve(fx, dfx, -5, eps),
  13. x2 = solve(fx, dfx, 0, eps),
  14. x3 = solve(fx, dfx, 2, eps);
  15. std::cout << "x1 = " << x1 << std::endl <<
  16. "x2 = " << x2 << std::endl <<
  17. "x3 = " << x3 << std::endl;
  18. std::cout << "f(x1) = " << fx(x1) << std::endl <<
  19. "f(x2) = " << fx(x2) << std::endl <<
  20. "f(x3) = " << fx(x3) << std::endl;
  21.  
  22. return 0;
  23. }
  24.  
  25. float solve(float (*fx)(float), float (*dfx)(float), float x0, const float eps) {
  26. float x = x0;
  27. while (std::abs(fx(x)) > eps) {
  28. if (dfx(x) == 0 || fx(x) * fx(x + eps * (x - fx(x) / dfx(x) - x > 0 ? 1.f : -1.f)) < 0) {
  29. break;
  30. }
  31. x -= fx(x) / dfx(x);
  32. }
  33. return x;
  34. }
  35.  
  36. float fx(float x) {
  37. return (x * x * x) + (3 * x * x) + (-8 * x) + (1);
  38. }
  39.  
  40. float dfx(float x) {
  41. return (3 * x * x) + (6 * x) + (-8);
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement