StoneHaos

alexey_mod1

Mar 1st, 2021
430
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <math.h>
  3. #include <utility>
  4. using namespace std;
  5.  
  6. typedef pair<double, double> cut;
  7. const double dx = 0.0001;
  8.  
  9. double f(double x) {
  10.     return pow(sin(x), 2.0) / (2.0 + sin(x));
  11. }
  12.  
  13. double f_(double x) {
  14.     return (f(x + dx) - f(x)) / dx;
  15. }
  16.  
  17. double f__(double x) {
  18.     return (f_(x + dx) - f_(x)) / dx;
  19. }
  20.  
  21. cut Sven(double x0, double h) {
  22.     int k = 1;
  23.     double x1, x2;
  24.     if (f(x0 - h) >= f(x0) && f(x0) >= f(x0 + h)) {
  25.         x1 = x0 + h;
  26.     }
  27.     else if (f(x0 - h) <= f(x0) && f(x0) <= f(x0 + h)) {
  28.         x1 = x0 - h;
  29.         h = -h;
  30.     }
  31.     else if (f(x0 - h) <= f(x0) && f(x0) >= f(x0 + h)) {
  32.         x1 = x0 + h;
  33.     }
  34.     else {
  35.         return cut(x0 - h, x0 + h);
  36.     }
  37.  
  38.     x2 = x1;
  39.     x1 = x0;
  40.     do {
  41.         x0 = x1;
  42.         x1 = x2;
  43.         x2 = x1 + pow(2.0, k * 1.0) * h;
  44.         k++;
  45.     } while (f(x2) <= f(x1));
  46.  
  47.     if (h > 0) {
  48.         return cut(x0, x2);
  49.     }
  50.     else {
  51.         return cut(x2, x0);
  52.     }
  53. }
  54.  
  55. double Newton(cut c, double eps) {
  56.     double x0, x1 = (c.first + c.second) / 2.0;
  57.     do {
  58.         x0 = x1;
  59.         x1 = x0 - f_(x0) / f__(x0);
  60.     } while (abs(x1 - x0) > eps);
  61.     return x1;
  62. }
  63.  
  64.  
  65. ostream& operator<<(ostream& out, cut c) {
  66.     out << "(" << c.first << "," << c.second << ")";
  67.     return out;
  68. }
  69.  
  70. int main(void) {
  71.     cut a = Sven(4, 0.1);
  72.     cout << a << endl;
  73.     cout << Newton(a, 0.001) << endl;
  74.     return 0;
  75. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×