我在Java中有一个给定形式的数学公式(当然不像这个简单):
String equation = "x^2 + 3*y + 1";
我想从具有相同大小n的x和y数组生成z值,使得z =等式(x,y)也具有大小n。例如z = {x [0] ^ 2 + 3 * y [0] + 1,.....,x [n-1] ^ 2 + 3 * y [n-1] + 1}。
没有外部库的Java中最好的方法是什么,这有助于我根据任意数量的变量(如x和y)的每个整数集来评估每个等式?
答案 0 :(得分:1)
如果你想从头开始做所有事情,你需要提出一个方程式解析器。
从那里你使用Enum:
enum Operation{ADD, SUBTRACT;
public int evaluate(int operand1, int operand2) throws IllegalOperationException {
switch(this) {
case ADD: return operand1 + operand2;
case SUBTRACT: return operand1 - operand2;
default:
break;
}
throw new IllegalOperationException();
}
public static Operation getOperator(String operator) throws IllegalOperationException{
for(Operation o: Operation.values()){
if(o.toString().equals(operator)){
return o;
}
}
throw new IllegalOperationException();
}
};
因此,使用堆栈/队列解析您的等式,然后对每个运算符(op)解析:
Operation.getOperator(op).evaluate(r1, r2);
将x和y替换为x [i]和y [i],并将constructed string
传递给内置的javascript引擎,以防您使用jdk1.6或更高版本。
ScriptEngineManager sm = new ScriptEngineManager();
ScriptEngine en = sm.getEngineByName("JavaScript");
String expression = //your expression with values;
System.out.println(engine.eval(expression));
答案 1 :(得分:0)
public int[] solveEquation(int[] x, int[] y){
if (x == null || y == null || x.length != y.length){
return null;
}
int[] z = new int[x.length];
for (int i=0; i<x.length; i++){
z[i] = x[i]^2 + 3*y[i] + 1;
}
return z;
}