Search code examples
pythonpython-internalspython-hypothesis

taking square using "value**2" results causes an overflow while "value*value" is fine


Given the same input, x**2 gives an integer overflow while x*x works fine.

I am not sure if this is because of the python's internal implementation of those operator or if this is a bug in the hypothesis package. Is the opcode for x**2 different from the opcode of x*x?

Here's the minimal example to reproduce it. value*value passes but value**2 fails.


from typing import TypeVar

import pytest
from hypothesis import given, strategies as st

T = TypeVar("T", int, float)

def square2(i: T) -> T:
    return i*i

@given(
  st.one_of(
      st.integers(),
      st.floats(allow_nan=False),
    )
)
def test_square2(value):
    assert square2(value) == value*value
    assert square2(value) == value**2

output

    def test_square2(value):
        assert square2(value) == value*value
>       assert square2(value) == value**2
E       OverflowError: (34, 'Result too large')

This is discovered while working on this tutorial: https://github.com/seifertm/hypothesis-workshop/blob/main/exercises/tests/test_01_baby_steps.py


Solution

  • This is just Python's standard semantics for float: overflow in multiplication returns inf, but overflow in exponentiation raises OverflowError.

    Weird, but not a bug in Hypothesis.