3. Parsing rulesNow, what will be inside the eval function? The idea is to search in the expression for an operator. Then split the expression in the part left from the operator (part1) and the part right from the operator (part2). Evaluate part1 and part2 with the function eval, and finally evaluate the answers of part1 and part2 with the found operator. You can not just pick any operator and do this, because we have to do with mathematical rules. For finding the operator in the expression that needs to be evaluated first, the following three rules hold.
- Neglect the operators between parentheses ( and ). Parentheses are used to overrule the precedence of mathematical operators. Normally the answer of the expression 2+3*4 is 14 and not 20, because multiplication has a higher precedence than addition. If you want to calculate the addition first, you have to enclose that part of the expression with parentheses: (2+3)*4.
- Find the operator with the lowest precedence. You can not just pick any operator and evaluate the parts left and right , because we have to do with mathematical precedence. For example 2+3*4 must be calculated as 2+(3*4)=14 and not (2+3)*4=20. The order of precedence from low to high is: ( ), - +, / *, ^.
- If there are more operators of the lowest precedence, then choose the last one. This is important for a good evaluation of for example "10 - 3 - 4". This must be calculated as "(10 - 3) - 4" = 3 and not "10 - (3 - 4)" = 11. The same holds for divisions.
Copyright © 2006 SpeQ Mathematics