Troon
(Troon)
July 28, 2023, 8:55am
1
Before I report this as a bug, am I missing something silly?

```
{% set z = 0 %}
minus one to the power zero: {{ -1**0 }}
minus one to the power one: {{ -1**1 }}
minus one to the power z: {{ -1**z }}
two to the power z: {{ 2**z }}
```

Anything raised to the power zero should be one. It seems that `-1**z`

always returns `-1`

, and:

```
{% set z = 2 %}
{{ (-2)**z }} # returns -4, incorrectly
{{ (-2)**2 }} # returns 4, correctly
```

Troon
(Troon)
July 28, 2023, 9:25am
3
Cheers, raised:

opened 09:24AM - 28 Jul 23 UTC

### The problem
Writing [IEEE 754](https://github.com/Troon/IEEE754-homeassis… tant) macro, reference equation uses `-1**(sign_bit)`. I kept getting incorrect results. On investigation, I found:
```
{% set z = 0 %}
{{ -1**0 }} # returns 1, correctly
{{ -1**z }} # returns -1, incorrectly
```
Further checks show this appears to affect all negative numbers:
```
{% set z = 4 %}
{{ (-2)**4 }} # 16
{{ (-2)**z }} # -16
```
Worked around my original problem with `[1,-1][sign_bit]`.
### What version of Home Assistant Core has the issue?
2023.7.1
### What was the last working version of Home Assistant Core?
_No response_
### What type of installation are you running?
Home Assistant Container
### Integration causing the issue
Template
### Link to integration documentation on our website
_No response_
### Diagnostics information
_No response_
### Example YAML snippet
_No response_
### Anything in the logs that might be useful for us?
_No response_
### Additional information
_No response_

Looks like an upstream Jinja issue though:

opened 03:35PM - 15 Sep 22 UTC

Unexpected behavior of the power operator with a variable of even value as expon… ent. It returns the negative value of the expected result.
## mcve
```python
from jinja2 import Environment
env = Environment()
env.globals = {"x": 2}
env.from_string("{{ -1 ** x }}").render()
```
From which I get `'-1'`
## Expected behavior
I expected the positive value `'1'` as a result
It instead works as expected in a Sandboxed environment when intercepting the `**` operator:
```python
from jinja2.sandbox import SandboxedEnvironment
sandbox_env = SandboxedEnvironment()
sandbox_env.globals = {"x": 2}
sandbox_env.intercepted_binops = frozenset(["**"])
sandbox_env.from_string("{{ -1 ** x }}").render()
```
From which I get `'1'`
## Environment:
- Python version: 3.8.10
- Jinja version: 3.1.2

1 Like