Friday, September 29, 2023

C++ program to find the root of a function using Newton's method

In this program:
f(x) is the function for which you want to find the root, and 
df(x) is its derivative. 
You can replace them with your own function and its derivative.
The newton function implements Newton's method to find the root within a specified tolerance and a maximum number of iterations.
In the main function, you can set the initial guess (initial_guess), tolerance (tolerance), and the maximum number of iterations (max_iterations) to control the root-finding process.

Compile and run this program, and it will find an approximate root of the function using Newton's method. 


#include <iostream>
#include <cmath>

using namespace std;

// Define the function for which we want to find the root
double f(double x) {
    return x * x - 4; // Example function: f(x) = x^2 - 4
}

// Define the derivative of the function
double df(double x) {
    return 2 * x; // Derivative of f(x) = x^2 - 4 is f'(x) = 2x
}

// Newton's method to find the root of a function
double newton(double initial_guess, double tol, int max_iterations) {
    double x = initial_guess;
    int iterations = 0;

    while (iterations < max_iterations) {
        double fx = f(x);
        double dfx = df(x);

        if (abs(fx) < tol) {
            return x; // Found a root within tolerance
        }

        x = x - fx / dfx; // Newton's iteration formula
        iterations++;
    }

    cout << "Newton's method did not converge within the specified number of iterations." << endl;
    return NAN; // Not a number (indicating an error)
}

int main() {
    double initial_guess = 2.0; // Initial guess for the root
    double tolerance = 0.0001; // Tolerance for the solution
    int max_iterations = 100; // Maximum number of iterations

    double root = newton(initial_guess, tolerance, max_iterations);

    if (!isnan(root)) {
        cout << "Approximate root: " << root << endl;
    }

    return 0;
}

No comments:

Post a Comment

N-point Star in Microsoft Visual Studio Console App

#include <windows.h> #include <cmath> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,...