tinyexpr
tinyexpr copied to clipboard
(-1)^0 returns -1 instead of 1
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.
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)
.
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.
I've added some extra test cases to smoke.c
. A fix is still coming...
@Photosounder Same issue raised here: https://github.com/codeplea/tinyexpr/issues/10#issuecomment-241543333
Doesn't matter to me anymore, I've made a more sophisticated replacement for TinyExpr https://github.com/Photosounder/rouziclib#expression-parsing 😁
Very nice :+1: