В общем, даны функции, и нужно методом бисекции и методом Ньютона правильно всё посчитать. Но вторая функции работает плохо, неправильно находит 0 в обоих методах. Я никак не могу понять, почему так
#include <iostream>
#include <cmath>
using namespace std;
float f1(float x) {
return pow(0.07, 1 / 3) - 2 * x + atan(sqrt(x));
}
float f2(float x)
{
return log(1 + x) - 0.95*sin(x) + 6 / 7 - x;
}
void m1(float a, float b, float E, float& x, int& i, float (*f) (float)){
i = 0;
while (fabs(a - b) >= E)
{
x = (a + b) / 2;
if ((*f) (x) * (*f) (b) > 0)
b = x;
else a = x;
i++;
}
}
void m2(float a, float b, float E, float& x2, int& i, float (*f) (float)){
float x1, ff;
x2 = (a + b) / 2; i = 0;
do {x1 = x2;
ff = ((*f) (x1 + E / 2) - (*f) (x1 - E / 2)) / E;
x2 = x1 - (*f) (x1) / ff;
i++;
cout << "Iteration " << i << ": x=" << x2 << ", f(x)=" << (*f)(x2) << endl;
} while (fabs(x1 - x2) >= E); }
int main()
{
float a, b, E, x11, x12, x21, x22;
int i11, i12, i21, i22;
cin >> a >> b >> E;
m1(a, b, E, x11, i11, f1);
m2(a, b, E, x12, i12, f1);
cout << " x11=" << x11 << " x12=" << x12<<endl;
cout << "i11=" << i11 << "i12=" << i12<<endl;
m1(a, b, E, x21, i21, f2);
m2(a, b, E, x22, i22, f2);
cout << " x21=" << x21 << " x22=" << x22<<endl;
cout << " i21=" << i21 << " i22=" << i22<<endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
float f1(float x) {
return pow(0.07, 1 / 3) - 2 * x + atan(sqrt(x));
}
float f2(float x)
{
return log(1 + x) - 0.95*sin(x) + 6 / 7 - x;
}
void m1(float a, float b, float E, float& x, int& i, float (*f) (float)){
i = 0;
while (fabs(a - b) >= E)
{
x = (a + b) / 2;
if ((*f) (x) * (*f) (b) > 0)
b = x;
else a = x;
i++;
}
}
void m2(float a, float b, float E, float& x2, int& i, float (*f) (float)){
float x1, ff;
x2 = (a + b) / 2; i = 0;
do {x1 = x2;
ff = ((*f) (x1 + E / 2) - (*f) (x1 - E / 2)) / E;
x2 = x1 - (*f) (x1) / ff;
i++;
cout << "Iteration " << i << ": x=" << x2 << ", f(x)=" << (*f)(x2) << endl;
} while (fabs(x1 - x2) >= E); }
int main()
{
float a, b, E, x11, x12, x21, x22;
int i11, i12, i21, i22;
cin >> a >> b >> E;
m1(a, b, E, x11, i11, f1);
m2(a, b, E, x12, i12, f1);
cout << " x11=" << x11 << " x12=" << x12<<endl;
cout << "i11=" << i11 << "i12=" << i12<<endl;
m1(a, b, E, x21, i21, f2);
m2(a, b, E, x22, i22, f2);
cout << " x21=" << x21 << " x22=" << x22<<endl;
cout << " i21=" << i21 << " i22=" << i22<<endl;
return 0;
}