1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| from doctest import run_docstring_examples
from typing import Callable, Union
def summation(n: int, term: Callable[[int], Union[int, float]])->Union[int, float]:
"""sommation
n -- limite supérieure
term -- fonction qui calcule le k ème terme
"""
total, k = 0, 1
while k <= n:
total, k = total + term(k), k + 1
return total
def identity(x: int)->int:
return x
def sum_naturals(n: int)->int:
"""somme des entiers naturels jusqu'à n
>>> sum_naturals(100)
5050
"""
return summation(n, identity)
def cube(x: int)->int:
return x*x*x
def sum_cubes(n: int)->int:
"""somme des cubes des entiers naturels jusqu'à n
>>> sum_cubes(100)
25502500
"""
return summation(n, cube)
def pi_term(x: int)->float:
return 8 / ((4*x-3) * (4*x-1))
def pi_sum(n: int)->float:
"""somme des termes de la série
8/(1*3) + 8(5*7) + 8/(9*11) + ...
>>> pi_sum(100)
3.1365926848388144
"""
return summation(n, pi_term)
run_docstring_examples(sum_naturals, globals(), True)
run_docstring_examples(sum_cubes, globals(), True)
run_docstring_examples(pi_sum, globals(), True) |
Partager