Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <cmath>
- #include <vector>
- double a = -2;
- double b = 2;
- double function(double x) {
- return sin(2.0 * x) + pow(cos(x), 2) - x * 0.5;
- }
- double derivative(double x) {
- return 2.0 * cos(2.0 * x) - 2.0 * sin(x) * cos(x) - 0.5;
- }
- std::vector<int> iteration(double x, double step) {
- std::vector<int> iterations;
- double a = x;
- double b = x + step;
- double da = derivative(a);
- double db = derivative(b);
- double alpha = 1.0 / ((abs(da) > abs(db)) ? da : db);
- double q = 1.0 - abs((abs(da) > abs(db) ? (db / da) : (da / db)));
- double k = 1.0 / q - 1.0;
- printf("| eps | equation root | accuracy estimation I |\n");
- for (double eps = 1E-2; eps > 1E-14; eps *= 1E-3) {
- double sigma = k * eps;
- double x0 = (a + b) * 0.5;
- double x1 = x0;
- int count = 0;
- do {
- x0 = x1;
- x1 = x0 - alpha * function(x0);
- count++;
- } while (abs(x1 - x0) > sigma);
- iterations.push_back(count);
- printf("| %.0E | %21.18f | %.15E |\n", eps, x1, abs(x1 - x0) / k);
- }
- printf("\n");
- return iterations;
- }
- std::vector<int> bisection(double x, double step) {
- std::vector<int> iterations;
- printf("| eps | equation root | accuracy estimation B |\n");
- for (double eps = 1E-2; eps > 1E-14; eps *= 1E-3) {
- double a = x;
- double b = x + step;
- int count = 0;
- do {
- double c = (a + b) * 0.5;
- double fa = function(a);
- double fb = function(b);
- double fc = function(c);
- if (fa * fc < 0) b = c;
- if (fb * fc < 0) a = c;
- count++;
- } while (abs(b - a) >= 2 * eps);
- iterations.push_back(count);
- printf("| %.0E | %21.18f | %.15E |\n", eps, (a + b) * 0.5, abs((b - a) * 0.5));
- }
- printf("\n");
- return iterations;
- }
- std::vector<double> findroots() {
- std::vector<double> X;
- for (double x = a; x <= b; x += 0.1) {
- if (function(x) * function(x + 0.1) < 0) {
- X.push_back(x);
- }
- }
- return X;
- }
- int main() {
- auto roots = findroots();
- auto ii = iteration(roots[0], 0.1);
- for (int i = 1; i < 3; i++) {
- iteration(roots[i], 0.1);
- }
- auto ib = bisection(roots[0], 0.1);
- for (int i = 1; i < 3; i++) {
- bisection(roots[i], 0.1);
- }
- printf("| eps | iteration | bisection |\n");
- int index = 0;
- for (double eps = 1E-2; eps > 1E-14; eps *= 1E-3, index++) {
- printf("| %.0E | %9i | %9i |\n", eps, ii[index], ib[index]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement