Skip to content

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

Closed

Description

@Photosounder

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.

Activity

  1. codeplea commented on Jul 3, 2019

    @codeplea
    Owner

    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).

  2. codeplea commented on Jul 4, 2019

    @codeplea
    Owner

    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.

  3. codeplea commented on Oct 2, 2020

    @codeplea
    Owner

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

  4. ArashPartow commented on Jun 7, 2022

    @ArashPartow

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

  5. Photosounder commented on Jun 7, 2022

    @Photosounder
    Author

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

  6. ArashPartow commented on Jun 8, 2022

    @ArashPartow

    Very nice 👍

  7. RokerHRO commented on Apr 8, 2024

    @RokerHRO

    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.

  8. added a commit that references this issue on Aug 5, 2026
    1e2ba48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions