百练2868:牛顿迭代

传送门:http://bailian.openjudge.cn/practice/2868/

【题解】

牛顿迭代:x[n+1] = x[n] - f(x[n])/f'(x[n])

这样迭代下去就能求f(x)的零点了。

对于本题只需要乱搞就行了。

# include <math.h>
# include <stdio.h>
# include <iomanip>
# include <string.h>
# include <iostream>
# include <algorithm>
// # include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const int M = 5e5 + 10;
const int mod = 1e9+7;

# define RG register
# define ST static

int times;
double n, x, px;

int main() {
    while(cin >> n) {
        px = 1.0; times = 0;
        while(1) {
            ++ times;
            x = (px + (double)n/px) / 2.0;
            if(fabs(px - x) <= 1e-6) break;
            px = x;
        }
        x = fabs(x);
        cout << times << ' ' << setprecision(2) << setiosflags(ios::fixed) << x << endl;
    }
    return 0;
}
View Code

 

posted @ 2017-05-16 22:08  Galaxies  阅读(221)  评论(0编辑  收藏  举报