1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package cn.fastfun.util;
- import java.util.ArrayList;
- import java.util.List;
- public class IrrUtil {
- /**
- * 迭代次数
- */
- public static int LOOP_NUM = 1000;
- /**
- * 最小差异
- */
- public static final double MIN_DIF = 1;
- /**
- * @param cashFlow 资金流
- * @return 收益率
- * @desc 使用方法参考main方法
- */
- public static double getIrr(List<Double> cashFlow) {
- double flowOut = cashFlow.get(0);
- double minValue = 0d;
- double maxValue = 1d;
- double testValue = 0d;
- int index = 0;
- while (LOOP_NUM > 0) {
- testValue = (minValue + maxValue) / 2;
- double npv = NPV(cashFlow, testValue);
- if (Math.abs(flowOut + npv) < MIN_DIF) {
- System.out.println(index);
- break;
- } else if (Math.abs(flowOut) > npv) {
- maxValue = testValue;
- } else {
- minValue = testValue;
- }
- index ++;
- LOOP_NUM--;
- }
- return testValue;
- }
- public static double NPV(List<Double> flowInArr, double rate) {
- double npv = 0;
- for (int i = 1; i < flowInArr.size(); i++) {
- npv += flowInArr.get(i) / Math.pow(1 + rate, i);
- }
- return npv;
- }
- public static String main(double price, List<Double> flowIn) {
- flowIn.add(0, price);
- return (IrrUtil.getIrr(flowIn)*100 +"%");
- }
- }
|