double func(double x) {
return x * x * x - 3 * x * x + 5 * x + 1;
}
double func_derivative(double x) {
return 3 * x * x - 6 * x + 5;
}
double bisectionMethod(double a, double b, double epsilon) {
if (func(a) * func(b) >= 0) {
std::cout << "The function may not have a root in the given interval." << std::endl;
return 0;
}
double c;
int iteration = 0;
do {
c = (a + b) / 2;
if (func(c) == 0.0) {
break;
}
else if (func(a) * func(c) < 0) {
b = c;
}
else {
a = c;
}
iteration++;
} while (fabs(func(c)) > epsilon);
std::cout << "Bisection Method: ";
std::cout << "Root: " << c << ", Iterations: " << iteration << std::endl;
return c;
}
double newtonRaphsonMethod(double initial, double epsilon) {
double x = initial;
int iteration = 0;
while (fabs(func(x)) > epsilon) {
x = x - func(x) / func_derivative(x);
iteration++;
}
std::cout << "Newton-Raphson Method: ";
std::cout << "Root: " << x << ", Iterations: " << iteration << std::endl;
return x;
}
int main() {
double a = -10.0; // Boshlang'ich kesishma
double b = 10.0; // Oxirgi kesishma
double epsilon = 0.0001; // Toleransiya qiymati
bisectionMethod(a, b, epsilon);
newtonRaphsonMethod(a, epsilon);
return 0;
}
b) 2x-cosx=0 Algebraik va transtsendent tenglamalarni yechishda oraliqni teng ikkiga bo’lish,
#include
#include
double func(double x) {
return 2 * x - cos(x);
}
double func_derivative(double x) {
return 2 + sin(x);
}
double newtonRaphsonMethod(double initial, double epsilon) {
double x = initial;
int iteration = 0;
while (fabs(func(x)) > epsilon) {
x = x - func(x) / func_derivative(x);
iteration++;
}
std::cout << "Root: " << x << ", Iterations: " << iteration << std::endl;
return x;
}
int main() {
double initial = 0.0; // Boshlang'ich x qiymati
double epsilon = 0.0001; // Toleransiya qiymati
newtonRaphsonMethod(initial, epsilon);
return 0;
}