1. 程式人生 > >【ZCMU1757】內部收益率(二分)

【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;
}