gpt4 book ai didi

java - de.congrace.exp4j 在 CustomFunction 的多个参数上失败

转载 作者:行者123 更新时间:2023-12-01 04:52:40 27 4
gpt4 key购买 nike

我正在尝试添加一个自定义函数,将数字求和到 ExpressionBuilder这是java代码:

package com.sapiens.bdms.drools.exe.helper.FuncServiceTrial;

import com.sapiens.bdms.drools.exe.helper.Functions;
import de.congrace.exp4j.*;

import java.util.ArrayList;
import java.util.Collection;


public class FormulaInterpreter {

public double interpret(String formula) throws UnparsableExpressionException, UnknownFunctionException, InvalidCustomFunctionException {
Collection<CustomFunction> customFunctions = new ArrayList<CustomFunction>();
customFunctions.add(new CustomFunction("SUM") {
@Override
public double applyFunction(double[] doubles) {
Double res = 0.0;
for (double aDouble : doubles) {
res += aDouble;
}
return res;
}
});
Calculable calc = (Calculable) new ExpressionBuilder(formula).withCustomFunctions(customFunctions).build();
return calc.calculate();
}

public static void main(String[] args) throws UnknownFunctionException, UnparsableExpressionException, InvalidCustomFunctionException {
FormulaInterpreter formulaInterpreter = new FormulaInterpreter();
double res = formulaInterpreter.interpret("SUM(2,4,4)");
System.out.println(res);
}
}

但它打印出“2”而不是 10

最佳答案

你能尝试这个构造函数告诉 exp4j 你的函数应该有多少个参数吗:

new CustomFunction("SUM",3)

如 API 文档中所述:http://www.objecthunter.net/exp4j/apidocs/de/congrace/exp4j/CustomFunction.html

这是一个有效的 JUnit 测试用例:

@Test
public void testCustomFunction21() throws Exception {
CustomFunction sumFunc = new CustomFunction("SUM",3) {
@Override
public double applyFunction(double[] doubles) {
Double res = 0.0;
for (double aDouble : doubles) {
res += aDouble;
}
return res;
}
};
Calculable calc = (Calculable) new ExpressionBuilder("SUM(2,4,4)").withCustomFunction(sumFunc).build();
assertTrue(10d == calc.calculate());
}

希望这有帮助,

弗兰克

关于java - de.congrace.exp4j 在 CustomFunction 的多个参数上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14710187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com