IrrUtil.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package cn.fastfun.util;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class IrrUtil {
  5. /**
  6. * 迭代次数
  7. */
  8. public static int LOOP_NUM = 1000;
  9. /**
  10. * 最小差异
  11. */
  12. public static final double MIN_DIF = 1;
  13. /**
  14. * @param cashFlow 资金流
  15. * @return 收益率
  16. * @desc 使用方法参考main方法
  17. */
  18. public static double getIrr(List<Double> cashFlow) {
  19. double flowOut = cashFlow.get(0);
  20. double minValue = 0d;
  21. double maxValue = 1d;
  22. double testValue = 0d;
  23. int index = 0;
  24. while (LOOP_NUM > 0) {
  25. testValue = (minValue + maxValue) / 2;
  26. double npv = NPV(cashFlow, testValue);
  27. if (Math.abs(flowOut + npv) < MIN_DIF) {
  28. System.out.println(index);
  29. break;
  30. } else if (Math.abs(flowOut) > npv) {
  31. maxValue = testValue;
  32. } else {
  33. minValue = testValue;
  34. }
  35. index ++;
  36. LOOP_NUM--;
  37. }
  38. return testValue;
  39. }
  40. public static double NPV(List<Double> flowInArr, double rate) {
  41. double npv = 0;
  42. for (int i = 1; i < flowInArr.size(); i++) {
  43. npv += flowInArr.get(i) / Math.pow(1 + rate, i);
  44. }
  45. return npv;
  46. }
  47. public static String main(double price, List<Double> flowIn) {
  48. flowIn.add(0, price);
  49. return (IrrUtil.getIrr(flowIn)*100 +"%");
  50. }
  51. }