01: package com.teamkonzept.lib.math;
02:
03: public class MathBinaryOperator extends BinaryOperator {
04:
05: final static int PLUS = 0;
06: final static int MINUS = 1;
07: final static int MULT = 2;
08: final static int DIV = 3;
09: final static int MODULO = 4;
10: final static int INT_DIV = 5;
11: final static int POW = 6;
12: int type;
13:
14: public MathBinaryOperator(int type, int parenlevel, int position)
15: throws UnsupportedOperatorException {
16: super (parenlevel, getPriority(type, position), position);
17: this .type = type;
18: }
19:
20: /**
21: * evaluates this operator to that operands
22: * returns the result of type Double
23: */
24: public Object evaluate(Object left, Object right)
25: throws BadOperandTypeException {
26: if (!(left instanceof Double))
27: throw new BadOperandTypeException(left, "Double");
28: if (!(right instanceof Double))
29: throw new BadOperandTypeException(right, "Double");
30: double d1 = ((Double) left).doubleValue();
31: double d2 = ((Double) right).doubleValue();
32: switch (type) {
33: case PLUS:
34: return new Double(d1 + d2);
35: case MINUS:
36: return new Double(d1 - d2);
37: case MULT:
38: return new Double(d1 * d2);
39: case DIV:
40: return new Double(d1 / d2);
41: case MODULO:
42: double intdiv = Math.floor(d1 / d2);
43: return new Double(d1 - d2 * intdiv);
44: case INT_DIV:
45: return new Double(Math.floor(d1 / d2));
46: case POW:
47: return new Double(Math.pow(d1, d2));
48: default:
49: // cant happen
50: }
51: return null;
52: }
53:
54: static int getPriority(int op, int position)
55: throws UnsupportedOperatorException {
56: switch (op) {
57: case PLUS:
58: return MATH_ADD_PRIORITY;
59: case MINUS:
60: return MATH_ADD_PRIORITY;
61: case MULT:
62: return MATH_MULT_PRIORITY;
63: case DIV:
64: return MATH_MULT_PRIORITY;
65: case MODULO:
66: return MATH_MULT_PRIORITY;
67: case INT_DIV:
68: return MATH_MULT_PRIORITY;
69: case POW:
70: return MATH_EXP_PRIORITY;
71: default:
72: throw new UnsupportedOperatorException(
73: MathBinaryOperator.class, op, position);
74: }
75: }
76: }
|