33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to determine the roots by using Bisection Method / Regula-Falsi Method / Newton Raphson Method.

Published on Dec 22, 2025
#include <iostream>
#include <cmath>
using namespace std;

// Define the function f(x)
double f(double x) {
    return x*x*x - x - 2;
}

// Define derivative for Newton-Raphson
double df(double x) {
    return 3*x*x - 1;
}

int main() {
    int choice;
    double a, b, x, x0, x1, eps = 0.0001;

    cout << "Choose Method:\n";
    cout << "1. Bisection Method\n";
    cout << "2. Regula-Falsi Method\n";
    cout << "3. Newton-Raphson Method\n";
    cout << "Enter choice: ";
    cin >> choice;

    switch (choice) {

    // ---------------- Bisection Method ----------------
    case 1:
        cout << "Enter initial guesses a and b: ";
        cin >> a >> b;

        if (f(a) * f(b) >= 0) {
            cout << "Invalid initial guesses." << endl;
            return 0;
        }

        do {
            x = (a + b) / 2;
            if (f(a) * f(x) < 0)
                b = x;
            else
                a = x;
        } while (fabs(f(x)) > eps);

        cout << "Root by Bisection Method = " << x << endl;
        break;

    // ---------------- Regula-Falsi Method ----------------
    case 2:
        cout << "Enter initial guesses a and b: ";
        cin >> a >> b;

        if (f(a) * f(b) >= 0) {
            cout << "Invalid initial guesses." << endl;
            return 0;
        }

        do {
            x = (a*f(b) - b*f(a)) / (f(b) - f(a));
            if (f(a) * f(x) < 0)
                b = x;
            else
                a = x;
        } while (fabs(f(x)) > eps);

        cout << "Root by Regula-Falsi Method = " << x << endl;
        break;

    // ---------------- Newton-Raphson Method ----------------
    case 3:
        cout << "Enter initial guess x0: ";
        cin >> x0;

        do {
            x1 = x0 - f(x0) / df(x0);
            x0 = x1;
        } while (fabs(f(x1)) > eps);

        cout << "Root by Newton-Raphson Method = " << x1 << endl;
        break;

    default:
        cout << "Invalid choice!" << endl;
    }

    return 0;
}

Documentation

Input

Choose Method:
1. Bisection Method
2. Regula-Falsi Method
3. Newton-Raphson Method
Enter choice: 1
Enter initial guesses a and b: 1 2

Output
Root by Bisection Method = 1.52138


✔ Bisection Method
✔ Regula–Falsi (False Position) Method
✔ Newton–Raphson Method

Problem Assumption

Let the equation be:

f(x)=x3−x−2

(This equation has a real root near x ≈ 1.52)