MCPcopy Index your code
hub / github.com/numpy/numpy / _var

Function _var

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

Source from the content-addressed store, hash-verified

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

Callers 1

_stdFunction · 0.70

Calls 8

asanyarrayFunction · 0.85
_count_reduce_itemsFunction · 0.85
reshapeMethod · 0.80
conjugateMethod · 0.80
dtypeMethod · 0.45
getMethod · 0.45
viewMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…