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

(-1)^0 returns -1 instead of 1 #52

Open
Photosounder opened this issue Jul 3, 2019 · 7 comments
Open

(-1)^0 returns -1 instead of 1 #52

Photosounder opened this issue Jul 3, 2019 · 7 comments

Comments

@Photosounder
Copy link

When I evaluate (-1)^0 I get -1, which is wrong. Yet when I evaluate pow(-1, 0) I get 1, which is correct. It seems to be an expression compilation error since te_eval only runs case TE_CONSTANT: return n->value;. (-x)^0 also always yields -1 regardless of the value of x, while x^0 and (0-x)^0 correctly yield 1. I'm using the logic branch in case that matters, with TE_POW_FROM_RIGHT defined.

Btw for the ease of debugging I suggest that you name your tokens enum, something like enum token and use enum token type; instead of int type; in the state struct, this way debuggers will show the name of the enum.

@codeplea
Copy link
Owner

codeplea commented Jul 3, 2019

Interesting. It seems to only happen with TE_POW_FROM_RIGHT defined. It's definitely a parser error. With TE_POW_FROM_RIGHT defined, it parses the expression as negation(power(1, 0)) instead of power(negation(1),0).

@codeplea
Copy link
Owner

codeplea commented Jul 4, 2019

When TE_POW_FROM_RIGHT is defined, there is special logic to ensure that -a^b = -(a^b). The problem is that it will optimize (-1)^0 to -1^0 to -(1^0), which is very wrong.

Without TE_POW_FROM_RIGHT, tinyexpr sees -a^b as (-a)^b, so there is no problem in that case.

There are probably other cases such as -a^-b^-c that need special consideration. I guess with TE_POW_FROM_RIGHT that should parse as -(a^(-(b^(-c)))), whereas without TE_POW_FROM_RIGHT it should parse as ((-a)^(-b))^(-c).

I will try to work up a solution soon.

@codeplea
Copy link
Owner

codeplea commented Oct 2, 2020

I've added some extra test cases to smoke.c. A fix is still coming...

@ArashPartow
Copy link

ArashPartow commented Jun 7, 2022

@Photosounder Same issue raised here: #10 (comment)

@Photosounder
Copy link
Author

Doesn't matter to me anymore, I've made a more sophisticated replacement for TinyExpr https://github.com/Photosounder/rouziclib#expression-parsing 😁

@ArashPartow
Copy link

Very nice 👍

@RokerHRO
Copy link

RokerHRO commented Apr 8, 2024

I think the problem can only be handled correctly by introducing another precedence level for the unary minus (and plus) sign, as it is be done by regular C expression parsers in the compiler, too.

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

No branches or pull requests

4 participants