Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <ctype.h>
  6.  
  7. #include <algorithm>
  8. #include <vector>
  9. #include <map>
  10. #include <set>
  11. #include <string>
  12. #include <sstream>
  13. #include <queue>
  14. #include <iterator>
  15.  
  16. #include <iostream>
  17.  
  18.  
  19. using namespace std;
  20.  
  21.  
  22. int n=1;
  23.  
  24. // x^3 + 3x- 5;
  25.  
  26.  
  27. float functionValue(float x) {
  28.     float res;
  29.     float exp;
  30.  
  31.     exp = pow(x, 3);
  32.     res = (exp + (3*x*1.0)) - 5;
  33.  
  34.     return res;
  35. }
  36.  
  37. int main() {
  38. //    freopen("in.txt", "r", stdin);
  39. //    freopen("out.txt", "w", stdout);
  40.  
  41.     float x1, x2, x0, f0, f1, f2, Estop = 0.01;
  42.  
  43.     x1 = 1, x2 = 2;
  44.  
  45.     f1 = functionValue(x1);
  46.     f2 = functionValue(x2);
  47.  
  48.     if(f1*f2 > 0) {
  49.         cout << "X1 and X2 do not bracket any root!" << endl;
  50.         goto stop;
  51.     } else {
  52. step4:
  53.         x0 = (x1+x2) /2;
  54.         f0 =functionValue(x0);
  55.     }
  56.  
  57.     if(f1*f0 < 0) {
  58.         x2 = x0;
  59.     } else {
  60.         x1 = x0;
  61.         f1 = f0;
  62.     }
  63.  
  64.     if((x2-x1)/x2 < Estop) {
  65.  
  66.         x0 = (x1 + x2) / 2;
  67.         cout << "Root: " << x0 << endl;
  68.         goto stop;
  69.  
  70.     } else {
  71.         cout << "Iteration " << n++ <<": " << x0 << endl;
  72.         goto step4;
  73.     }
  74. stop:
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement