【ZCMU1757】内部收益率(二分)

题目链接

不忘初心,砥砺前行!庆祝中华人民共和国建国六十九周年!祝祖国繁荣昌盛,祝全国人民幸福安康!

Problem 1757. -- 内部收益率

1757: 内部收益率

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 103  Solved: 47
[Submit][Status][Web Board]

Description

Input

Output

Sample Input

1 -1 2 2 -8 6 9 0

Sample Output

1.00 0.50

HINT

【解题思路】

嗯...答案是一定存在的,因为CF0小于0,其他的CFi都是大于0的,而IRR为负数的时候的范围是需要小于等于-1的,所以肯定能找到一个近似的IRR使这个方程成立。所以直接二分搜答案即可。

【代码】

#include<bits/stdc++.h>
using namespace std;
const double MAX=1e5+5;
const double zero=1e-5;
double a[15];
int n;
double quickpow(double a,int b)
{
    double ans=1;
    while(b)
    {
        if(b&1)ans=ans*a;
        a=a*a;
        b>>=1;
    }
    return ans;
}
double makeans(double irr)
{
    double ans=0;
    for(int i=1;i<=n;i++)
        ans+=(a[i]/(quickpow(1+irr,i)));
    return ans;
}
double binarysearch()
{
    double l=-1,r=MAX;
    while(l<r)
    {
        double mid=(l+r)/2;
        double ans=makeans(mid);
        if(fabs(ans+a[0])<=zero)return mid;
        else if(ans>-a[0])l=mid;
        else r=mid;
    }
}
int main()
{
    while(~scanf("%d",&n) && n)
    {
        for(int i=0;i<=n;i++)
            scanf("%lf",&a[i]);
        double ans=binarysearch();
        printf("%.2f\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39826163/article/details/83018354
今日推荐