add generic test for logistics function fix2 #15

Open
jiamengwu wants to merge 5 commits from jiamengwu/2025-plovdiv-testing-debugging:logistic into main
3 changed files with 42 additions and 10 deletions

View file

@ -1 +1,11 @@
# Your code goes here # Your code goes here
def f(x, r):
return r * x * (1-x)
def iterate_f(it, x, r):
result = [x]
for i in range(it):
x = f(x, r)
result.append(x)
return result

View file

@ -1,15 +1,11 @@
from numpy.testing import assert_allclose from numpy.testing import assert_allclose
import pytest
from logistic import f from logistic import f, iterate_f
def test_f_corner_cases(): @pytest.mark.parametrize('x,r,expected', [(0, 1.1, 0),(1, 3.7, 0)])
def test_f_corner_cases(x, r, expected):
# Test cases are (x, r, expected) # Test cases are (x, r, expected)
cases = [
(0, 1.1, 0),
(1, 3.7, 0),
]
for x, r, expected in cases:
result = f(x, r) result = f(x, r)
assert_allclose(result, expected) assert_allclose(result, expected)
@ -19,6 +15,15 @@ def test_f_corner_cases():
# x=0.2, r=3.4 => f(x, r)=0.544 # x=0.2, r=3.4 => f(x, r)=0.544
# x=0.5, r=2 => f(x, r)=0.5 # x=0.5, r=2 => f(x, r)=0.5
def test_f_normal_cases():
cases = [
(.1, 2.2, .198),
(.2, 3.4, .544),
(.5, 2, .5),
]
for x, r, expected in cases:
result = f(x, r)
assert_allclose(result, expected)
# Hands on 2: # Hands on 2:
# parametrize the above test using @pytest.mark.parametrize # parametrize the above test using @pytest.mark.parametrize
@ -29,3 +34,11 @@ def test_f_corner_cases():
# x=0.1, r=2.2, it=1 => iterate_f(it, x, r)=[0.1, 0.198] # x=0.1, r=2.2, it=1 => iterate_f(it, x, r)=[0.1, 0.198]
# x=0.2, r=3.4, it=4 => iterate_f(it, x, r)=[0.2, 0.544, 0.843418, 0.449019, 0.841163] # x=0.2, r=3.4, it=4 => iterate_f(it, x, r)=[0.2, 0.544, 0.843418, 0.449019, 0.841163]
# x=0.5, r=2, it=3 => iterate_f(it, x, r)=[0.5, 0.5, 0.5] # x=0.5, r=2, it=3 => iterate_f(it, x, r)=[0.5, 0.5, 0.5]
@pytest.mark.parametrize('x,r,it,expected', [
(0.1, 2.2, 1, [0.1, 0.198]),
(0.2, 3.4, 4, [0.2, 0.544, 0.843418, 0.449019, 0.841163]),
(0.5, 2, 3, [0.5, 0.5, 0.5, 0.5]),
])
def test_iterate_f(x, r, it, expected):
result = iterate_f(it, x, r)
assert_allclose(result, expected, rtol=1e-06)

View file

@ -0,0 +1,9 @@
from numpy.testing import assert_allclose
import pytest
from logistic_fit import fit_r
from logistic import iterate_f
def test_logistic_fit(x0=0.3, r=3.421, it=23):
xs = iterate_f(it, x0, r)
r_fitted = fit_r(xs)
assert_allclose(r, r_fitted)