tinyexpr icon indicating copy to clipboard operation
tinyexpr copied to clipboard

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

Open Photosounder opened this issue 5 years ago • 7 comments

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.

Photosounder avatar Jul 03 '19 09:07 Photosounder

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 avatar Jul 03 '19 19:07 codeplea

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 avatar Jul 04 '19 04:07 codeplea

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

codeplea avatar Oct 02 '20 22:10 codeplea

@Photosounder Same issue raised here: https://github.com/codeplea/tinyexpr/issues/10#issuecomment-241543333

ArashPartow avatar Jun 07 '22 11:06 ArashPartow

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

Photosounder avatar Jun 07 '22 11:06 Photosounder

Very nice :+1:

ArashPartow avatar Jun 08 '22 21:06 ArashPartow