Coverage for pyguymer3/var.py: 70%

10 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-07-08 18:47 +0000

1#!/usr/bin/env python3 

2 

3# Define function ... 

4def var( 

5 arr, 

6 /, 

7 *, 

8 dof = 0, 

9): 

10 """Find the variance of an array. 

11 

12 This function finds the variance of an array, with optionally specified 

13 degrees of freedom. 

14 

15 Parameters 

16 ---------- 

17 arr : numpy.ndarray 

18 the array 

19 dof : int, default=0 

20 the degrees of freedom 

21 

22 Returns 

23 ------- 

24 ans : float 

25 the variance of the array 

26 

27 Notes 

28 ----- 

29 See `the NumPy documentation <https://numpy.org/doc/stable/reference/generated/numpy.var.html>`_. 

30 

31 In standard statistical practice: 

32 

33 * ``dof=0`` provides a maximum likelihood estimate of the variance for 

34 normally distributed variables; and 

35 * ``dof=1`` provides an unbiased estimator of the variance of a 

36 hypothetical infinite population. 

37 

38 Copyright 2017 Thomas Guymer [1]_ 

39 

40 References 

41 ---------- 

42 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3 

43 """ 

44 

45 # Import special modules ... 

46 try: 

47 import numpy 

48 except: 

49 raise Exception("\"numpy\" is not installed; run \"pip install --user numpy\"") from None 

50 

51 # Import sub-functions ... 

52 from .mean import mean 

53 

54 # Check argument ... 

55 if not isinstance(arr, numpy.ndarray): 

56 raise TypeError("\"arr\" is not a NumPy array") from None 

57 

58 # Calculate the squared deviations from the mean ... 

59 tmp = numpy.float_power(arr - mean(arr, dof = 0), 2) 

60 

61 # Return the answer ... 

62 return mean(tmp, dof = dof)