Test for poor convergence based on three function evaluations.

    This test evaluates the function at the three points and returns false if
    the relative error is greater than 1e-3.
422271
def _poor_convergence(z, r, f, bn, mvec):
    
    check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j)
    diffs = []
    ftests = []
    for check_point in check_points:
        rtest = r * check_point
        ztest = z + rtest
        ftest = f(ztest)
        # Evaluate powerseries:
        comp = np.sum(bn * np.power(check_point, mvec))
        ftests.append(ftest)
        diffs.append(comp - ftest)

    max_abs_error = np.max(np.abs(diffs))
    max_f_value = np.max(np.abs(ftests))
    return max_abs_error > 1e-3 * max_f_value
1144288
def _mean_absolute_error(y, y_pred, w):
    """"""
    return np.average(np.abs(y_pred - y), weights=w)
868044
def cal_p_bm3(v, k, p_ref=0.0):
    
    vvr = v / k[0]
    p = (p_ref - 0.5 * (3. * k[1] - 5. * p_ref) * (1. - vvr**(-2. / 3.)) +
         9. / 8. * k[1] * (k[2] - 4. + 35. / 9. * p_ref / k[1]) *
         (1. - vvr**(-2. / 3.))**2.) * vvr**(-5. / 3.)
    return p
1227466
function guess_errors() {
		var el = 0,
			b = [0, 0, 0, 0, 0],
			t = [];

		var deg_lambda = 0,
			lambda = [1, 0, 0, 0, 0]; // error+erasure locator poly

		// Berlekamp-Massey algorithm to determine error+erasure locator polynomial

		for (var r = 0; r < 4; r++) {
			var discr = calc_discrepancy(lambda, r + 1); // Compute discrepancy at the r-th step in poly-form

			if (discr !== 0) {
				deg_lambda = 0;

				for (var i = 0; i < 5; i++) {
					t[i] = lambda[i] ^ gmult(discr, b[i]);

					if (t[i]) deg_lambda = i;
				}

				if (2 * el <= r) {
					el = r + 1 - el;

					for (i = 0; i < 5; i++) {
						b[i] = gmult(lambda[i], ginv(discr));
					}
				}

				lambda = t.slice(); // copy
			}

			b.unshift(0); // shift => mul by x
		}

		// Find roots of the locator polynomial.

		var errloc = find_errors(lambda);

		var errors = errloc.length;

		if (errors < 1 || errors > 2) return false;

		if (deg_lambda !== errors) return false; // deg(lambda) unequal to number of roots => uncorrectable error

		// Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo x**(4)). Also find deg(omega).

		var omega = [0, 0, 0, 0, 0];

		for (var i = 0; i < 4; i++) {
			var t = 0;

			for (var j = 0; j < i; j++) {
				t ^= gmult(syndrome[i + 1 - j], lambda[j]);
			}

			omega[i] = t;
		}

		// Compute error values in poly-form.

		for (r = 0; r < errors; r++) {
			var t = 0;
			var pos = errloc[r];
			var root = 31 - pos;

			for (i = 0; i < 4; i++) // evaluate Omega at alpha^(-i)
			{
				t ^= gmult(omega[i], gexp[(root * i) % 31]);
			}

			if (t) // evaluate Lambda' (derivative) at alpha^(-i); all odd powers disappear
			{
				var denom = gmult(lambda[1], 1) ^ gmult(lambda[3], gexp[(root * 2) % 31]);

				if (denom === 0) return false;

				if (pos > 12) pos -= 14;

				codeword[pos] ^= gmult(t, ginv(denom));
			}
		}

		return true;
	}
402708
def p_try_statement_3(self, p):
        """"""
        p[0] = ast.Try(statements=p[2], catch=p[3], fin=p[4])
575021
def _has_converged(pi_star, pi):
    
    node_count = pi.shape[0]
    EPS = 10e-6
    for i in range(node_count):
        if pi[i] - pi_star[i] > EPS:
            return False

    return True
1043978
def reeval(self, X, fit, func, ask, args=()):
        
        self.fit = list(fit)
        self.fitre = list(fit)
        self.idx = self.indices(fit)
        if not len(self.idx):
            return self.idx
        evals = int(self.evaluations) if self.f_aggregate else 1
        fagg = np.median if self.f_aggregate is None else self.f_aggregate
        for i in self.idx:
            X_i = X[i]
            if self.epsilon:
                if self.parallel:
                    self.fitre[i] = fagg(func(ask(evals, X_i, self.epsilon), *args))
                else:
                    self.fitre[i] = fagg([func(ask(1, X_i, self.epsilon)[0], *args)
                                            for _k in xrange(evals)])
            else:
                self.fitre[i] = fagg([func(X_i, *args) for _k in xrange(evals)])
        self.evaluations_just_done = evals * len(self.idx)
        return self.fit, self.fitre, self.idx
1199665
def mean_absolute_error(seq, correct):
    
    assert len(seq) == len(correct)
    diffs = [abs(a-b) for a, b in zip(seq, correct)]
    return sum(diffs)/float(len(diffs))
412702
def demo_err():
    
    max_order = 7
    n = 20
    l = 0.25
    fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}'
    fmt2 = '{0: <5d}\t{1:20.18f}\t{2: >21.18f}\t{3: >21.18f}\t{4: >21.18f}'
    x = np.cumsum(np.random.rand(n)*l)
    x = np.concatenate((x[::-1]*-1, x))
    lst = []
    derivs = np.zeros(n)
    for order in range(max_order+1):
        print('Order', order)
        for m in range(1+order//2, n+1):
            sub_x = x[n-m:n+m]
            derivs[m-1] = derivatives_at_point_by_finite_diff(
                sub_x, np.exp(sub_x), 0, order)[order]
        print(fmt1.format('m', 'val', 'diff', 'analytical error',
                          'diff/analytical'))
        for m in range(1, n):
            print(fmt2.format(
                (m+1)*2, derivs[m], derivs[m]-derivs[m-1],
                derivs[m]-1, (derivs[m]-derivs[m-1])/(derivs[m]-1)))
        lst.append((derivs[-1], abs(derivs[-1]-derivs[-2])))
    print(np.array(lst))
542347
function tryCatchReject3(f, x, y, thisArg, next) {
			try {
				f.call(thisArg, x, y, next);
			} catch(e) {
				next.become(new Rejected(e));
			}
		}
193297
def _tie_correct(sample):
    
    tc = 0
    n = sum(sample.values())

    if n < 2:
        return 1.0  # Avoid a ``ZeroDivisionError``.

    for k in sorted(sample.keys()):
        tc += math.pow(sample[k], 3) - sample[k]
    tc = 1 - tc / (math.pow(n, 3) - n)

    return tc
481746
def _check_convergence(self, P, Q, i, type):
        
        normP = linalg.norm(P, Inf)
        normQ = linalg.norm(Q, Inf)

        if self.verbose:
            logger.info("  %s  %3d   %10.3e   %10.3e" % (type,i, normP, normQ))

        if (normP < self.tolerance) and (normQ < self.tolerance):
            converged = True
        else:
            converged = False

        return converged
252038
def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter,
              ytol=None, full_output=False, disp=True):
    '''
    '''
    fa = f(a, *args)
    fb = f(b, *args)
    if fa*fb > 0.0:
        raise ValueError("f(a) and f(b) must have different signs") 
    elif fa == 0.0:
        return a
    elif fb == 0.0:
        return b

    dm = b - a
    iterations = 0.0
    
    for i in range(maxiter):
        dm *= 0.5
        xm = a + dm
        fm = f(xm, *args)
        if fm*fa >= 0.0:
            a = xm
        abs_dm = fabs(dm)
        
        if fm == 0.0:
            return xm
        elif ytol is not None:
            if (abs_dm < xtol + rtol*abs_dm) and abs(fm) < ytol:
                return xm
        elif (abs_dm < xtol + rtol*abs_dm):
            return xm
    raise UnconvergedError("Failed to converge after %d iterations" %maxiter)
446378
def evaluate(self, X, y):
        
        scores = self.ops.flatten(list(self.pipe(X)))
        if not hasattr(y, "shape"):
            y = self.ops.flatten(y)
        scores = scores.reshape(y.shape)
        if len(scores.shape) == 1:
            correct = ((scores >= 0.5) == (y >= 0.5)).sum()
        else:
            correct = (scores.argmax(axis=1) == y.argmax(axis=1)).sum()
        return correct / y.shape[0]
574116
private double[] lineSearchBacktrack(Function func, double[] dir, double[] x,
      double[] newX, double[] grad, double lastValue)
      throws MaxEvaluationsExceeded {

    double normGradInDir = ArrayMath.innerProduct(dir, grad);
    say("(" + nf.format(normGradInDir) + ")");
    if (normGradInDir > 0) {
      say("{WARNING--- direction of positive gradient chosen!}");
    }

    // c1 can be anything between 0 and 1, exclusive (usu. 1/10 - 1/2)
    double step, c1;

    // for first few steps, we have less confidence in our initial step-size a
    // so scale back quicker
    if (its <= 2) {
      step = 0.1;
      c1 = 0.1;
    } else {
      step = 1.0;
      c1 = 0.1;
    }

    // should be small e.g. 10^-5 ... 10^-1
    double c = 0.01;

    // double v = func.valueAt(x);
    // c = c * mult(grad, dir);
    c = c * normGradInDir;

    double[] newPoint = new double[3];

    while ((newPoint[f] = func.valueAt((plusAndConstMult(x, dir, step, newX)))) > lastValue
        + c * step) {
      fevals += 1;
      if (newPoint[f] < lastValue) {
        // an improvement, but not good enough... suspicious!
        say("!");
      } else {
        say(".");
      }
      step = c1 * step;
    }

    newPoint[a] = step;
    fevals += 1;
    if (fevals > maxFevals) {
      throw new MaxEvaluationsExceeded(
          " Exceeded during linesearch() Function ");
    }

    return newPoint;
  }
1153751
def errors(self):
        

        n = self.n
        dt = self.dt
        order = self._order
        sigma = self.sigma

        error = np.zeros(order + 1)
        std = np.zeros(order + 1)

        if n == 0:
            return (error, std)

        if order == 0:
            error[0] = sigma/sqrt(n)
            std[0] = sigma/sqrt(n)

        elif order == 1:
            if n > 1:
                error[0] = sigma * sqrt(2*(2*n-1) / (n*(n+1)))
                error[1] = sigma * sqrt(12. / (n*(n*n-1)*dt*dt))
            std[0] = sigma * sqrt((2*(2*n-1)) / (n*(n+1)))
            std[1] = (sigma/dt) * sqrt(12. / (n*(n*n-1)))

        elif order == 2:
            dt2 = dt * dt

            if n >= 3:
                error[0] = sigma * sqrt(3*(3*n*n-3*n+2) / (n*(n+1)*(n+2)))
                error[1] = sigma * sqrt(12*(16*n*n-30*n+11) /
                                        (n*(n*n-1)*(n*n-4)*dt2))
                error[2] = sigma * sqrt(720/(n*(n*n-1)*(n*n-4)*dt2*dt2))

            std[0] = sigma * sqrt((3*(3*n*n - 3*n + 2)) / (n*(n+1)*(n+2)))
            std[1] = (sigma/dt) * sqrt((12*(16*n*n - 30*n + 11)) /
                                       (n*(n*n - 1)*(n*n - 4)))
            std[2] = (sigma/dt2) * sqrt(720 / (n*(n*n-1)*(n*n-4)))

        return error, std
1212739
def reject_sv(m, s, y):
    
    mp = m + 0.5 * s**2 * (-1. + y**2 * np.exp(-m))
    ntries = 0
    while True:
        ntries += 1
        x = stats.norm.rvs(loc=mp, scale=s)
        u = stats.uniform.rvs()
        if np.log(u) < - 0.5 * y**2 * (np.exp(-x) - np.exp(-m) * (1. + m - x)):
            break
        if ntries > 1000:
            print('1000 failed attempt, m,s,y=%f, %f, %f' % (m, s, y))
            break
    return x