irr java_Java版的IRR(内部收益率)实现
时间: 2024-02-23 11:58:59 浏览: 314
Java中可以使用Apache Commons Math库来计算IRR。下面是一个示例代码:
```java
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.solvers.BaseUnivariateSolver;
import org.apache.commons.math3.analysis.solvers.BrentSolver;
public class IRRCalculator {
/**
* 计算IRR
* @param cashFlows 现金流,必须以负值表示投资额,以正值表示收益额
* @return IRR
*/
public static double calculateIRR(double[] cashFlows) {
UnivariateFunction function = new UnivariateFunction() {
@Override
public double value(double x) {
double npv = 0.0;
for (int i = 0; i < cashFlows.length; i++) {
npv += cashFlows[i] / Math.pow(1 + x, i);
}
return npv;
}
};
BaseUnivariateSolver solver = new BrentSolver();
double irr = solver.solve(1000, function, -1.0, 1.0);
return irr;
}
public static void main(String[] args) {
double[] cashFlows = {-1000, 500, 300, 200, 100};
double irr = IRRCalculator.calculateIRR(cashFlows);
System.out.println("IRR: " + irr);
}
}
```
在上述代码中,我们首先定义了一个UnivariateFunction对象,用于计算IRR的NPV(净现值)。然后使用BrentSolver来解方程,获得IRR。在main方法中,我们传入一个示例现金流,计算出IRR并打印输出。
阅读全文