""""
Ex. 3.7 from "A Primer on...".
Write a function sum_1k(M) that computes and
returns a sum, and write a test function
test_sum_1k()
"""
def sum_1k(M):
s = 0
for k in range(1,M+1):
s += 1/k
return s
#print(sum_1k(3))
# sum = 1 + 1/2 + 1/3 = 11/6
def test_sum_1k():
M = 3
tol = 1e-12
expected = 11/6
computed = sum_1k(M)
#use a tolerance since we compare floats:
success = abs(expected - computed) < tol
assert success
#call the test function (should give no output if test passes):
test_sum_1k()
"""
Terminal> python sum_1k.py
"""
"""
Alternatively, use pytest to run the test. Then you don't need
the explicit call to the test function above, since pytest will
automatically find and run all test functions:
Terminal> pytest sum_1k.py
===================================== test session starts ======================================
platform darwin -- Python 3.9.7, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /Users/sundnes/Desktop/IN1900_9sep
plugins: anyio-2.2.0, mock-3.10.0, cov-3.0.0
collected 1 item
sum_1k.py . [100%]
====================================== 1 passed in 0.01s =======================================
"""