Add iterating function and the test for it

This commit is contained in:
ASPP Student 2025-09-23 18:07:05 +03:00
parent 4736cc7ac9
commit b192a2a76f
2 changed files with 32 additions and 11 deletions

View file

@ -1,4 +1,13 @@
# Your code goes here # Your code goes here
import numpy as np
def f(x, r): def f(x, r):
return r * x * (1 - x) 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

View file

@ -1,7 +1,7 @@
import pytest import pytest
from numpy.testing import assert_allclose from numpy.testing import assert_allclose
from logistic import f from logistic import f, iterate_f
def test_f_corner_cases(): def test_f_corner_cases():
@ -14,6 +14,17 @@ def test_f_corner_cases():
result = f(x, r) result = f(x, r)
assert_allclose(result, expected) assert_allclose(result, expected)
# Hands on 1
#Add a new test for these generic cases using the for-loop pattern:
# x=0.1, r=2.2 => f(x, r)=0.198
# x=0.2, r=3.4 => f(x, r)=0.544
# x=0.5, r=2 => f(x, r)=0.5
# Hands on 2:
# parametrize the above test using @pytest.mark.parametrize
@pytest.mark.parametrize( @pytest.mark.parametrize(
'x, r, expected', 'x, r, expected',
[ [
@ -26,17 +37,18 @@ def test_f_generic_cases(x, r, expected):
result = f(x, r) result = f(x, r)
assert_allclose(result, expected) assert_allclose(result, expected)
# Hands on 1
#Add a new test for these generic cases using the for-loop pattern:
# x=0.1, r=2.2 => f(x, r)=0.198
# x=0.2, r=3.4 => f(x, r)=0.544
# x=0.5, r=2 => f(x, r)=0.5
# Hands on 2:
# parametrize the above test using @pytest.mark.parametrize
@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 # Hands on 3
# Implement a function iterate_f that runs f for it iterations. Write tests for the following cases: # 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] # x=0.1, r=2.2, it=1 => iterate_f(it, x, r)=[0.1, 0.198]