Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Evaluate percentage expressions correctly #268

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

jeremypw
Copy link
Collaborator

@jeremypw jeremypw commented Nov 30, 2023

Fixes #222

  • Evaluate a% with no preceding operator as (a / 100)
  • Evaluate a + b% as a + (b*a/100)
  • Evaluate a - b% as a - (b*a/100)
  • Evaluate a * b% as a * (b * a / 100) (Google gives a * (b/100))
  • Evaluate a / b% as a / (b * a / 100) (Google gives a / (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)% as 165 whereas Google gives the incorrect answer 150.1.

However, it is unclear what the correct answer is for expressions such as a * b% and a / b%. The current solution gives different answers to Google for these expressions. For consistency, in this PR a * b% evaluates as a * (b * a / 100) and a / b% evaluates as a / (b*a / 100) i.e. the percentage is evaluated the same way regardless of the preceding operator.

@jeremypw jeremypw marked this pull request as ready for review December 2, 2023 20:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Error in percentage calculation
1 participant