Untitled
unknown
plain_text
a year ago
2.2 kB
16
Indexable
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
// ---------------- Functions & Derivatives ---------------- //
// (a) f(x) = x^3 - 2x^2 - 5
double f1(double x) {
return x*x*x - 2*x*x - 5;
}
double f1_derivative(double x) {
return 3*x*x - 4*x;
}
// (b) f(x) = x^3 + 4.001x^2 + 4.002x + 1.101
double f2(double x) {
return x*x*x + 4.001*x*x + 4.002*x + 1.101;
}
double f2_derivative(double x) {
return 3*x*x + 8.002*x + 4.002;
}
// (c) f(x) = x^5 - x^4 + 2x^3 - 3x^2 + x - 4
double f3(double x) {
return pow(x,5) - pow(x,4) + 2*pow(x,3) - 3*x*x + x - 4;
}
double f3_derivative(double x) {
return 5*pow(x,4) - 4*pow(x,3) + 6*x*x - 6*x + 1;
}
// ---------------- Newton-Raphson Method ---------------- //
double newtonRaphson(double (*f)(double), double (*df)(double), double x0,
double tol = 1e-4, int maxIter = 100) {
int iter = 0;
double x = x0;
while (iter < maxIter) {
double fx = f(x);
double dfx = df(x);
if (fabs(dfx) < 1e-12) { // avoid division by 0
cout << "Derivative too small. Stopping.\n";
break;
}
double x1 = x - fx/dfx;
if (fabs(x1 - x) < tol) {
cout << "Iterations: " << iter+1 << endl;
return x1;
}
x = x1;
iter++;
}
cout << "Max iterations reached.\n";
return x;
}
// ---------------- Main ---------------- //
int main() {
cout << fixed << setprecision(6);
cout << "Root of (a) f(x) = x^3 - 2x^2 - 5:" << endl;
double root1 = newtonRaphson(f1, f1_derivative, 2.0); // initial guess near expected root
cout << "Approximate root = " << root1 << endl << endl;
cout << "Root of (b) f(x) = x^3 + 4.001x^2 + 4.002x + 1.101:" << endl;
double root2 = newtonRaphson(f2, f2_derivative, -0.5); // initial guess
cout << "Approximate root = " << root2 << endl << endl;
cout << "Root of (c) f(x) = x^5 - x^4 + 2x^3 - 3x^2 + x - 4:" << endl;
double root3 = newtonRaphson(f3, f3_derivative, 1.5); // initial guess
cout << "Approximate root = " << root3 << endl;
return 0;
}Editor is loading...
Leave a Comment