Problem C. Jane's Flower Shop - APAC Test 2017 Round A(牛顿迭代)

题目链接

https://code.google.com/codejam/contest/11274486/dashboard#s=p2

题意

给一个方程,求解

思路

二分

一时脑残写了个牛顿迭代,之前纠结于二分函数不一定单调,其实只要保证解单调即可:因为 r [1,1]之间只有1个解,且 f(1)>0 ,所以 r 左边f(r)>0 r 右边f(r)<0,根据此性质进行二分即可

牛顿迭代法

牛顿迭代法wiki
所以我们只需要去逼近解即可。
我们令 x=r+1
xn+1=xn+f(xn)f(xn)
于是,计算出 f(xn) f(xn) 即可

代码

#include <bits/stdc++.h>

using namespace std;

inline int in() {int x; scanf("%d", &x); return x;}
#define pr(x) {cout << #x << ' ' << x << endl;}
#define LL long long

const int maxn = 105;
double c[maxn], a[maxn];
int n;

void read() {
    n = in();
    for (int i = 0; i <= n; i++) scanf("%lf", &c[i]);
    c[0] = -c[0];
}

void get_derivative() {
    for (int i = 0; i <= n; i++) {
        a[i] = (double)(n - i) * c[i];
    }
}

double quick_pow(double x, int n) {
    double res = 1;
    while (n) {
        if (n & 1) res *= x;
        x *= x;
        n >>= 1;
    }
    return res;
}

double cal(double x, int sta) {
    if (sta) {
        double res = 0;
        for (int i = 0; i < n; i++) {
            res += a[i] * quick_pow(x, n - i - 1);
        }
        return res;
    } else {
        double res = 0;
        for (int i = 0; i <= n; i++) {
            res += c[i] * quick_pow(x, n - i);
        }
        return res;
    }
}

double newton() {
    double x = 2.0;
    while (fabs(cal(x, 0)) > 1e-12) {
        double t = x - cal(x, 0) / cal(x, 1);
        if (x - t < 1e-10) return x - 1.0;
        x = t;
    }
    return x - 1.0;
}

int main() {
    int T = in(), kase = 0;
    while (T--) {
        read();
        get_derivative();
        double res = newton();
        printf("Case #%d: %.12lf\n", ++kase, res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值