Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <iostream>
- float solve(float (*)(float), float (*)(float), float, float);
- float fx(float);
- float dfx(float);
- int main() {
- const float eps = 0.0001;
- float x1 = solve(fx, dfx, -5, eps),
- x2 = solve(fx, dfx, 0, eps),
- x3 = solve(fx, dfx, 2, eps);
- std::cout << "x1 = " << x1 << std::endl <<
- "x2 = " << x2 << std::endl <<
- "x3 = " << x3 << std::endl;
- std::cout << "f(x1) = " << fx(x1) << std::endl <<
- "f(x2) = " << fx(x2) << std::endl <<
- "f(x3) = " << fx(x3) << std::endl;
- return 0;
- }
- float solve(float (*fx)(float), float (*dfx)(float), float x0, const float eps) {
- float x = x0;
- while (std::abs(fx(x)) > eps) {
- if (dfx(x) == 0 || fx(x) * fx(x + eps * (x - fx(x) / dfx(x) - x > 0 ? 1.f : -1.f)) < 0) {
- break;
- }
- x -= fx(x) / dfx(x);
- }
- return x;
- }
- float fx(float x) {
- return (x * x * x) + (3 * x * x) + (-8 * x) + (1);
- }
- float dfx(float x) {
- return (3 * x * x) + (6 * x) + (-8);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement