MCPcopy Create free account
hub / github.com/Aghajari/MathParser / MathParser

Class MathParser

MathParser/src/com/aghajari/math/MathParser.java:116–1133  ·  view source on GitHub ↗

A simple but powerful math parser for java. MathParser parser = new MathParser(); // start parser.addExpression("f(x, y) = 2(x + y)"); // addFunction parser.addExpression("x0 = 1 + 2 ^ 2"); // addVariabl

Source from the content-addressed store, hash-verified

114 * @version 1.0.0
115 */
116public class MathParser implements Cloneable {
117
118 /**
119 * {@link #setRoundEnabled(boolean)}
120 */
121 private boolean roundEnabled = true;
122 private int roundScale = 6;
123
124 private final ArrayList<MathVariable> variables = new ArrayList<>();
125 private final ArrayList<MathFunction> functions = new ArrayList<>();
126 private final ArrayList<MathVariable> innerVariables = new ArrayList<>();
127 private final AtomicInteger tmpGenerator = new AtomicInteger(0);
128
129 /* The order of operations */
130 static final char[] order = {'%', '^', '*', '/', '+', '-'};
131
132 /* The priority of operations connected to order[] */
133 static final int[] orderPriority = {3, 2, 1, 1, 0, 0};
134
135 /* Special characters will end name of variables or functions */
136 static final char[] special = {'%', '^', '*', '/', '+', '-', ',', '(', ')', '!', '=', '<', '>'};
137
138 /* Basic math operations that parser supports */
139 static final HashMap<Character, MathOperation> operations = new HashMap<>();
140
141 static {
142 operations.put('^', Math::pow);
143 operations.put('*', (a, b) -> a * b);
144 operations.put('/', (a, b) -> a / b);
145 operations.put('+', Double::sum);
146 operations.put('-', (a, b) -> a - b);
147 operations.put('%', (a, b) -> a % b);
148 }
149
150 private MathParser() {
151 }
152
153 public static MathParser create() {
154 return new MathParser();
155 }
156
157 /**
158 * Parses and calculates the expression
159 *
160 * @param expression the expression to parse and calculate
161 * @throws MathParserException If something went wrong
162 * @throws BalancedParenthesesException If parentheses aren't balanced
163 * @throws MathInvalidParameterException If parameter of the function is invalid
164 * @throws MathFunctionInvalidArgumentsException If the number of arguments is unexpected
165 * @throws MathFunctionNotFoundException If couldn't find the function
166 * @throws MathVariableNotFoundException If couldn't find the variable
167 */
168 public double parse(String expression) throws MathParserException {
169 String org = expression;
170 validate(expression);
171 try {
172 initDefaultVariables();
173 expression = firstSimplify(expression);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected