Friday, April 24, 2015

UVa 11881 - Internal Rate of Return

#include <stdio.h>
#include <math.h>
#include <limits>
using namespace std;

static const double EPS = 1e-9;

int t, cash_flow[11];

double npv(double irr) {
	double npv = cash_flow[0];
	double irr_plus_1 = irr + 1;
	double irr_plus_1_power = 1;
	for (int i = 1; i <= t; i++) {
		irr_plus_1_power *= irr_plus_1;
		npv += cash_flow[i] / irr_plus_1_power;
	}
	return npv;
}

int main() {
	scanf("%d", &t);
	while (t != 0) {
		scanf("%d", &cash_flow[0]);
		for (int i = 1; i <= t; i++)
			scanf("%d", &cash_flow[i]);

		double best_sol = fabs(npv(-0.99)), sol = -0.99;
		double ini = -0.999, fin = numeric_limits<double>::max();
		while (ini + EPS <= fin) {
			double mid = (ini + fin) / 2;
			double npv_mid = npv(mid);
			if (fabs(npv_mid) < best_sol) {
				best_sol = fabs(npv_mid);
				sol = mid;
			}
			if (npv_mid > EPS)
				ini = mid;
			else
				fin = mid;
		}

		/*if (round(sol * 100) == 0)
		 sol = 0;*/

		printf("%0.2f\n", sol);
		scanf("%d", &t);
	}
	return 0;
}

No comments:

Post a Comment