using namespace std;
// Tenglama x-cos(x)
// Birinchi tartibli hosila 1+sin(x)
// Ikkinchi tartibli hosila cos(x)
//2-Tenglama pow(x, 3) - 3 * x -1 (0, 1)
//Birinchi tartibli hosila 3 * pow(x, 2) - 3
//Ikkinchi tartibli hosila 6 * x
double function(double x) {
// return x-cos(x);
return pow(x, 3) - 3 * x -1;
}
double first_derivative (double x) {
// return 1+sin(x)
return 3 * pow(x, 2) - 3;
}
double second_derivative (double x) {
// return cos(x)
return 6 * x ;
}
double vatarlarMethod(double a, double b, double epsilon) {
double c;
int steps = 0;
do
{
c = a - function(a) * (b - a) / (function(b) - function(a));
(function(a) * function(c) > 0) ? a = c : b = c;
steps++;
} while (fabs(function(c)) >= epsilon);
cout << "Yechim topish uchun zarur bo'lgan qadamlar soni: " << steps << endl;
return c;
}
int main()
{
// double a = 0, b = 1, epsilon = 0.001;
double a = 0, b = 1, epsilon = 0.001;
if (function(a) * function(b) >= 0 || first_derivative(a) * first_derivative(b) <= 0) {
cout << "Tenglama bu oraliqda yechimga ega emas!" << endl;
}
double result = vatarlarMethod(a, b, epsilon);
cout << "Tenglamaning vatarlar usulida hisoblangan ildizi: " << result << endl;
return 0;
}
Urinmalar (Nyuton) usuli
#include
#include
using namespace std;
// Tenglama x -cos(x)=0
// Birinchi tartibli hosila 1+sin(x)
// Ikkinchi tartibli hosila cos(x)
//2-Tenglama pow(x, 3) + 3 * x -1 = 0 (0, 1)
//Birinchi tartibli hosila 3 * pow(x, 2) +3
//Ikkinchi tartibli hosila 6 * x
double function(double x) {
// return x-cos(x);
return pow(x, 3) + 3 * x -1;
}
double first_derivative (double x) {
// return 1+sin(x);
return 3 * pow(x, 2) +3;
}
double second_derivative (double x) {
// return cos(x);
return 6 * x ;
}
double NyutonMethod(double a, double b, double epsilon) {
double c;
int steps = 0;
if (function(a) * second_derivative(a) > 0)
c = a;
else
c = b;
do
{
c = c - function(c) / first_derivative(c);
steps++;
} while (fabs(function(c)) >= epsilon);
cout << "Yechim topish uchun zarur bo'lagan qadamlar soni: " << steps << endl;
return c;
}
int main()
{
// double a = 0, b = 1, epsilon = 0.001;
double a = 0, b = 1, epsilon = 0.001;
if (function(a) * function(b) >= 0 || first_derivative(a) * first_derivative(b) <= 0) {
cout << "Tenglama bu oraliqda yechimga ega emas!" << endl;
}
double result = NyutonMethod(a, b, epsilon);
cout << "Tenglamaning Nuyuton usulida hisoblangan ildizi: " << result << endl;
return 0;
}