Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using namespace std;
- #include <cstdio>
- #include <cmath>
- #include <vector>
- double function(double x) {
- return log(x) - x + 5;
- }
- double derivative(double x) {
- return 1.0 / x - 1;
- }
- vector<int> iteration(double X, double step) {
- double a = X, b = X + step;
- double da = derivative(a), db = derivative(b), m, M;
- if (abs(da) >= abs(db)) {
- M = da;
- m = db;
- } else {
- M = db;
- m = da;
- }
- double q = 1 - abs(m / M);
- vector<int> iterations;
- printf("| eps | equation root | accuracy estimation I |\n");
- for (double eps = 1E-2; eps > 1E-14; eps *= 1E-3) {
- double t = (1 - q) / q * eps;
- double x = (a + b) / 2, x1 = x;
- int count = 0;
- do {
- x = x1;
- x1 = x - function(x) / M;
- count++;
- } while (abs(x1 - x) > t);
- iterations.push_back(count);
- printf("| %.0E | %13.19f | %.19f |\n", eps, x1, abs(abs(x1) - abs(x)) * q / (1 - q));
- }
- printf("\n");
- return iterations;
- }
- vector<int> secant(double A, double B, double step) {
- vector<int> iterations;
- printf("| eps | equation root | accuracy estimation S |\n");
- for (double eps = 1E-2; eps > 1E-14; eps *= 1E-3) {
- double a = A, b = B, x;
- int count = 0;
- while (fabs(b - a) >= eps) {
- x = a + (function(b) * (b - a)) / (function(b) - function(a));
- if (function(a) * function(x) < 0) {
- b = x;
- } else if (function(x) * function(b) < 0) {
- a = x;
- }
- count++;
- }
- iterations.push_back(count);
- printf("| %.0E | %13.19f | %.19f |\n", eps, x, abs((b - a) * 0.5));
- }
- printf("\n");
- return iterations;
- }
- vector<double> find_x(double a, double b, double step) {
- vector<double> X;
- for (double x = a; x <= b; x += step) {
- if (function(x) * function(x + step) < 0) {
- X.push_back(x);
- }
- }
- return X;
- }
- int main() {
- double step = 0.1;
- double a = 6.5;
- double b = 7.6;
- auto X = find_x(a, b, step)[0];
- vector<int> ii = iteration(X, step);
- vector<int> ib = secant(a, b, step);
- printf("| eps | iteration count | secant count |\n");
- int index = 0;
- for (double eps = 1E-2; eps > 1E-14; eps *= 1E-3, index++) {
- printf("| %.0E | %15i | %12i |\n", eps, ii[index], ib[index]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement