Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using namespace std;
- #include <cstdio>
- #include <cmath>
- double F(double x) {
- return x * x * x * x + 2 * x * x * x + sin(x) + 0.5;
- }
- double f(double x) {
- return 2 * (2 * x + 3) * x * x + cos(x);
- }
- double f2(double x) {
- return 12 * x * (x + 1) - sin(x);
- }
- int *iteration(double root, double step) {
- double a = root;
- double b = root + step;
- double da = f(a);
- double db = f(b), m, M;
- abs(da) > abs(db) ? (M = da, m = db) : (M = db, m = da);
- double alpha = 1 / M, q = 1 - abs(m / M);
- int *iters = new int[3], *iters_ptr = iters;
- printf("| eps | equation root | accuracy estimation for I |\n");
- for (double eps = 1e-2; eps > 1e-14; eps *= 1e-3) {
- double sigma = (1 - q) / q * eps, x = (a + b) / 2, x1 = x;
- int iterations = 0;
- do {
- iterations++;
- x = x1;
- x1 = x - alpha * F(x);
- } while (abs(x1 - x) > sigma);
- *iters_ptr++ = iterations;
- double accuracy = abs(abs(x1) - abs(x)) * q / (1 - q);
- printf("| %.0e | %13.10f | %25.23f |\n", eps, x1, accuracy);
- }
- printf("\n");
- return iters;
- }
- int *tangent(double root, double step) {
- int *iters = new int[3], *iters_ptr = iters;
- double a = root;
- double b = root + step;
- double m = fabs(f(a));
- for (double x = a; x < b; x += 0.001) {
- double y = fabs(f(x));
- if (m >= y) m = y;
- }
- double x1 = F(a) * f2(a) ? a : b;
- printf("| eps | equation root | accuracy estimation for D |\n");
- for (double eps = 1e-2; eps > 1e-14; eps *= 1e-3) {
- double x = x1;
- int iterations = 0;
- while (fabs(F(x))/m > eps) {
- iterations++;
- x -= F(x) / f(x);
- }
- *iters_ptr++ = iterations;
- double accuracy = fabs(F(x)) / m;
- printf("| %.0e | %13.10f | %25.23f |\n", eps, x, accuracy);
- }
- printf("\n");
- return iters;
- }
- int main() {
- double step = 0.5;
- double a = -3;
- double b = 0;
- double roots[2], *roots_ptr = roots;
- for (double x = a; x < b; x += step) {
- if (F(x) * F(x + step) < 0) {
- *roots_ptr++ = x;
- }
- }
- int *iters_i = iteration(roots[0], step);
- for (int i = 1; i < 3; i++) {
- iteration(roots[i], step);
- }
- int *iters_d = tangent(roots[0], step);
- for (int i = 1; i < 3; i++) {
- tangent(roots[i], step);
- }
- printf("| eps | iteration count for I | iteration count for D |\n");
- for (double eps = 1e-2; eps > 1e-14; eps *= 1e-3) {
- printf("| %.0e | %21i | %21i |\n", eps, *iters_i++, *iters_d++);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement