Evaluate percentage expressions correctly #268
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #222
a%
with no preceding operator as(a / 100)
a + b%
asa + (b*a/100)
a - b%
asa - (b*a/100)
a * b%
asa * (b * a / 100)
(Google givesa * (b/100)
)a / b%
asa / (b * a / 100)
(Google givesa / (b/100)
)To fix this within the current paradigm (reverse Polish notation),
%
is treated as a special token and a new token representing the current left value (CLV) is introduced. The former is replaced during scanning with an expression involving*
,/
,100
and the CLV except that special versions of the multiply and divide operators are used that have a higher than normal precedence in order to ensure the percentage calculation is performed first. During evaluation the CLV is obtained from the stack.An advantage of this approach is that it correctly evaluates expressions such as
(100 + 50) + (7 + 3)%
as165
whereas Google gives the incorrect answer150.1
.However, it is unclear what the correct answer is for expressions such as
a * b%
anda / b%
. The current solution gives different answers to Google for these expressions. For consistency, in this PRa * b%
evaluates asa * (b * a / 100)
anda / b%
evaluates asa / (b*a / 100)
i.e. the percentage is evaluated the same way regardless of the preceding operator.