diff --git a/testing_project/logistic.py b/testing_project/logistic.py index e49d1c2..a60f6dc 100644 --- a/testing_project/logistic.py +++ b/testing_project/logistic.py @@ -1 +1,14 @@ # Your code goes here +import numpy as np + +def f(x, r): + return r * x * (1 - x) + +def iterate_f(x, r, n_iterations): + trajectory = np.zeros(n_iterations+1) + trajectory[0] = x + for i in range(n_iterations): + trajectory[i+1] = f(x, r) + x = trajectory[i+1] + return trajectory + diff --git a/testing_project/logistic_fit.py b/testing_project/logistic_fit.py index 1d38ac7..55ee1f0 100644 --- a/testing_project/logistic_fit.py +++ b/testing_project/logistic_fit.py @@ -24,7 +24,7 @@ def fit_r(xs): it = len(xs) - 1 def error(r): - return np.linalg.norm(xs - iterate_f(it, x0, r)) + return np.linalg.norm(xs - iterate_f(x0, r, it)) errors = [] for r in np.linspace(0, 4, 4001): diff --git a/testing_project/test_logistic.py b/testing_project/test_logistic.py index 100d824..39e8bf6 100644 --- a/testing_project/test_logistic.py +++ b/testing_project/test_logistic.py @@ -1,6 +1,7 @@ +import pytest from numpy.testing import assert_allclose -from logistic import f +from logistic import f, iterate_f def test_f_corner_cases(): @@ -24,6 +25,30 @@ def test_f_corner_cases(): # parametrize the above test using @pytest.mark.parametrize +@pytest.mark.parametrize( + 'x, r, expected', + [ + (0.1, 2.2 ,0.198), + (0.2, 3.4 ,0.544), + (0.5, 2 ,0.5) + ] +) +def test_f_generic_cases(x, r, expected): + result = f(x, r) + assert_allclose(result, expected) + + +@pytest.mark.parametrize( + 'x, r, n_iterations, 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_generic(x, r, n_iterations, expected): + result = iterate_f(x, r, n_iterations) + assert_allclose(result, expected, rtol=1e-6) # Hands on 3 # Implement a function iterate_f that runs f for it iterations. Write tests for the following cases: # x=0.1, r=2.2, it=1 => iterate_f(it, x, r)=[0.1, 0.198] diff --git a/testing_project/test_logistic_fit.py b/testing_project/test_logistic_fit.py new file mode 100644 index 0000000..1a03e0c --- /dev/null +++ b/testing_project/test_logistic_fit.py @@ -0,0 +1,22 @@ +from numpy.testing import assert_allclose +import numpy as np + +from logistic import iterate_f +from logistic_fit import fit_r + +def test_fit_r(): + r = 3.421 + trajectory = iterate_f(0.3, r, 23) + fit_result_r = fit_r(trajectory) + assert_allclose(r, fit_result_r) + + +def test_fit_r_randomized(): + random_state = np.random.RandomState(42) + x0 = 0.3 + for _ in range(100): + r = random_state.rand() + trajectory = iterate_f(x0, r, 23) + fit_result_r = fit_r(trajectory) + assert_allclose(r, fit_result_r, atol=0.1) +