UVA 11881 Internal Rate of Return

来源:互联网 发布:smtp服务器端口25 编辑:程序博客网 时间:2024/06/03 15:59

     f(x)=c0+c1*(1+x)^(-1)+c2*(1+x)^(-2)+...+cn*(1+x)^(-n)=0;

保证c0<0,10000>c1...cn>0,求x在(-1,inf)的解。

求导后发现导函数在定义域上恒小于0,而x趋近于0+时f(x)无穷大,所以在定义域上恒有唯一解,直接二分判断答案..

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>using namespace std;typedef long long ll;const double inf=1e7;const double eps=1e-6;int n,m;double a[22];int dcmp(double x){    if (fabs(x)<eps) return 0;    else return x<0?-1:1;}double pw(double x,int c){    if (c==0) return 1.0;    double res=1;    for (int i=1; i<=c; i++)    {        res*=x;    }    if (dcmp(res)==0) return inf;    return 1/res;}double f(double x){    double res=0;    for (int i=0; i<n; i++)    {        res+=a[i]*pw(x,i);    }    return res;}int main(){//    freopen("in.txt","r",stdin);    while(cin>>n && n)    {        n++;        for (int i=0; i<n; i++)        cin>>a[i];        double l=0.000001,r=1000000.0;        double mid;        while(l<r)        {            mid=(l+r)/2.0;            int k=dcmp(f(mid));            if (k==-1) r=mid;            else if (k==1) l=mid;            else if (k==0)            {                l=r=mid; break;            }        }        printf("%.2lf\n",l-1.0);    }    return 0;}


0 0