fork download
  1. // Assignment – 01
  2. // Tanmoy Debnath (21203050); SL- 17
  3. #include <iostream>
  4. #include <cmath>
  5. #include <cstdlib>
  6. using namespace std;
  7. // Define the polynomial function
  8. double Polynomial(double x, double a, double b, double c, double d, double e) {
  9. return a * pow(x, 4) + b * pow(x, 3) + c * pow(x, 2) + d * x + e;
  10. }
  11.  
  12. // Function to find the root using the False Position method
  13. double FalsePosition(double a, double b, double c, double d, double e, double p, double q, int n) {
  14. double fp = Polynomial(p, a, b, c, d, e);
  15. double fq = Polynomial(q, a, b, c, d, e);
  16.  
  17. if (fp * fq >= 0) {
  18. throw "The values of f(p) and f(q) should have opposite signs.";
  19. }
  20.  
  21. double root = 0;
  22. double precision = pow(10, -n);
  23.  
  24. while (fabs(q - p) >= precision) {
  25. root = (p * fq - q * fp) / (fq - fp);
  26.  
  27. double fr = Polynomial(root, a, b, c, d, e);
  28.  
  29. if (fabs(fr) < precision) {
  30. break;
  31. }
  32.  
  33. if (fp * fr < 0) {
  34. q = root;
  35. fq = fr;
  36. } else {
  37. p = root;
  38. fp = fr;
  39. }
  40. }
  41.  
  42. return round(root * pow(10, n)) / pow(10, n); // Round to n decimal places
  43. }
  44.  
  45. int main() {
  46. double a, b, c, d, e, p, q;
  47. int n;
  48.  
  49. cout << "Enter co-efficients of the polynomial f(x) = ax^4 + bx^3 + cx^2 + dx + e:" << endl;
  50. cout << "a: ";
  51. cin >> a;
  52. cout << "b: ";
  53. cin >> b;
  54. cout << "c: ";
  55. cin >> c;
  56. cout << "d: ";
  57. cin >> d;
  58. cout << "e: ";
  59. cin >> e;
  60.  
  61. cout << "\nEnter interval [p, q] where the root lies:" << endl;
  62. cout << "p: ";
  63. cin >> p;
  64. cout << "q: ";
  65. cin >> q;
  66.  
  67. cout << "\nEnter number of decimal places for the root: ";
  68. cin >> n;
  69.  
  70. try {
  71. double root = FalsePosition(a, b, c, d, e, p, q, n);
  72. cout << "\nRoot found: " << root << endl;
  73. } catch (const char* msg) {
  74. cout << "\nError: " << msg << endl;
  75. }
  76.  
  77. return 0;
  78. }
  79.  
Success #stdin #stdout 0.01s 5300KB
stdin
 
stdout
Enter co-efficients of the polynomial f(x) = ax^4 + bx^3 + cx^2 + dx + e:
a: b: c: d: e: 
Enter interval [p, q] where the root lies:
p: q: 
Enter number of decimal places for the root: 
Error: The values of f(p) and f(q) should have opposite signs.