Created
June 2, 2023 18:10
-
-
Save mahenzon/e3fe2963671c0740ad9df8143bf76a4a to your computer and use it in GitHub Desktop.
Equation Root Finder using Bisection Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run example: