Coverage for src/foapy/characteristics/_arithmetic_mean.py: 100%

6 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-05-17 20:45 +0000

1import numpy as np 

2 

3 

4def arithmetic_mean(intervals, dtype=None): 

5 """ 

6 Calculates average arithmetic value of intervals lengths. 

7 

8 $$ \\Delta_a = \\frac{1}{n} * \\sum_{i=1}^{n} \\Delta_{i} $$ 

9 

10 where \\( \\Delta_{i} \\) represents each interval and \\( n \\) 

11 is the total number of intervals. 

12 

13 Parameters 

14 ---------- 

15 intervals : array_like 

16 An array of intervals 

17 dtype : dtype, optional 

18 The dtype of the output 

19 

20 Returns 

21 ------- 

22 : float 

23 The arithmetic mean of the input array of intervals. 

24 

25 Examples 

26 -------- 

27 

28 Calculate the arithmetic mean of intervals of a sequence. 

29 

30 ``` py linenums="1" 

31 import foapy 

32 import numpy as np 

33 

34 source = ['a', 'b', 'a', 'c', 'a', 'd'] 

35 intervals = foapy.intervals(source, foapy.binding.start, foapy.mode.normal) 

36 result = foapy.characteristics.arithmetic_mean(intervals) 

37 print(result) 

38 # 2.8333333333333335 

39 

40 # Improve precision by specifying a dtype. 

41 result = foapy.characteristics.arithmetic_mean(intervals, dtype=np.longdouble) 

42 print(result) 

43 # 2.8333333333333333333 

44 ``` 

45 

46 Improve precision by specifying a dtype. 

47 

48 ``` py linenums="1" 

49 import foapy 

50 import numpy as np 

51 

52 source = ['a', 'b', 'a', 'c', 'a', 'd'] 

53 intervals = foapy.intervals(source, foapy.binding.start, foapy.mode.normal) 

54 ``` 

55 

56 """ # noqa: W605 

57 

58 n = len(intervals) 

59 

60 # Check for an empty list or a list with zeros 

61 if n == 0 or all(x == 0 for x in intervals): 

62 return 0 

63 

64 return np.sum(intervals, dtype=dtype) / n