MCPcopy Create free account
hub / github.com/numpy/numpy / _var

Function _var

numpy/core/_methods.py:135–202  ·  view source on GitHub ↗
(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
         where=True)

Source from the content-addressed store, hash-verified

133 return ret
134
135def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
136 where=True):
137 arr = asanyarray(a)
138
139 rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
140 # Make this warning show up on top.
141 if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
142 warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
143 stacklevel=2)
144
145 # Cast bool, unsigned int, and int to float64 by default
146 if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
147 dtype = mu.dtype('f8')
148
149 # Compute the mean.
150 # Note that if dtype is not of inexact type then arraymean will
151 # not be either.
152 arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
153 # The shape of rcount has to match arrmean to not change the shape of out
154 # in broadcasting. Otherwise, it cannot be stored back to arrmean.
155 if rcount.ndim == 0:
156 # fast-path for default case when where is True
157 div = rcount
158 else:
159 # matching rcount to arrmean when where is specified as array
160 div = rcount.reshape(arrmean.shape)
161 if isinstance(arrmean, mu.ndarray):
162 with _no_nep50_warning():
163 arrmean = um.true_divide(arrmean, div, out=arrmean,
164 casting='unsafe', subok=False)
165 elif hasattr(arrmean, "dtype"):
166 arrmean = arrmean.dtype.type(arrmean / rcount)
167 else:
168 arrmean = arrmean / rcount
169
170 # Compute sum of squared deviations from mean
171 # Note that x may not be inexact and that we need it to be an array,
172 # not a scalar.
173 x = asanyarray(arr - arrmean)
174
175 if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
176 x = um.multiply(x, x, out=x)
177 # Fast-paths for built-in complex types
178 elif x.dtype in _complex_to_float:
179 xv = x.view(dtype=(_complex_to_float[x.dtype], (2,)))
180 um.multiply(xv, xv, out=xv)
181 x = um.add(xv[..., 0], xv[..., 1], out=x.real).real
182 # Most general case; includes handling object arrays containing imaginary
183 # numbers and complex types with non-native byteorder
184 else:
185 x = um.multiply(x, um.conjugate(x), out=x).real
186
187 ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
188
189 # Compute degrees of freedom and make sure it is not negative.
190 rcount = um.maximum(rcount - ddof, 0)
191
192 # divide by degrees of freedom

Callers 1

_stdFunction · 0.70

Calls 9

_no_nep50_warningFunction · 0.90
asanyarrayFunction · 0.85
_count_reduce_itemsFunction · 0.85
warnMethod · 0.80
reshapeMethod · 0.80
conjugateMethod · 0.80
dtypeMethod · 0.45
viewMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected