Calculate quantiles.
6957
private void init() {
        quantiles = new double[data.length][8];
        for (int i = 0; i < data.length; i++) {
            int n = data[i].length;
            Arrays.sort(data[i]);
            quantiles[i][1] = data[i][n / 4];
            quantiles[i][2] = data[i][n / 2];
            quantiles[i][3] = data[i][3 * n / 4];
            quantiles[i][5] = quantiles[i][3] - quantiles[i][1]; // interquartile range
            quantiles[i][6] = quantiles[i][1] - 1.5 * quantiles[i][5];
            quantiles[i][7] = quantiles[i][3] + 1.5 * quantiles[i][5];
            quantiles[i][0] = quantiles[i][6] < data[i][0] ? data[i][0] : quantiles[i][6];
            quantiles[i][4] = quantiles[i][7] > data[i][data[i].length - 1] ? data[i][data[i].length - 1] : quantiles[i][7];
        }
    }
665035
public Double getQuantile(int quantile, int base) {
    if (getCount() == 0)
      return null;
    
    if ((quantile > base) || (quantile <= 0) || (base <= 0))
      throw new IllegalArgumentException("Incorrect quantile/base specified.");
    
    double quantileFraq = (double) quantile / base;
    
    int index = (int) Math.round(quantileFraq * (getCount() - 1));
    
    return (double) data.get(index) + shift;
  }
729502
def param_describe(params, quant=95, axis=0):
    """"""
    par = np.mean(params, axis=axis)
    lo, up = perc(quant)
    p_up = np.percentile(params, up, axis=axis)
    p_lo = np.percentile(params, lo, axis=axis)
    return par, p_lo, p_up
444797
def trimiquants(self, col: str, inf: float):
        
        try:
            self.df = self._trimquants(col, inf, None)
        except Exception as e:
            self.err(e, self.trimiquants, "Can not trim inferior quantiles")
1087767
def calculateBestIntervals(self):
        """"""
        self.__intervals = []
        self.__readAPI(self.__getURL())
        today = datetime.datetime.now().date()

        self.__validInterval(datetime.date(2008, 1, 1), today)
        self.__logger.info("Total number of intervals: " +
                           str(len(self.__intervals)))
        self.__lastDay = today.strftime("%Y-%m-%d")
895776
def trimsquants(self, col: str, sup: float):
        
        try:
            self.df = self._trimquants(col, None, sup)
        except Exception as e:
            self.err(e, self.trimsquants, "Can not trim superior quantiles")
1045101
def quantile(q, variable, weight_variable = None, filter_variable = None):
    
    def formula(entity, period):
        value = entity(variable, period)
        if weight_variable is not None:
            weight = entity(weight_variable, period)
        weight = entity.filled_array(1)
        if filter_variable is not None:
            filter_value = entity(filter_variable, period)
            weight = filter_value * weight

        labels = arange(1, q + 1)
        quantile, _ = weightedcalcs_quantiles(
            value,
            labels,
            weight,
            return_quantiles = True,
            )
        if filter_variable is not None:
            quantile = where(weight > 0, quantile, -1)
        return quantile

    return formula
752178
public void clear() {

        for(int i=1; i<=2*m+3; i++) {
            n[i] = i+1;
        }

        f[1] = 0F;
        f[2*m+3] = 1F;

        for(int i=1; i<=m; i++) {
            f[2*i+1] = quantiles[i-1];
        }

        for(int i=1; i<=m+1; i++) {
            f[2*i] = (f[2*i-1] + f[2*i+1])/2F;
        }

        for(int i=1; i<=2*m+3; i++) {
            d[i] = 1F + 2*(m+1)*f[i];
        }
        isInitializing = true;
        ni = 1;

    }
1022952
function quantiles( vector, num ) {
		var numValues = vector.length,
			qValues = new Array( num+1 ),
			vec, id, value;

		// Create a copy of the input vector:
		vec = vector.slice();

		// Sort the input vector:
		vec.sort( function ( a, b ) {
			return a - b;
		});

		// 0th quantile is the min:
		qValues[ 0 ] = vec[ 0 ];

		// Max defines the quantile upper bound:
		qValues[ num ] = vec[ numValues-1 ];

		// Get the quantiles...
		for ( var i = 1; i < num; i++ ) {

			// Calculate the vector index marking the quantile:
			id = ( numValues * i / num ) - 1;

			// Is the index an integer?
			if ( id === parseInt( id, 10 ) ) {
				// Value is the average between the value at id and id+1:
				value = ( vec[ id ] + vec[ id+1 ] ) / 2.0;
			} else {
				// Round up to the next index:
				id = Math.ceil( id );
				value = vec[ id ];
			}
			qValues[ i ] = value;
		} // end FOR i
		return qValues;
	}
842066
public static double quantile(double val, double loc, double scale, double shape1, double shape2) {
    if(!(val >= 0.) || !(val <= 1.)) {
      return Double.NaN;
    }
    if(val == 0.) {
      if(shape2 <= 0.) {
        return shape1 < 0. ? loc + scale / shape1 : Double.NEGATIVE_INFINITY;
      }
      else {
        return loc + (shape1 != 0. //
            ? scale / shape1 * (1. - FastMath.pow(shape2, -shape1)) //
            : scale * FastMath.log(shape2));
      }
    }
    if(val == 1.) {
      return shape1 <= 0. ? Double.NEGATIVE_INFINITY : loc + scale / shape1;
    }
    val = -FastMath.log(val);
    if(shape2 != 0.) {
      val = (1 - FastMath.exp(-shape2 * val)) / shape2;
    }
    val = -FastMath.log(val);
    if(shape1 != 0.) {
      val = (1 - FastMath.exp(-shape1 * val)) / shape1;
    }
    return loc + scale * val;
  }
764914
protected double quantile(double p, double xmin, double xmax, double eps) {
        if (eps <= 0.0) {
            throw new IllegalArgumentException("Invalid epsilon: " + eps);            
        }
        
        while (Math.abs(xmax - xmin) > eps) {
            double xmed = (xmax + xmin) / 2;
            if (cdf(xmed) > p) {
                xmax = xmed;
            } else {
                xmin = xmed;
            }
        }

        return xmin;
    }
306508
def _calculateValue(self):
        """"""
        cmd = '''
              UPDATE V
                 SET value = (
                     SELECT MAX(value)
                       FROM Q
                      WHERE V.state = Q.state
                      GROUP BY state);'''
        self._cur.execute(cmd)
        self._conn.commit()
640029
def calc_containment(self):
        """"""

        hists = self.hists
        hists_out = self._hists_eff
        quantiles = [0.34, 0.68, 0.90, 0.95]
        cth_axis_idx = dict(evclass=2, evtype=3)
        for k in ['evclass']:  # ,'evtype']:

            print(k)

            non = hists['%s_psf_on' % k]
            noff = hists['%s_psf_off' % k]
            alpha = hists['%s_alpha' % k][..., None]
            if k == 'evclass':
                sep = self._sep_bins[None, :, None, 1:]
            else:
                sep = self._sep_bins[None, None, :, None, 1:]

            qval, qerr = calc_quantiles(sep, non, noff, alpha, quantiles)
            for i, q in enumerate(quantiles):
                hists_out['%s_cth_q%2i' % (k, q * 100)] = qval[i]
                hists_out['%s_cth_q%2i_err' % (k, q * 100)] = qerr[i]

            non = np.sum(non, axis=cth_axis_idx[k])
            noff = np.sum(noff, axis=cth_axis_idx[k])
            alpha = np.squeeze(alpha, axis=cth_axis_idx[k])
            sep = np.squeeze(sep, axis=cth_axis_idx[k])

            qval, qerr = calc_quantiles(sep, non, noff, alpha, quantiles)
            for i, q in enumerate(quantiles):
                hists_out['%s_q%2i' % (k, q * 100)] = qval[i]
                hists_out['%s_q%2i_err' % (k, q * 100)] = qerr[i]
314153
public static double quantile(double val, double sigma) {
    if(!(val >= 0.) || !(val <= 1.)) {
      return Double.NaN;
    }
    if(val == 0.) {
      return 0.;
    }
    if(val == 1.) {
      return Double.POSITIVE_INFINITY;
    }
    return sigma * FastMath.sqrt(-2. * FastMath.log(1. - val));
  }
1338247
def _pvalues_all(self):
        """"""
        return 2.0 * (1.0 - scs.t.cdf(np.abs(self._tstat_all), self.df_err))
1062090
public void computeStats() {
    if (statsComputed.getAndSet(true)) {
      return;
    }

    if (curSize == 0) {
      return;
    }

    Arrays.sort(values, 0, curSize); // to compute percentileValues
    min = values[0];
    max = values[curSize - 1];

    total = 0L;
    double sumSquares = 0.0;
    for (int i = 0; i < curSize; ++i) {
      total += values[i];
      sumSquares += values[i] * values[i];
    }
    mean = (double) total / curSize;
    if (curSize == 1) {
      variance = 0d;
    } else {
      variance = (sumSquares - ((double) total * total / curSize)) / (curSize - 1);
    }
    stddev = Math.sqrt(variance);

    computePercentiles(curSize);
  }
1095024
def _psturng(q, r, v):
    """"""
    if q < 0.:
        raise ValueError('q should be >= 0')

    opt_func = lambda p, r, v : abs(_qsturng(p, r, v) - q)

    if v == 1:
        if q < _qsturng(.9, r, 1):
            return .1
        elif q > _qsturng(.999, r, 1):
            return .001
        return 1. - fminbound(opt_func, .9, .999, args=(r,v))
    else:
        if q < _qsturng(.1, r, v):
            return .9
        elif q > _qsturng(.999, r, v):
            return .001
        return 1. - fminbound(opt_func, .1, .999, args=(r,v))