numerical 4
unknown
plain_text
a year ago
3.4 kB
15
Indexable
#include <bits/stdc++.h>
using namespace std;
/* Function to evaluate the polynomial at a given point */
double evaluatePolynomial(const vector<double>& coeffs, double x) {
double result = 0.0;
int n = coeffs.size();
for (int i = 0; i < n; ++i) {
result += coeffs[i] * pow(x, n - 1 - i);
}
return result;
}
/* Function to evaluate the derivative of the polynomial at a given point */
double evaluatePolynomialDerivative(const vector<double>& coeffs, double x) {
double result = 0.0;
int n = coeffs.size();
for (int i = 0; i < n - 1; ++i) {
result += coeffs[i] * (n - 1 - i) * pow(x, n - 2 - i);
}
return result;
}
int main() {
vector<double> coeffs;
double x0, x1, f0, g0, e;
int step, N;
double startInterval, endInterval, intervalStep;
vector<double> roots;
/* Setting precision and writing floating point values in fixed-point notation. */
cout << setprecision(6) << fixed;
/* Input the polynomial */
int degree;
cout << "Enter the degree of the polynomial: ";
cin >> degree;
cout << "Enter the coefficients of the polynomial (highest degree to constant term):" << endl;
for (int i = 0; i <= degree; ++i) {
double coeff;
cin >> coeff;
coeffs.push_back(coeff);
}
/* Inputs */
cout << "Enter tolerable error: ";
cin >> e;
cout << "Enter maximum iterations: ";
cin >> N;
cout << "Enter start of interval: ";
cin >> startInterval;
cout << "Enter end of interval: ";
cin >> endInterval;
cout << "Enter interval step (small value like 0.1): ";
cin >> intervalStep;
/* Implementing Newton-Raphson Method for each guess in the interval */
cout << endl << "*********************" << endl;
cout << "Newton-Raphson Method for Multiple Roots" << endl;
cout << "*********************" << endl;
for (double guess = startInterval; guess <= endInterval; guess += intervalStep) {
x0 = guess;
step = 1;
while (step <= N) {
g0 = evaluatePolynomialDerivative(coeffs, x0);
f0 = evaluatePolynomial(coeffs, x0);
if (g0 == 0.0) {
break; // Skip to next guess if derivative is zero
}
x1 = x0 - f0 / g0;
if (fabs(evaluatePolynomial(coeffs, x1)) <= e) {
// Check if this root is close to any already found root
bool isUnique = true;
for (double root : roots) {
if (fabs(root - x1) < e) {
isUnique = false;
break;
}
}
if (isUnique) {
roots.push_back(x1);
cout << "Found root: x = " << x1 << " with f(x) = " << evaluatePolynomial(coeffs, x1) << endl;
}
break; // Exit the loop once root is found
}
x0 = x1;
step = step + 1;
}
}
// Sort and display all unique roots found
sort(roots.begin(), roots.end());
cout << endl << "All unique roots found: " << endl;
for (double root : roots) {
cout << "Root: " << root << endl;
}
return 0;
}
Editor is loading...
Leave a Comment