jep自定义函数使用,下面是jep自定义函数计算年利率一个demo
jep在使用函数时,需要把相应的函数加入jep 幂函数
Jep jep = new Jep(); jep.addFunction("pow", new Power());自定义函数也是如此 1.定义年利率计算类AnnualInterestRate,由于需要多个参数,故继承NaryFunction类,该类根据个人需求继承相应的类
package main.java.com.extension.jep; import com.singularsys.jep.EvaluationException; import com.singularsys.jep.functions.NaryFunction; /** * 年利率计算 chenyouhong */ public class AnnualInterestRate extends NaryFunction { // Use default constructor: variable number of arguments // Ensure at least one argument //此处实际参数个数是4,此处并未做相关的判断 n == 4 ? true : false @Override public boolean checkNumberOfParameters(int n) { return true; } //处理方法及相应的入参 public Object eval(Object[] args) throws EvaluationException { double amount = asDouble(0,args[0]); double newPrice = asDouble(1,args[1]); Integer periods = asInt(2,args[2]); double yearRate = asDouble(3,args[3]); return this.getYearRate(amount, newPrice, periods, yearRate); } private Double getYearRate(Double amount, Double newPrice, Integer periods, Double yearRate) { double yuegong = getMonth(amount, periods, yearRate); double yg = 1d; double yh = 1d; while (com.lz.utils.math.DoubleMathUtils.sub(yg, yuegong) <= 0) { yg = getMonth(newPrice, periods, yh);// 月供 yh = com.lz.utils.math.DoubleMathUtils.sum(yh, 0.01); } return yh; } private Double getMonth(Double amount, Integer periods, Double yearRate) { double a = 0, i = 0; int n = 0; double c1; double c2; a = amount;// 总贷款 n = periods; i = com.lz.utils.math.DoubleMathUtils.div(yearRate - 0.001d, 1200, 4); c2 = com.lz.utils.math.DoubleMathUtils.div(a * i * Math.pow((1 + i), n), Math.pow((1 + i), n) - 1, 2); return c2; // 161102 向下取整到小数点后两位 } }2.年利率类定义后,应用与一般方法一致
Jep jep = new Jep(); //总金额 jep.addVariable("amount", 86900); //实际金额 jep.addVariable("price", 67900 ); jep.addVariable("peridos", 36); jep.addVariable("yearRate", 0.07125); jep.addFunction("annualInterestRate", new AnnualInterestRate()); jep.parse("annualInterestRate(amount, price, peridos, yearRate)"); //最终年利率 System.out.println( jep.evaluate());3.jep文档链接 http://www.singularsys.com/jep/doc/html/customfunctions.html
4.demo地址 https://github.com/13162576590/jep_demo