Last active
November 4, 2021 20:16
-
-
Save alexandru-dinu/a8de1cb8058a30f036341353e802c0eb to your computer and use it in GitHub Desktop.
Python hypothesis example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Simple hypothesis example. | |
Test that sqrt computed using Newton-Raphson is correct. | |
Run with: | |
$ py.test --hypothesis-show-statistics sqrt.py | |
""" | |
import hypothesis.strategies as st | |
from hypothesis import given, settings | |
EPS = 1e-3 | |
def nr_sqrt(a: float, eps: float) -> float: | |
""" | |
f(x) = x**2 - a | |
f'(x) = 2x | |
x_new = x_old - f(x) / f'(x) | |
""" | |
if a == 0: | |
return 0 | |
x_old = float("inf") | |
x_new = a / 2 | |
while abs(x_new - x_old) > eps: | |
x_old = x_new | |
x_new = 0.5 * (x_old + a / x_old) | |
return x_new | |
@settings(max_examples=5000) | |
@given( | |
st.floats( | |
min_value=0, | |
max_value=1e6, | |
allow_nan=None, | |
allow_infinity=None, | |
width=32, | |
) | |
) | |
def test(a): | |
s = nr_sqrt(a, eps=EPS) | |
assert abs(s ** 2 - a) < EPS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment