Newton
unknown
plain_text
a month ago
2.7 kB
1
Indexable
Never
#include <bits/stdc++.h> using namespace std; 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; } 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; cout << setprecision(6) << fixed; 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); } 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; cout << "Newton-Raphson Method for Multiple Roots" << 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; } x1 = x0 - f0 / g0; if (fabs(evaluatePolynomial(coeffs, x1)) <= e) { 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; } x0 = x1; step = step + 1; } } sort(roots.begin(), roots.end()); cout << endl << "All unique roots found: " << endl; for (double root : roots) { cout << "Root: " << root << endl; } return 0; }
Leave a Comment