fel计算引擎(表达式计算数学公式)--实例sigma求和∑

fel计算引擎--实例sigma求和∑

从而避免每一个公式都手动写方法计算,只要输入数学公式就可计算结果;

示例计算   

1+2*(SUM('x_*3+1','1','5')+1)

 

fel用的0.9版本,支持大数高精度;

约定变量以下划线结尾

 

public class SumFunction extends CommonFunction {

    private FelContext felContext;

    @Override
    public String getName() {
        return "SUM";
    }

    @Override
    public Object call(FelNode felNode, FelContext felContext) {
        this.felContext = felContext;
        return super.call(felNode, felContext);
    }

    @Override
    public Object call(Object[] objects) {
        if (objects == null || objects.length != 3) {
            throw new IllegalArgumentException("SUM Function Argument Illegal");
        }
        Object express = objects[0];
        Object beginIndex = objects[1];
        Object endIndex = objects[2];
        System.out.println("\nStart SumFunction: origin express=" + express + "; beginIndex=" + beginIndex + "; endIndex=" + endIndex);
        int beginIndexInteger = Integer.valueOf(objects[1].toString());
        int endIndexInteger = Integer.valueOf(objects[2].toString());
        String expressString = express.toString();

        BigDecimal sum = BigDecimal.ZERO;

        FelEngine felEngine = FelBuilder.bigNumberEngine();
        felEngine.setContext(felContext);
        for (int i = beginIndexInteger; i <= endIndexInteger; i++) {
            String expressReal = expressString.replaceAll("_", "_" + i);
            Object eval = felEngine.eval(expressReal);
            System.out.println("expressReal=" + expressReal + "; index=" + i + "; eval=" + eval);
            sum = sum.add(new BigDecimal(eval.toString()));
            System.out.println("SumIterator=" + sum);
        }

        double sumFunctionResult = sum.doubleValue();
        System.out.println("End SumFunction: result=" + sumFunctionResult + "\n");
        return sumFunctionResult;
    }

}

 

public class SumFunctionTest {

    public static void main(String[] args) {
        FelEngine felEngine = FelBuilder.bigNumberEngine();
        felEngine.addFun(new SumFunction());

        FelContext context = felEngine.getContext();
        for (int i = 1; i <= 5; i++) {
            context.set("x_" + i, i);
        }

        String exp = "1+2*(SUM('x_*3+1','1','5')+1)";
        Object eval = felEngine.eval(exp, context);
        System.out.println("TEST SUM= " + eval);
    }

}

 

Start SumFunction: origin express=x_*3+1; beginIndex=1; endIndex=5
expressReal=x_1*3+1; index=1; eval=4
SumIterator=4
expressReal=x_2*3+1; index=2; eval=7
SumIterator=11
expressReal=x_3*3+1; index=3; eval=10
SumIterator=21
expressReal=x_4*3+1; index=4; eval=13
SumIterator=34
expressReal=x_5*3+1; index=5; eval=16
SumIterator=50
End SumFunction: result=50.0

TEST SUM= 103.0

 

 

 

 

 

你可能感兴趣的:(计算引擎,计算引擎)