Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- #include <utility>
- using namespace std;
- typedef pair<double, double> cut;
- const double dx = 0.0001;
- double f(double x) {
- return pow(sin(x), 2.0) / (2.0 + sin(x));
- }
- double f_(double x) {
- return (f(x + dx) - f(x)) / dx;
- }
- double f__(double x) {
- return (f_(x + dx) - f_(x)) / dx;
- }
- cut Sven(double x0, double h) {
- int k = 1;
- double x1, x2;
- if (f(x0 - h) >= f(x0) && f(x0) >= f(x0 + h)) {
- x1 = x0 + h;
- }
- else if (f(x0 - h) <= f(x0) && f(x0) <= f(x0 + h)) {
- x1 = x0 - h;
- h = -h;
- }
- else if (f(x0 - h) <= f(x0) && f(x0) >= f(x0 + h)) {
- x1 = x0 + h;
- }
- else {
- return cut(x0 - h, x0 + h);
- }
- x2 = x1;
- x1 = x0;
- do {
- x0 = x1;
- x1 = x2;
- x2 = x1 + pow(2.0, k * 1.0) * h;
- k++;
- } while (f(x2) <= f(x1));
- if (h > 0) {
- return cut(x0, x2);
- }
- else {
- return cut(x2, x0);
- }
- }
- double Newton(cut c, double eps) {
- double x0, x1 = (c.first + c.second) / 2.0;
- do {
- x0 = x1;
- x1 = x0 - f_(x0) / f__(x0);
- } while (abs(x1 - x0) > eps);
- return x1;
- }
- ostream& operator<<(ostream& out, cut c) {
- out << "(" << c.first << "," << c.second << ")";
- return out;
- }
- int main(void) {
- cut a = Sven(4, 0.1);
- cout << a << endl;
- cout << Newton(a, 0.001) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement