UVA 11881 Internal Rate of Return

     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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值