r"""Calculate standard deviation of data x[]:
        std = sqrt(\sum_i (x_i - mean)^2 \over n-1)
        https://wiki.python.org/moin/NumericAndScientificRecipes
762433
def stdev(x):
    
    """
    from math import sqrt
    n = len(x)
    mean = sum(x) / float(n)
    std = sqrt(sum((a - mean)**2 for a in x) / float(n - 1))
    return std
549272
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
        
        # Get original mean and standard deviations
        mean, stddevs = super().get_mean_and_stddevs(
            sctx, rctx, dctx, imt, stddev_types)
        cff = SInterCan15Mid.SITE_COEFFS[imt]
        mean += np.log(cff['mf'])
        return mean, stddevs
1060461
def _get_stddevs(self, C, distance, stddev_types):
        
        stddevs = []
        for stddev_type in stddev_types:
            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
            if stddev_type == const.StdDev.TOTAL:
                sigma = C["s1"] + (C["s2"] / (1.0 +
                                   ((distance / C["s3"]) ** 2.)))
                stddevs.append(sigma + np.zeros_like(distance))
        return stddevs
496612
def root_mean_square(X):
    '''  '''
    segment_width = X.shape[1]
    return np.sqrt(np.sum(X * X, axis=1) / segment_width)
149274
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        # Check that the GSIM supports the standard deviations requested
        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
                   for stddev_type in stddev_types)
        coe = self.COEFFS[imt]
        mean = (self._get_magnitude_scaling(coe, rup.mag) +
                self._get_distance_scaling(coe, dists.rhypo) +
                self._get_azimuth_correction(coe, dists.azimuth))
        # Convert to g
        if imt.name in "SA PGA":
            mean = np.log(np.exp(mean) / (100.0 * g))
        # Compute std
        stddevs = self._compute_std(coe, stddev_types, dists.azimuth.shape)
        return mean, stddevs
193160
public static double StdDev( int[] values, double mean ){
        double  stddev = 0;
        double  diff;
        int     hits;
        int     total = 0;

        // for all values
        for ( int i = 0, n = values.length; i < n; i++ )
        {
            hits = values[i];
            diff = (double) i - mean;
            // accumulate std.dev.
            stddev += diff * diff * hits;
            // accumalate total
            total += hits;
        }

        return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );
    }
1179608
public function stdDev(){
		
		Number::setScale(static::NUMERIC_FUNCTIONS_SCALE);
		
		$mean = $this->average();
		$squares = new static();
		
		foreach($this->_Arr as $num){
			$squares->add(Number::pow(Number::sub(\strval($num), $mean), '2'));
		}
		
		return Number::sqrt($squares->average());
		
	}
1166659
def gausspars(data):
    
    N, mean, d = len(data), 0., 0.
    if N < 1:
        return "", ""
    if N == 1:
        return data[0], 0
    for j in range(N):
        mean += old_div(data[j], float(N))
    for j in range(N):
        d += (data[j] - mean)**2
    stdev = np.sqrt(d * (1./(float(N - 1))))
    return mean, stdev
1048914
def stats():
    ''''''
    import re
    import sys
    import math
    values = []
    for line in sys.stdin:
        values.extend(map(float, re.findall(r'\d+\.?\d+', line)))

    mean = sum(values) / len(values)
    variance = sum((val - mean) ** 2 for val in values) / len(values)
    print '%3i items; mean: %10.5f; std-dev: %10.5f' % (
        len(values), mean, math.sqrt(variance))
1325234
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
                   for stddev_type in stddev_types)

        C = self.COEFFS[imt]
        mean = self._get_mean(
            C, rup.mag, rup.rake, rup.dip, dists.rrup, dists.rjb
        )
        stddevs = self._get_stddevs(C, rup.mag, stddev_types, dists.rrup.size)

        return mean, stddevs
1278566
def get_mean_and_std(dataset):
    """"""
    dataloader = torch.utils.data.DataLoader(
        dataset, batch_size=1, shuffle=True, num_workers=2
    )
    mean = torch.zeros(3)
    std = torch.zeros(3)
    print("==> Computing mean and std..")
    for inputs, _ in dataloader:
        for i in range(3):
            mean[i] += inputs[:, i, :, :].mean()
            std[i] += inputs[:, i, :, :].std()
    mean.div_(len(dataset))
    std.div_(len(dataset))
    return mean, std
714720
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
                   for stddev_type in stddev_types)

        C = self.COEFFS[imt]
        mean = (self._get_magnitude_scaling(C, rup.mag) +
                self._get_distance_scaling(C, rup.mag, dists.rhypo))
        if imt.name in "SA PGA":
            mean = np.log(np.exp(mean) / (100.0 * g))
        stddevs = self._compute_std(C, stddev_types, len(dists.rhypo))
        return mean, stddevs
446669
def _get_stddevs(self, C, stddev_types, rup, imt, num_sites):
        
        stddevs = []
        for stddev_type in stddev_types:
            sigma_mean = self._compute_standard_dev(rup, imt, C)
            sigma_tot = np.sqrt((sigma_mean ** 2) + (C['SigmaReg'] ** 2))
            sigma_tot = np.log10(np.exp(sigma_tot))
            stddevs.append(sigma_tot + np.zeros(num_sites))
        return stddevs
1347308
def standard_deviation(data, period):
    
    catch_errors.check_for_period_error(data, period)

    stds = [np.std(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))]

    stds = fill_for_noncomputable_vals(data, stds)
    return stds
1085939
def _get_stddevs(self, C, stddev_types, stddev_shape):
        
        stddevs = []
        for stddev_type in stddev_types:
            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
            if stddev_type == const.StdDev.TOTAL:
                stddevs.append(C["sigtot"] + np.zeros(stddev_shape))
            elif stddev_type == const.StdDev.INTRA_EVENT:
                stddevs.append(C['sig2'] + np.zeros(stddev_shape))
            elif stddev_type == const.StdDev.INTER_EVENT:
                stddevs.append(C['sig1'] + np.zeros(stddev_shape))
        return stddevs
1251810
def _get_stddevs(self, stddev_types, rrup):
        
        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
                   for stddev_type in stddev_types)
        std = np.zeros_like(rrup)
        std[rrup <= 20] = 0.23
        idx = (rrup > 20) & (rrup <= 30)
        std[idx] = 0.23 - 0.03 * np.log10(rrup[idx] / 20) / np.log10(30. / 20.)
        std[rrup > 30] = 0.20
        # convert from log10 to ln
        std = np.log(10 ** std)
        return [std for stddev_type in stddev_types]
283850
def normalize_std_array(vector):
  """"""

  # Initializes variables
  length = 1
  n_samples = len(vector)
  mean = numpy.ndarray((length,), 'float64')
  std = numpy.ndarray((length,), 'float64')
  mean.fill(0)
  std.fill(0)

  # Computes mean and variance
  for array in vector:
    x = array.astype('float64')
    mean += x
    std += (x ** 2)

  mean /= n_samples
  std /= n_samples
  std -= (mean ** 2)
  std = std ** 0.5
  arrayset = numpy.ndarray(shape=(n_samples,mean.shape[0]), dtype=numpy.float64)

  for i in range (0, n_samples):
    arrayset[i,:] = (vector[i]-mean) / std
  return arrayset