Skip to content

Instantly share code, notes, and snippets.

@mahenzon
Created June 2, 2023 18:10
Show Gist options
  • Save mahenzon/e3fe2963671c0740ad9df8143bf76a4a to your computer and use it in GitHub Desktop.
Save mahenzon/e3fe2963671c0740ad9df8143bf76a4a to your computer and use it in GitHub Desktop.
Equation Root Finder using Bisection Method
//
// Created by Suren Khorenyan on 02.06.2023.
//
#include <iostream>
#include <cmath>
double equation(double a, double b, double x) {
return a * pow(x, 3) + b * x - 1;
}
double findRoot(double a, double b, double left, double right, double epsilon) {
double middle, middleValue;
while (std::abs(right - left) > epsilon) {
middle = (left + right) / 2.0;
middleValue = equation(a, b, middle);
if (middleValue == 0.0)
return middle;
if (equation(a, b, left) * middleValue < 0.0)
right = middle;
else
left = middle;
}
return middle;
}
int main() {
double a, b, epsilon;
std::cout << "Enter the value for a: ";
std::cin >> a;
std::cout << "Enter the value for b: ";
std::cin >> b;
std::cout << "Enter the value for epsilon (tolerance): ";
std::cin >> epsilon;
double left, right;
std::cout << "Enter the left boundary: ";
std::cin >> left;
std::cout << "Enter the right boundary: ";
std::cin >> right;
double root = findRoot(a, b, left, right, epsilon);
std::cout << "The root of the equation " << a << "x^3 + " << b << "x - 1 = 0 ";
std::cout << "in the interval [" << left << ", " << right << "] is: " << root << std::endl;
return 0;
}
@mahenzon
Copy link
Author

mahenzon commented Jun 2, 2023

Run example:

Enter the value for a: 2
Enter the value for b: 3
Enter the value for epsilon (tolerance): 0.0001
Enter the left boundary: 0
Enter the right boundary: 1
The root of the equation 2x^3 + 3x - 1 = 0 in the interval [0, 1] is: 0.312927

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment