/** * Set a named constant (constants names are not case-sensitive). Constants are like variables but * are not cleared by clear(). Variables of the same name have precedence over constants. */ public MathEval setConstant(String nam, Double val) { if (constants.get(nam) != null) { throw new IllegalArgumentException("Constants may not be redefined"); } validateName(nam); constants.put(nam, val); return this; }
private double doNamedVal(int beg, int end) { while (beg < end && Character.isWhitespace(expression.charAt(end))) { end--; } // since a letter triggers a named value, this can never reduce to beg==end String nam = expression.substring(beg, (end + 1)); Double val; if ((val = constants.get(nam)) != null) { return val.doubleValue(); } else if ((val = variables.get(nam)) != null) { isConstant = false; return val.doubleValue(); } else if (relaxed) { isConstant = false; return 0.0; } throw exception(beg, "Unrecognized constant or variable \"" + nam + "\""); }
private double doFunction(int beg, int end) { int argbeg; for (argbeg = beg; argbeg <= end && expression.charAt(argbeg) != '('; argbeg++) {; } String fncnam = expression.substring(beg, argbeg).trim(); ArgParser fncargs = new ArgParser(argbeg, end); FunctionHandler fnchdl = null; try { if ((fnchdl = pureFunctions.get(fncnam)) != null) { return fnchdl.evaluateFunction(fncnam, fncargs); } else if ((fnchdl = impureFunctions.get(fncnam)) != null) { isConstant = false; // impure functions cannot be guaranteed to be constant return fnchdl.evaluateFunction(fncnam, fncargs); } fncargs = null; // suppress check for too many fncargs } catch (ArithmeticException thr) { fncargs = null; throw thr; } catch (NoSuchMethodError thr) { fncargs = null; throw exception(beg, "Function not supported in this JVM: \"" + fncnam + "\""); } catch (UnsupportedOperationException thr) { fncargs = null; throw exception(beg, thr.getMessage()); } catch (Throwable thr) { fncargs = null; throw exception(beg, "Unexpected exception parsing function arguments", thr); } finally { if (fncargs != null) { if (fncargs.hasNext()) { throw exception(fncargs.getIndex(), "Function has too many arguments"); } offset = fncargs.getIndex(); } } throw exception(beg, "Function \"" + fncnam + "\" not recognized"); }
/** Set a named variable (variables names are not case-sensitive). */ public double getVariable(String nam) { Double val = variables.get(nam); return (val == null ? 0 : val.doubleValue()); }
/** * Set a named constant (constant names are not case-sensitive). Constants are like variables but * are not cleared by clear(). Variables of the same name have precedence over constants. */ public double getConstant(String nam) { Double val = constants.get(nam); return (val == null ? 0 : val.doubleValue()); }