dmkozyrev

equations.cpp

Dec 2nd, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. /*
  2.     Методы решения нелинейных уравнений:
  3.         1.  Ньютона
  4.         2.  Бисекций
  5.         3.  Ппростых итераций
  6. */
  7.  
  8. #include <iostream>
  9. #include <cmath>
  10. #include <cstdio>
  11.  
  12. using namespace std;
  13.  
  14. //  ln(x+1)-2x^2+1=0
  15. //  ln(x+1)-2x^2+x+1=x
  16. //  ln(x+1)-(x-1)(2x+1) = x
  17.  
  18. // 2x^2-x-1=0
  19. // D=1+8 = 9 = 3^2
  20. // x1=(1+3)/4 = 1
  21. // x2=(1-3)/4 = -1/2
  22. // 2x^2-x-1=2(x-1)(x+1/2)=(x-1)(2x+1)
  23.  
  24. //  0.5*(log(x+1)+1)/x=x
  25.  
  26. inline double f(double x) {
  27. //  f(x) = 0
  28.     return log(x+1)-2*x*x+1;
  29. }
  30.  
  31. inline double df(double x) {
  32. //  f(x) = 0
  33.     return 1/fabs(x+1)-4*x;
  34. }
  35.  
  36. inline double g(double x) {
  37. //  x = g(x)
  38.     return 0.5*(log(x+1)+1)/x;
  39. }
  40.  
  41. double solve_bisection(double (*f)(double x), double a, double b, double eps, int limit) {
  42.     cout << "\tMethod of bisections:" << endl;
  43.     double x = 0.5*(a+b);
  44.     int count = 0;
  45.     while ( fabs( (*f)(x) ) > eps && count < limit) {
  46.         printf("%d:\t x = %0.9lf \t f(x) = %0.9lf\n", count, x, (*f)(x));
  47.         if ( (*f)(a)*(*f)(x) < 0 )
  48.             b = x;
  49.         else
  50.             a = x;
  51.         x = 0.5*(a+b);
  52.         ++count;
  53.     }
  54.     cout << endl;
  55.     return x;
  56. }
  57.  
  58. double solve_iteration(double (*f)(double x), double eps, int limit) {
  59.     cout << "\tMethod of simple iterations:" << endl;
  60.     double x = 1, y = (*f)(x);
  61.     int count = 0;
  62.     while (fabs(x - y) >= eps && count < limit) {
  63.         printf("%d:\t x = %0.9lf \t f(x) = %0.9lf\n", count, x, x-(*f)(x));
  64.         x = y;
  65.         y = (*f)(x);
  66.         count++;
  67.     }
  68.     cout << endl;
  69.     return x;
  70. }
  71.  
  72. double solve_neuton(double (*f)(double x), double (*df)(double x), double eps, double limit) {
  73.     cout << "\tMethod of Neuton:" << endl;
  74.     double x = 10, y = (*f)(x)/(*df)(x);
  75.     int count = 0;
  76.     while (fabs((*f)(x)) >= eps && count < limit) {
  77.         printf("%d:\t x = %0.9lf \t f(x) = %0.9lf\n", count, x, (*f)(x));
  78.         x -= y;
  79.         y = (*f)(x)/(*df)(x);
  80.         count++;
  81.     }
  82.     cout << endl;
  83.     return x;
  84. }
  85.  
  86. int main() {
  87.     double eps = 10e-9;
  88.     solve_bisection(f, 0.1, 10, eps, 1000);
  89.     solve_iteration(g, eps, 1000);
  90.     solve_neuton(f, df, eps, 1000);
  91.     return 0;
  92. }
Add Comment
Please, Sign In to add comment