Example #1
0
def jacobi_mus(n, t, low):
    t = mpmath.mpf(t)
    low = mpmath.mpf(low)
    half = mpmath.mpf('.5')
    n_idx = mpmath.mpf(1) * np.arange(1, n)
    rn = (2 * n_idx + 1) / (2 * t) - (2 * n_idx + 1) * (half - 1) / (
        2 * (2 * n_idx + half + 1) * (2 * n_idx + half - 1))
    sn = n_idx * (2 * n_idx + 1) * (2 * n_idx - 1) * (n_idx + half - 1) / (
        4 * (2 * n_idx + half) * (2 * n_idx + half - 1)**2 *
        (2 * n_idx + half - 2))
    us = jacobi_us(n, low, t)

    low2 = low * low
    t_inv = half / t
    e0 = mpmath.exp(-t) * t_inv
    et = mpmath.exp(-t * low2) * low * t_inv
    tt = mpmath.sqrt(t)
    alpha0 = jacobi_alpha(0)
    mu0 = mpmath.sqrt(
        mpmath.pi) / 2 / tt * (mpmath.erfc(low * tt) - mpmath.erfc(tt))
    mu1 = t_inv * mu0 - e0 + et - alpha0 * mu0

    mus = [mu0, mu1]
    for i in range(1, n - 1):
        mu2 = rn[i - 1] * mu1 + sn[i - 1] * mu0 + us[i - 1]
        mus.append(mu2)
        mu1, mu0 = mu2, mu1
    return np.array(mus)
Example #2
0
def laguerre_mu0(t, low=0):
    if t == 0:
        return 1 - low
    else:
        tt = mpmath.sqrt(t)
        return mpmath.sqrt(
            mpmath.pi) / 2 / tt * (mpmath.erfc(low * tt) - mpmath.erfc(tt))
Example #3
0
    def CalculatePosition(self, NDcoors, t, NDvel=None):
        A = self.As
        X = self.roots
        NDz0 = self.NDz0
        NDw0 = self.NDw0

        NDxy = 0.
        suma = sum([A[i] * X[i] for i in range(4)])

        for i in range(4):
            NDxy += A[i] / X[i] * cmath.exp(X[i]**2 * t) * mpmath.erfc(
                -X[i] * math.sqrt(t))

        NDcoors[0] = float(NDxy.real)
        NDcoors[1] = float(NDxy.imag)
        NDcoors[2] = float(NDz0 + t * NDw0)

        if NDvel is None:
            NDxy = 0.0
            for i in range(4):
                NDxy += A[i] * X[i] * cmath.exp(X[i]**2 * t) * mpmath.erfc(
                    -X[i] * math.sqrt(t))
            NDvel[0] = float(NDxy.real)
            NDvel[1] = float(NDxy.imag)
            NDvel[2] = float(NDw0)
Example #4
0
def fdq(x0, seta2, seff2):

    xm = x0 / np.sqrt(2. * seta2)
    tau = lamda1 * seff2 / np.sqrt(2. * seta2)

    intgr1 = erfc(tau - xm)
    intgr2 = erfc(tau + xm)

    return .5 * (seff2 / (1. + lamda2 * seff2)) * (intgr1 + intgr2)
Example #5
0
def fdq(x0, seta2, seff2):

    xm = x0/np.sqrt(2.*seta2)
    tau = lamda1*seff2/np.sqrt(2.*seta2)  

    intgr1 = erfc(tau-xm)
    intgr2 = erfc(tau+xm)

    return .5*(seff2/(1.+lamda2*seff2))*(intgr1+intgr2)
def fl0xnz(x0, seta2, seff2):

    xm = x0 / np.sqrt(2. * seta2)
    tau = lamda1 * seff2 / np.sqrt(2. * seta2)
    ki = theta * (1. + lamda2 * seff2) / np.sqrt(2. * seta2)

    intgr1 = erfc(tau + ki - xm)
    intgr2 = erfc(tau + ki + xm)

    return .5 * (intgr1 + intgr2)
Example #7
0
def fl2(x0, seta2, seff2):

    coeff = 1./np.sqrt(np.pi)
    xm = x0/np.sqrt(2.*seta2)
    tau = lamda1*seff2/np.sqrt(2.*seta2)

    intgr1 = -coeff*(tau-xm)*exp(-(tau-xm)**2) +(.5+(tau-xm)**2)*erfc(tau-xm)
    intgr2 = -coeff*(tau+xm)*exp(-(tau+xm)**2) +(.5+(tau+xm)**2)*erfc(tau+xm)

    return (seta2/(1.+lamda2*seff2)**2)*(intgr1+intgr2)  
def fl0xnz(x0, seta2, seff2):

    xm = x0/np.sqrt(2.*seta2)
    tau = lamda1*seff2/np.sqrt(2.*seta2)
    ki = theta*(1.+lamda2*seff2)/np.sqrt(2.*seta2) 

    intgr1 = erfc(tau+ki-xm)
    intgr2 = erfc(tau+ki+xm)

    return .5*(intgr1+intgr2)
Example #9
0
def fl1(x0, seta2, seff2):

    coeff = 1./np.sqrt(np.pi)
    xm = x0/np.sqrt(2.*seta2)
    tau = lamda1*seff2/np.sqrt(2.*seta2)

    intgr1 = coeff*exp(-(tau-xm)**2) -(tau-xm)*erfc(tau-xm)
    intgr2 = coeff*exp(-(tau+xm)**2) -(tau+xm)*erfc(tau+xm)

    return .5*(np.sqrt(2.*seta2)/(1.+lamda2*seff2))*(intgr1+intgr2)
Example #10
0
def test_bounds_for_Q1():
    """
    These bounds are from:

        Jiangping Wang and Dapeng Wu,
        "Tight bounds for the first order Marcum Q-function"
        Wireless Communications and Mobile Computing,
        Volume 12, Issue 4, March 2012, Pages 293-301.

    """
    with mpmath.workdps(50):
        sqrt2 = mpmath.sqrt(2)
        sqrthalfpi = mpmath.sqrt(mpmath.pi / 2)
        for b in [mpmath.mp.mpf(1), mpmath.mp.mpf(10)]:
            for a in [b / 16, 0.5 * b, 0.875 * b, b]:
                q1 = marcumq(1, a, b)

                sinhab = mpmath.sinh(a * b)
                i0ab = mpmath.besseli(0, a * b)

                # lower bound when 0 <= a <= b
                lb = (mpmath.sqrt(mpmath.pi / 8) * b * i0ab / sinhab *
                      (mpmath.erfc((b - a) / sqrt2) - mpmath.erfc(
                          (b + a) / sqrt2)))
                assert lb < q1

                # upper bound when 0 <= a <= b
                ub = ((i0ab + 3) / (mpmath.exp(a * b) + 3) * (
                    mpmath.exp(-(b - a)**2 / 2) + a * sqrthalfpi * mpmath.erfc(
                        (b - a) / sqrt2) + 3 * mpmath.exp(-(a**2 + b**2) / 2)))
                assert q1 < ub, ("marcumq(1, a, b) < ub for a = %s,  b = %s" %
                                 (a, b))

        for a in [mpmath.mp.mpf(1), mpmath.mp.mpf(10)]:
            for b in [b / 16, 0.5 * b, 0.875 * b, b]:
                q1 = marcumq(1, a, b)

                sinhab = mpmath.sinh(a * b)
                i0ab = mpmath.besseli(0, a * b)

                # lower bound when 0 <= b <= a
                lb = (1 - sqrthalfpi * b * i0ab / sinhab *
                      (mpmath.erf(a / sqrt2) - mpmath.erf(
                          (a - b) / sqrt2) / 2 - mpmath.erf(
                              (a + b) / sqrt2) / 2))
                assert lb < q1

                # upper bound when 0 <= b <= a
                ub = (
                    1 - i0ab / (mpmath.exp(a * b) + 3) *
                    (4 * mpmath.exp(-a**2 / 2) - mpmath.exp(-(b - a)**2 / 2) -
                     3 * mpmath.exp(-(a**2 + b**2) / 2) + a * sqrthalfpi *
                     (mpmath.erfc(-a / sqrt2) - mpmath.erfc((b - a) / sqrt2))))
                assert q1 < ub, ("marcumq(1, a, b) < ub for a = %s,  b = %s" %
                                 (a, b))
Example #11
0
def fl1(x0, seta2, seff2):

    coeff = 1. / np.sqrt(np.pi)
    xm = x0 / np.sqrt(2. * seta2)
    tau = lamda1 * seff2 / np.sqrt(2. * seta2)

    intgr1 = coeff * exp(-(tau - xm)**2) - (tau - xm) * erfc(tau - xm)
    intgr2 = coeff * exp(-(tau + xm)**2) - (tau + xm) * erfc(tau + xm)

    return .5 * (np.sqrt(2. * seta2) /
                 (1. + lamda2 * seff2)) * (intgr1 + intgr2)
Example #12
0
def fq(x0, seta2, seff2):

    coeff = 1./np.sqrt(np.pi)
    xm = x0/np.sqrt(2.*seta2)
    tau = lamda1*seff2/np.sqrt(2.*seta2)
    psi = lamda2*seff2*x0/np.sqrt(2.*seta2)
    
    intgr1 = coeff*(-tau+2*psi+xm)*exp(-(tau+xm)**2) +.5*(1.+2.*(tau-psi)**2)*erfc(tau+xm)
    intgr2 = coeff*(-tau-2*psi-xm)*exp(-(tau-xm)**2) +.5*(1.+2.*(tau+psi)**2)*erfc(tau-xm)
    intgr3 = .5*x0**2*(erf(tau+xm)+erf(tau-xm))

    return (seta2/(1.+lamda2*seff2)**2)*(intgr1+intgr2)+intgr3
Example #13
0
def fl2(x0, seta2, seff2):

    coeff = 1. / np.sqrt(np.pi)
    xm = x0 / np.sqrt(2. * seta2)
    tau = lamda1 * seff2 / np.sqrt(2. * seta2)

    intgr1 = -coeff * (tau - xm) * exp(-(tau - xm)**2) + (
        .5 + (tau - xm)**2) * erfc(tau - xm)
    intgr2 = -coeff * (tau + xm) * exp(-(tau + xm)**2) + (
        .5 + (tau + xm)**2) * erfc(tau + xm)

    return (seta2 / (1. + lamda2 * seff2)**2) * (intgr1 + intgr2)
Example #14
0
def fq(x0, seta2, seff2):

    coeff = 1. / np.sqrt(np.pi)
    xm = x0 / np.sqrt(2. * seta2)
    tau = lamda1 * seff2 / np.sqrt(2. * seta2)
    psi = lamda2 * seff2 * x0 / np.sqrt(2. * seta2)

    intgr1 = coeff * (-tau + 2 * psi + xm) * exp(-(tau + xm)**2) + .5 * (
        1. + 2. * (tau - psi)**2) * erfc(tau + xm)
    intgr2 = coeff * (-tau - 2 * psi - xm) * exp(-(tau - xm)**2) + .5 * (
        1. + 2. * (tau + psi)**2) * erfc(tau - xm)
    intgr3 = .5 * x0**2 * (erf(tau + xm) + erf(tau - xm))

    return (seta2 / (1. + lamda2 * seff2)**2) * (intgr1 + intgr2) + intgr3
def func(t, k):
    # k must be an integer in [0, 100)
    t = mpmath.mpf(t)
    y100 = (t + 2*k + 1)/2
    y = y100/100
    x = 4/y - 4
    return mpmath.erfc(x)*mpmath.exp(x**2)
Example #16
0
def avg_x2(eta, avx):
   
    iT = beta/(2.*sigmaeff2)
    
    bm = -beta*lamda*eta
    bp = beta*lamda*eta
    
    tp = np.sqrt(iT)*(-eta+lamda1)
    tm = np.sqrt(iT)*(eta+lamda1)

    nom1 = (tp/(2.*iT*np.sqrt(iT)) - (lamda1+avx)/iT)*exp(-tp**2) + (1./(2.*iT*np.sqrt(iT)) + (lamda1+avx)**2/np.sqrt(iT))*(np.sqrt(np.pi)/2.)*erfc(tp)
    nom2 = (tm/(2.*iT*np.sqrt(iT)) - (lamda1-avx)/iT)*exp(-tm**2) + (1./(2.*iT*np.sqrt(iT)) + (lamda1-avx)**2/np.sqrt(iT))*(np.sqrt(np.pi)/2.)*erfc(tm)
    dnom1 = .5*np.sqrt(np.pi/iT)*erfc(tp)
    dnom2 = .5*np.sqrt(np.pi/iT)*erfc(tm)

    integrand = (exp(bm)*nom1+exp(bp)*nom2)/(exp(bm)*dnom1+exp(bp)*dnom2)   

    return integrand  
Example #17
0
def avg_x(eta):
    

    iT = beta/(2.*sigmaeff2)
    
    bm = -beta*lamda*eta
    bp = beta*lamda*eta
    
    tp = np.sqrt(iT)*(-eta+lamda1)
    tm = np.sqrt(iT)*(eta+lamda1)

    nom1 = -(lamda1/2.)*np.sqrt(np.pi/iT)*erfc(tp) + (.5/iT)*exp(-tp**2)
    nom2 = (lamda1/2.)*np.sqrt(np.pi/iT)*erfc(tm) - (.5/iT)*exp(-tm**2)
    dnom1 = .5*np.sqrt(np.pi/iT)*erfc(tp)
    dnom2 = .5*np.sqrt(np.pi/iT)*erfc(tm)

    integrand = (exp(bm)*nom1+exp(bp)*nom2)/(exp(bm)*dnom1+exp(bp)*dnom2)
    
    return integrand
Example #18
0
def tabulate_erfc():
    k = mpmath.mpf('3.75')
    values = []
    for t in chebrt:
        x = k*(t+1)/(1-t)
        values.append((1+2*x)*mpmath.exp(x*x)*mpmath.erfc(x))
    values = np.array(values)
    fac = mpmath.mpf(2) / ngrids
    tab = values.dot(cs.T) * fac
    tab[0] /= 2
    return tab
Example #19
0
def PlasmaDispersion(z, n=0):
  #if(hasattr(x,'__iter__')):
  # Values from Callen , Fundamentals of Plasma Physics

  Z =  1.j * mp.sqrt(mp.pi) * mp.exp(- z**2) * mp.erfc(-1.j * z)

  if   n == 0 : return  Z
  elif n == 1 : return  1. + z * Z 
  elif n == 2 : return  z + z**2 * Z
  elif n == 3 : return  0.5 * ( 1. + 2. * z**2 * ( 1. + z * Z))
  else        : raise TypeError("BUG : Plasma Dispersion function only for N <= 3 defined") 
  """  
Example #20
0
 def CalculateBassetForce(self, FB, t):
     A = self.As
     X = self.roots
     C1 = self.C1
     basset_dimensional_coeff = self.basset_dimensional_coeff
     pp = self.pp
     sqrt_t = math.sqrt(t)
     FhZ = sum([(1j * A[i] / X[i] - A[i] * X[i]) * X[i] *
                cmath.exp(X[i]**2 * t) * mpmath.erfc(-X[i] * sqrt_t)
                for i in range(len(X))])
     FhZ *= basset_dimensional_coeff * C1 * math.sqrt(math.pi)
     FB[0] = float(FhZ.real)
     FB[1] = float(FhZ.imag)
     FB[2] = 0.0
Example #21
0
def PlasmaDispersion(z, n=0):
    #if(hasattr(x,'__iter__')):
    # Values from Callen , Fundamentals of Plasma Physics

    Z = 1.j * mp.sqrt(mp.pi) * mp.exp(-z**2) * mp.erfc(-1.j * z)

    if n == 0: return Z
    elif n == 1: return 1. + z * Z
    elif n == 2: return z + z**2 * Z
    elif n == 3: return 0.5 * (1. + 2. * z**2 * (1. + z * Z))
    else:
        raise TypeError(
            "BUG : Plasma Dispersion function only for N <= 3 defined")
    """  
Example #22
0
 def CalculatePosition(self, NDcoors, t):
     A = self.As
     X = self.roots
     NDz0 = self.NDz0
     NDw0 = self.NDw0
     
     NDxy = 0.
     
     for i in range(4):
         NDxy += A[i] / X[i] * cmath.exp(X[i] ** 2 * t) * mpmath.erfc(- X[i] * math.sqrt(t))
     
     NDcoors[0] = float(NDxy.real)
     NDcoors[1] = float(NDxy.imag)
     NDcoors[2] = float(NDz0 + t * NDw0)
Example #23
0
    def CalculatePosition(self, NDcoors, t):
        A = self.As
        X = self.roots
        NDz0 = self.NDz0
        NDw0 = self.NDw0

        NDxy = 0.

        for i in range(4):
            NDxy += A[i] / X[i] * cmath.exp(X[i]**2 * t) * mpmath.erfc(
                -X[i] * math.sqrt(t))

        NDcoors[0] = float(NDxy.real)
        NDcoors[1] = float(NDxy.imag)
        NDcoors[2] = float(NDz0 + t * NDw0)
Example #24
0
def var(a, b):
    """
    Variance of the Benktander I distribution.

    Variable names follow the convention used on wikipedia.
    """
    _validate_ab(a, b)
    with mpmath.extradps(5):
        a = mpmath.mpf(a)
        b = mpmath.mpf(b)
        sb = mpmath.sqrt(b)
        t = (a - mpmath.mp.one) / (2 * sb)
        sqrtpi = mpmath.sqrt(mpmath.pi)
        return (-sb + a * mpmath.exp(t**2) * sqrtpi * mpmath.erfc(t)) / (a**2 *
                                                                         sb)
def voigt_slow(a, u):
    """ Calculate the voigt function to very high accuracy.
    Uses numerical integration, so is slow.  Answer is correct to 20
    significant figures.
    Note this needs `mpmath` or `sympy` to be installed.
    """
    try:
        import mpmath as mp
    except ImportError:
        from sympy import mpmath as mp
    with mp.workdps(20):
        z = mp.mpc(u, a)
        result = mp.exp(-z * z) * mp.erfc(-1j * z)

    return result.real
Example #26
0
def test_erf_complex():
    # need to increase mpmath precision for this test
    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
    try:
        mpmath.mp.dps = 70
        x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11))
        x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11))
        points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(),y2.ravel()]

        assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points,
                          vectorized=False, rtol=1e-13)
        assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points,
                          vectorized=False, rtol=1e-13)
    finally:
        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
Example #27
0
def cdf(x, mu=0, sigma=1):
    """
    CDF of the Lévy distribution.
    """
    if sigma <= 0:
        raise ValueError('sigma must be positive.')

    if x <= mu:
        return mpmath.zero

    with mpmath.extradps(5):
        x = mpmath.mpf(x)
        mu = mpmath.mpf(mu)
        sigma = mpmath.mpf(sigma)
        arg = mpmath.sqrt(sigma / (2 * (x - mu)))
        return mpmath.erfc(arg)
Example #28
0
def scattered_pulse(x, sigma, taud, area=True, log=True):
    if area:
        amplitude = (1.0 / taud) * (
            1.0 / np.sqrt(2 * np.pi * sigma**2)
        )  #convolution of gaussian of unit area and exponential of unit area
    else:
        amplitude = 1.0  #convolution of gaussian of unit amplitude and exponential of unit peak

    xbar = sigma / (taud * np.sqrt(2)) - x / (sigma * np.sqrt(2))

    if log:  #compute in the natural log
        retval = np.zeros_like(xbar)
        for i in range(len(x)):
            retval[i] = mp.exp(
                mp.log(amplitude * (sigma / 2) * np.sqrt(np.pi / 2)) +
                0.5 * sigma**2 / taud**2 - x[i] / taud +
                float(mp.log(mp.erfc(xbar[i]))))
        return retval * 2  #factor of 2?
    else:
        return amplitude * (sigma / 2) * np.sqrt(np.pi / 2) * np.exp(
            0.5 * sigma**2 / taud**2) * np.exp(
                -x / taud) * (1 - special.erf(xbar))
Example #29
0
def test_erf_complex():
    # need to increase mpmath precision for this test
    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
    try:
        mpmath.mp.dps = 70
        x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11))
        x2, y2 = np.meshgrid(np.logspace(-80, .8, 31),
                             np.logspace(-80, .8, 11))
        points = np.r_[x1.ravel(), x2.ravel()] + 1j * np.r_[y1.ravel(),
                                                            y2.ravel()]

        assert_func_equal(sc.erf,
                          lambda x: complex(mpmath.erf(x)),
                          points,
                          vectorized=False,
                          rtol=1e-13)
        assert_func_equal(sc.erfc,
                          lambda x: complex(mpmath.erfc(x)),
                          points,
                          vectorized=False,
                          rtol=1e-13)
    finally:
        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
Example #30
0
def qfunc(x):
	return 0.5*mp.erfc(x/np.sqrt(2))
Example #31
0
def wofz(x, y):
    z = mpmath.mpc(x, y)
    w = mpmath.exp(-z**2) * mpmath.erfc(z * -1j)
    return w.real, w.imag
Example #32
0
 def test_erfc_complex(self):
     assert_mpmath_equal(sc.erfc,
                         _exception_to_nan(lambda z: mpmath.erfc(z)),
                         [ComplexArg()], n=200)
Example #33
0
 def test_erfc(self):
     assert_mpmath_equal(sc.erfc,
                         _exception_to_nan(lambda z: mpmath.erfc(z)),
                         [Arg()])
Example #34
0
			def ps0_lp (κ, s):
				k = σ * κ
				return (1 - mpmath.exp(k**2/2)/2 * ( mpmath.exp(+κ*x[i]) * mpmath.erfc((b+k)/sqrt2)
				                                   + mpmath.exp(-κ*x[i]) * (1+mpmath.erf((b-k)/sqrt2)) ) ) / s
Example #35
0
        x = k*(t+1)/(1-t)
        values.append((1+2*x)*mpmath.exp(x*x)*mpmath.erfc(x))
    values = np.array(values)
    fac = mpmath.mpf(2) / ngrids
    tab = values.dot(cs.T) * fac
    tab[0] /= 2
    return tab

def clenshaw_d1(tab, t):
    d0 = 0
    d1 = tab[ngrids-1]
    for k in reversed(range(1, ngrids-1)):
        d1, d0 = t * 2 * d1 - d0 + tab[k], d1
    return t * d1 - d0 + tab[0]

def erfc(x, tab=None):
    if tab is None:
        tab = tabulate_erfc().astype(float)
    k = 3.75
    t = (x-k)/ (x+k)
    v = clenshaw_d1(tab, t)
    return v / (1 + 2*x) / np.exp(x * x)

if __name__ == '__main__':
    table = tabulate_erfc().astype(float)
    for c in np.arange(-20, 8):
        x = mpmath.mpf('1.5')**c
        ref = mpmath.erfc(x)
        v = erfc(float(x), table)
        print('erfc',1.5**c, 'erfc(x)', v, 'error', float(v / ref - 1))
Example #36
0
 def test_erfc_complex(self):
     assert_mpmath_equal(sc.erfc,
                         _exception_to_nan(lambda z: mpmath.erfc(z)),
                         [ComplexArg()],
                         n=200)
Example #37
0
 def test_erfc(self):
     assert_mpmath_equal(sc.erfc,
                         _exception_to_nan(lambda z: mpmath.erfc(z)),
                         [Arg()])
Example #38
0
def wofz(x, y):
    z = mpmath.mpc(x, y)
    w = mpmath.exp(-z**2) * mpmath.erfc(z * -1j)
    return w.real, w.imag
def f45(x):
    # log_erfc
    return mpmath.log(mpmath.erfc(x))
def f44(x):
    # erfc
    return mpmath.erfc(x)
    def DoSamplingSpecificXConditionedAll(self, w, a, ind, fitErrExcludingInd, varLast, bLogDebug=False):
        assert (a > 0) and (w >= 0) and (varLast >= 0), __file__ + ': DoSamplingSpecificXConditionedAll: invalid inputs'                        
        
        etaIndSquared = varLast / self._hNormSquared[ind]       
        assert (etaIndSquared > 0), __file__ + ': etaIndSquared is not strictly positive'     
        dotProduct = np.sum(fitErrExcludingInd * self._h[:, ind])
        muIndComponents = (dotProduct / self._hNormSquared[ind], -etaIndSquared / a)
        muInd = sum(muIndComponents)
        
        """
        When y is big, calculating uInd is a challenge since there are numerical issues. We're 
        trying to multiply a very small number (which equals 0 due to finite floating point
        representation) and a very large number, which is prone to returning 0.        
        """  
        y = -muInd / PlazeGibbsSamplerReconstructor.CONST_SQRT_2 / math.sqrt(etaIndSquared)
                        
        uInd = (w / a) * \
            mpmath.sqrt(etaIndSquared) * PlazeGibbsSamplerReconstructor.CONST_SQRT_HALF_PI * mpmath.erfc(y) * \
            mpmath.exp(y * y)
                                               
        uIndFloat = float(uInd) # Convert to an ordinary Python float
        assert (uIndFloat >= 0), __file__ + ': uIndFloat is negative: ' + str(uIndFloat) + \
            ' w=' + str(w) + \
            ' a=' + str(a) + \
            ' etaIndSquared=' + str(etaIndSquared) + \
            ' y=' + str(y) + \
            ' muIndComp=(' + str(muIndComponents[0]) + ',' + str(muIndComponents[1]) + ')' + \
            ' dotProduct=' + str(dotProduct) + \
            ' hNormSquared=' + str(self._hNormSquared[ind])
        
        if uIndFloat == float('inf'):
            wInd = 1
        else:
            wInd = uIndFloat / (uIndFloat + (1 - w))            
                                                                                                                
        if ((wInd < 0) or (wInd > 1)):
            raise ValueError('uInd is {0} and wInd is {1}'.format(uInd, wInd))                                    
        
        if pymc.rbernoulli(wInd):
            # With probability wInd, generate a sample from a truncated Gaussian r.v. (support (0,Inf))
#             xSample = pymc.rtruncated_normal(muInd, 1/etaIndSquared, a=0)[0]
            try:            
                xSample = NumericalHelper.RandomNonnegativeNormal(muInd, etaIndSquared)
            except:
                fmtString = "Caught exception at {0}: NNN({1}, {2}). Intm. calc.: {3}, {4}, {5}. Exception: {6}"
                msg = fmtString.format(ind,
                                       muInd, etaIndSquared,                                                
                                       muIndComponents[0],
                                       muIndComponents[1],
                                       varLast,
                                       sys.exc_info()[0])
                logging.error(msg)
                xSample = 0; # XXX: Due to a numerical problem
            else:
                # Check the value of xSample 
                if (xSample < 0):
                    fmtString = "Invalid xSample at {0}: NNN({1}, {2}) ~> sample {3}. Intm. calc.: {4}, {5}, {6}"
                    logging.error(fmtString.format(ind,
                                                   muInd, etaIndSquared, xSample,                                               
                                                   muIndComponents[0],
                                                   muIndComponents[1],
                                                   varLast))
                    # Don't throw an exception
    #                raise ValueError('xSample cannot be negative')
                    xSample = 0; # XXX: Also due to a numerical problem, but no exception raised   
        else:
            # With probability (1-wInd), generate 0
            xSample = 0
        
        if bLogDebug:
            fmtString = '      {0}/{1}: {2:.5e}, {3:.5f}={4:.5f}-{5:.5f}, {6:.5e}, {7:.5e}: {8:.5e}'
            logging.debug(fmtString.format(self._samplerIter,
                                           ind, 
                                           etaIndSquared, 
                                           muInd, 
                                           muIndComponents[0],
                                           -muIndComponents[1],
                                           uIndFloat, 
                                           wInd, 
                                           xSample))
            
        return xSample
def erfcx_mp(x):
    x = mpmath.mpf(x)
    return mpmath.erfc(x) * mpmath.exp(x*x)