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

Formula evaluation with adjacent parentheses incorrect #3333

Open
FrittenKeeZ opened this issue Dec 9, 2024 · 4 comments
Open

Formula evaluation with adjacent parentheses incorrect #3333

FrittenKeeZ opened this issue Dec 9, 2024 · 4 comments
Labels

Comments

@FrittenKeeZ
Copy link

Having a formula with division followed by adjacent parentheses statements is evaluated incorrectly.

Example:

(2*4+3)+9(4+1)/(1*9)(5+7)
(2*4+3)+9*(4+1)/(1*9)*(5+7)

Both of these formulas should evaluate to 71, but only the last one does.

@josdejong
Copy link
Owner

josdejong commented Dec 11, 2024

Thanks for your input. Implicit multiplications can be tricky. A simpler case of your example is the following:

math.parse('1/(2)(4)') // 0.125

I agree that the behavior is quite confusing. Mathjs has some special rules in place dealing with implicit multiplication. The difficult thing is that in different cases, you would expect different types of behavior. Just giving implicit multiplication the same precedence as multiply and divide gives odd cases too.

math.parse('1/(2)(x)').toString({ parenthesis: 'all' }) // "1 / (2 x)" 
math.parse('1/2 x').toString({ parenthesis: 'all' })    // "(1 / 2) x"
math.parse('4km / 2h').toString({ parenthesis: 'all' }) // "(4 km) / (2 h)" 

I'm always open for good ideas to improve the behavior, but implicit multiplication is a tricky subject, see for example #792, #2370.

@FrittenKeeZ
Copy link
Author

@josdejong we're using these regexes to "fix" the expressions before evaluation:

expression
    .replace(/(\d)(\()/, '$1*$2')
    .replace(/(\))(\d)/, '$1*$2')
    .replace(/(\))(\()/, '$1*$2')

@josdejong
Copy link
Owner

Thanks for sharing.

Please be careful with regexes like these, they can go wrong when you have nesting, like nested parenthesis inside parenthesis.

In general, it can help to present to the user how the experession is evaluated by shoing the exrpesion with all the (relevant) parens.

@FrittenKeeZ
Copy link
Author

It's looking specifically for something like 5(, )5 and )( - anything else is untouched, so nesting shouldn't be a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants