# [R Squared](http://en.wikipedia.org/wiki/Coefficient_of_determination)  The r-squared value of data compared with a function `f` is the sum of the squared differences between the prediction and the actual value.
540350
function r_squared(data, f) {
        if (data.length < 2) return 1;

        // Compute the average y value for the actual
        // data set in order to compute the
        // _total sum of squares_
        var sum = 0, average;
        for (var i = 0; i < data.length; i++) {
            sum += data[i][1];
        }
        average = sum / data.length;

        // Compute the total sum of squares - the
        // squared difference between each point
        // and the average of all points.
        var sum_of_squares = 0;
        for (var j = 0; j < data.length; j++) {
            sum_of_squares += Math.pow(average - data[j][1], 2);
        }

        // Finally estimate the error: the squared
        // difference between the estimate and the actual data
        // value at each point.
        var err = 0;
        for (var k = 0; k < data.length; k++) {
            err += Math.pow(data[k][1] - f(data[k][0]), 2);
        }

        // As the error grows larger, its ratio to the
        // sum of squares increases and the r squared
        // value grows lower.
        return 1 - (err / sum_of_squares);
    }
887927
def calculate_rsq(self):
        
        assert hasattr(self, 'betas'), 'no betas found, please run regression before rsq'

        explained_times = self.design_matrix.sum(axis = 0) != 0

        explained_signal = self.predict_from_design_matrix(self.design_matrix)
        self.rsq = 1.0 - np.sum((explained_signal[:,explained_times] - self.resampled_signal[:,explained_times])**2, axis = -1) / np.sum(self.resampled_signal[:,explained_times].squeeze()**2, axis = -1)
        self.ssr = np.sum((explained_signal[:,explained_times] - self.resampled_signal[:,explained_times])**2, axis = -1)
        return np.squeeze(self.rsq)
106310
def _distance_stats_sqr_fast_generic(x, y, dcov_function):
    """"""
    covariance_xy_sqr = dcov_function(x, y)
    variance_x_sqr = dcov_function(x, x)
    variance_y_sqr = dcov_function(y, y)
    denominator_sqr_signed = variance_x_sqr * variance_y_sqr
    denominator_sqr = np.absolute(denominator_sqr_signed)
    denominator = _sqrt(denominator_sqr)

    # Comparisons using a tolerance can change results if the
    # covariance has a similar order of magnitude
    if denominator == 0.0:
        correlation_xy_sqr = denominator.dtype.type(0)
    else:
        correlation_xy_sqr = covariance_xy_sqr / denominator

    return Stats(covariance_xy=covariance_xy_sqr,
                 correlation_xy=correlation_xy_sqr,
                 variance_x=variance_x_sqr,
                 variance_y=variance_y_sqr)
1063813
def value(self):
        """"""
        return self._sign[1] * self.S0 * norm.cdf(
            self._sign[1] * self.d1, 0.0, 1.0
        ) - self._sign[1] * self.K * np.exp(-self.r * self.T) * norm.cdf(
            self._sign[1] * self.d2, 0.0, 1.0
        )
1295493
function(pos) {
        var x = this.x, y = this.y;
        var sq = pos.squaredNorm();
        this.x = x * pos.x + y * pos.y; this.y = y * pos.x - x * pos.y;
        return this.$scale(1 / sq);
    }
412975
function rgeom(prob) {
      var scale;

      if (prob <= 0 || prob > 1) { return function() { return NaN; }; }

      scale = prob / (1 - prob);

      return function() {
         return rpois(rexp(scale)())();
      };
   }
1290827
def _is(self, r, val):
        
        if not is_register(r) or val is None:
            return False

        r = r.lower()
        if is_register(val):
            return self.eq(r, val)

        if is_number(val):
            val = str(valnum(val))
        else:
            val = str(val)

        if val[0] == '(':
            val = self.mem[val[1:-1]]

        return self.regs[r] == val
70764
function rf(df1, df2) {
      var rchisqRatio;

      rchisqRatio = function(d) { return chisq.rchisq(d)() / d; };

      if (df1 <= 0 || df2 <= 0) { return function() { return NaN; }; }

      return function() {
         return rchisqRatio(df1) / rchisqRatio(df2);
      };
   }
81036
def F(self, **kwargs):
        '''
        
        '''
        Eg = self.Eg_Gamma_0(**kwargs)
        Delta_SO = self.Delta_SO(**kwargs)
        Ep = self.Ep(**kwargs)
        meff = self.meff_e_Gamma_0(**kwargs)
        return (1./meff-1-(Ep*(Eg+2.*Delta_SO/3.))/(Eg*(Eg+Delta_SO)))/2
200404
private static double[] calcLinReg(double[] xData, double[] yData) {
        double sumX = 0;
        double sumY = 0;
        double prod = 0;
        int nstat = xData.length;
        double[] regCoef = new double[3]; //(intercept, gradient, r2)

        double meanYValue = mean(yData);
        double meanXValue = mean(xData);

        //calculating regression coefficients
        for (int i = 0; i < nstat; i++) {
            sumX += (xData[i] - meanXValue) * (xData[i] - meanXValue);
            sumY += (yData[i] - meanYValue) * (yData[i] - meanYValue);
            prod += (xData[i] - meanXValue) * (yData[i] - meanYValue);
        }
        if (sumX > 0 && sumY > 0) {
            regCoef[1] = prod / sumX;  //gradient
            regCoef[0] = meanYValue - regCoef[1] * meanXValue; //intercept
            regCoef[2] = Math.pow((prod / Math.sqrt(sumX * sumY)), 2); //r2
        }
        return regCoef;
    }
773549
public SDVariable squaredNorm(SDVariable x, boolean keepDims, int... dimensions) {
        return squaredNorm(null, x, keepDims, dimensions);
    }
661080
public SDVariable squaredDifference(SDVariable x) {
        return squaredDifference(sameDiff.generateNewVarName(SquaredDifferenceOp.OP_NAME,0),x);
    }
383521
def obfn_dfd(self):
        
        """
        XF = sl.rfftn(self.obfn_fvar(), mp_Nv, mp_axisN)
        DX = np.moveaxis(sl.irfftn(sl.inner(mp_Df, XF, mp_axisM),
                                   mp_Nv, mp_axisN), mp_axisM,
                         self.cri.axisM)
        return np.sum((self.W*(DX-self.S))**2)/2.0
905320
def _calculateXi(self, r):
        
        a = self._a
        return  (r - a)/(r + a)
289986
def erf(x):
    
    try:
        return math.erf(x)
    except TypeError:
        pass
    if isinstance(x, GVar):
        f = math.erf(x.mean)
        dfdx = 2. * math.exp(- x.mean ** 2) / math.sqrt(math.pi)
        return gvar_function(x, f, dfdx)
    else:
        x = numpy.asarray(x)
        ans = numpy.empty(x.shape, x.dtype)
        for i in range(x.size):
            try:
                ans.flat[i] = erf(x.flat[i])
            except TypeError:
                xi = x.flat[i]
                f = math.erf(xi.mean)
                dfdx = 2. * math.exp(- xi.mean ** 2) / math.sqrt(math.pi)
                ans.flat[i] = gvar_function(xi, f, dfdx)
        return ans
742620
function R(iid, name, val, flags) {
        var aret;
        var bFlags = decodeBitPattern(flags, 2); // [isGlobal, isScriptLocal]

        if (sandbox.analysis && sandbox.analysis.read) {
            aret = sandbox.analysis.read(iid, name, val, bFlags[0], bFlags[1]);
            if (aret) {
                val = aret.result;
            }
        }
        return (lastComputedValue = val);
    }
1096009
def F(self, x):
        
        if isinstance(x, np.ndarray):
            nfwvals = np.ones_like(x)
            inds1 = np.where(x < 1)
            inds2 = np.where(x > 1)
            nfwvals[inds1] = (1 - x[inds1] ** 2) ** -.5 * np.arctanh((1 - x[inds1] ** 2) ** .5)
            nfwvals[inds2] = (x[inds2] ** 2 - 1) ** -.5 * np.arctan((x[inds2] ** 2 - 1) ** .5)
            return nfwvals

        elif isinstance(x, float) or isinstance(x, int):
            if x == 1:
                return 1
            if x < 1:
                return (1 - x ** 2) ** -.5 * np.arctanh((1 - x ** 2) ** .5)
            else:
                return (x ** 2 - 1) ** -.5 * np.arctan((x ** 2 - 1) ** .5)