Question

I am using a Bean Shell interpreter in a for loop like this

    for(int i = 0; i <functionSize; i++){
         interpreter.set("x", i);
         yvalues[i] = (Integer) interpreter.eval(functionString);
    }

The problem I am having is that when I do the function 2^x I get really strange output. The list of the first few y values is like this: 2, 3, 0 , 1, 6, 7, 4, 5, 10 , 11, 8 , 9 ...

Does anybody know how to get the bean shell interpreter to correctly evaluate powers?

Edit: I would like to use the bean shell interpreter in place of writing a math parser. Does anyone know how I can get the bean shell to evaluate powers of functions of x?

Was it helpful?

Solution

The expression 2^x represents bitwise XOR, not exponentiation. Use Math.pow(2,x) if you like, but realize that it operates on doubles, not ints, so will give you a floating-point answer that will probably cause an exception when you try to cast the result as an integer.

edit: there is also BigInteger.pow(), which returns a BigInteger.

Or, if you want powers of 2, but not any other base, use the expression for left shift: 1 << x for x between 0 and 31.

OTHER TIPS

Ended up editing to:

 double y = Double.parseDouble(interpreter.eval(functionString).toString());
 yvalues[i] = (int) y;

And using Math.pow(a, b) as my input.

Doesn't look pretty, but its working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top