Python math.erf() Examples

The following are 30 code examples for showing how to use math.erf(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: python_moztelemetry   Author: mozilla   File: stats.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def ndtr(a):
    """
    Returns the area under the Gaussian probability density function,
    integrated from minus infinity to x.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtr.html#scipy.special.ndtr

    """
    sqrth = math.sqrt(2) / 2
    x = float(a) * sqrth
    z = abs(x)
    if z < sqrth:
        y = 0.5 + 0.5 * math.erf(x)
    else:
        y = 0.5 * math.erfc(z)
        if x > 0:
            y = 1 - y
    return y 
Example 2
Project: pyKriging   Author: capaulson   File: regressionkrige.py    License: MIT License 6 votes vote down vote up
def expimp(self, x):
        '''
        Returns the expected improvement at the design vector X in the model
        :param x: A real world coordinates design vector
        :return EI: The expected improvement value at the point x in the model
        '''
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = ((y_min - self.predict_normalized(x)) * (0.5 + 0.5*m.erf((
                      1./np.sqrt(2.))*((y_min - self.predict_normalized(x)) /
                                       S))))
            EI_two = ((S * (1. / np.sqrt(2. * np.pi))) * (np.exp(-(1./2.) *
                      ((y_min - self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 3
Project: pyKriging   Author: capaulson   File: krige.py    License: MIT License 6 votes vote down vote up
def expimp(self, x):
        '''
        Returns the expected improvement at the design vector X in the model
        :param x: A real world coordinates design vector
        :return EI: The expected improvement value at the point x in the model
        '''
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = ((y_min - self.predict_normalized(x)) * (0.5 + 0.5*m.erf((
                      1./np.sqrt(2.))*((y_min - self.predict_normalized(x)) /
                                       S))))
            EI_two = ((S * (1. / np.sqrt(2. * np.pi))) * (np.exp(-(1./2.) *
                      ((y_min - self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 4
Project: spectral   Author: spectralpython   File: resampling.py    License: MIT License 6 votes vote down vote up
def erf_local(x):
    # save the sign of x
    sign = 1 if x >= 0 else -1
    x = abs(x)

    # constants
    a1 =  0.254829592
    a2 = -0.284496736
    a3 =  1.421413741
    a4 = -1.453152027
    a5 =  1.061405429
    p  =  0.3275911

    # A&S formula 7.1.26
    t = 1.0/(1.0 + p*x)
    y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
    return sign*y # erf(-x) = -erf(x) 
Example 5
Project: PyChemia   Author: MaterialsDiscovery   File: mathematics.py    License: MIT License 6 votes vote down vote up
def integral_gaussian(a, b, mu, sigma):
    """
    Computes the integral of a gaussian centered
    in mu with a given sigma
    :param a:
    :param b:
    :param mu:
    :param sigma:
    :return:
    """

    # Integral from -\infty to a
    val_floor = 0.5 * (1 + math.erf((a - mu) / (sigma * math.sqrt(2.0))))

    # Integral from -\infty to b
    val_ceil = 0.5 * (1 + math.erf((b - mu) / (sigma * sqrt(2.0))))

    return val_ceil - val_floor 
Example 6
Project: Turing   Author: TuringApp   File: stats.py    License: MIT License 6 votes vote down vote up
def erfinv(y):
    # courtesy of
    # https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c#L15
    a = [0.886226899, -1.645349621, 0.914624893, -0.140543331]
    b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
    c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
    d = [3.543889200, 1.637067800]
    if y > 1:
        return None
    if y == 1:
        return math.copysign(1, y) * float("inf")
    if y <= 0.7:
        z = y * y
        num = (((a[3] * z + a[2]) * z + a[1]) * z + a[0])
        dem = ((((b[3] * z + b[2]) * z + b[1]) * z + b[0]) * z + 1.0)
        x = y * num / dem
    else:
        z = math.sqrt(-math.log((1.0 - abs(y)) / 2.0))
        num = ((c[3] * z + c[2]) * z + c[1]) * z + c[0]
        dem = (d[1] * z + d[0]) * z + 1.0
        x = (math.copysign(1.0, y)) * num / dem
    for _ in [1, 2]:
        x = x - (erf(x) - y) / ((2 / math.sqrt(trig.c_pi)) * math.exp(-x * x))
    return x 
Example 7
Project: pvfactors   Author: SunPower   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def integral_default_gaussian(y, x):
    """Calculate the value of the integral from x to y of the erf function

    Parameters
    ----------
    y : float
        upper limit
    x : float
        lower limit

    Returns
    -------
    float
        Calculated value of integral

    """
    return 0.5 * (math.erf(x) - math.erf(y)) 
Example 8
def sum_of_erf(mu, sigma, N=1000):
    """
    Compute the sum of erf term

    :param mu: The Gaussian mean
    :param sigma: The Gaussian sigma
    :param N: The number of iterations in the sum
    """
    from math import sqrt, erf

    sum1 = 0
    sum2 = N * erf((N + 1 - mu) / (sqrt(2) * sigma))
    sum3 = N * erf((-N - mu) / (sqrt(2) * sigma))
    for i in range(-N, N):
        sum1 += erf((i + 1 - mu) / (sqrt(2) * sigma))
    return -0.5 * (sum1 + sum2 + sum3) 
Example 9
Project: hadrian   Author: modelop   File: link.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        return unwrapForNorm(x, lambda y: (math.erf(y/math.sqrt(2.)) + 1.)/2.) 
Example 10
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 5 votes vote down vote up
def CDF(self, x):
        if (self.sigma == 0.0) and (x < self.mu):
            return 0.0
        elif (self.sigma == 0.0) and (x >= self.mu):
            return 1.0
        else:
            return 0.5 * (1.0 + math.erf((x - self.mu)/(self.sigma * math.sqrt(2.0)))) 
Example 11
Project: hadrian   Author: modelop   File: spec.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, a):
        try:
            return math.erf(a)
        except:
            raise PFARuntimeException("domain error", self.errcodeBase + 0, self.name, pos) 
Example 12
Project: tributary   Author: timkpaine   File: ops.py    License: Apache License 2.0 5 votes vote down vote up
def Erf(self):
    return unary(self, 'erf(' + str(self._name_no_id()) + ')', (lambda x: math.erf(self.value()))) 
Example 13
Project: tributary   Author: timkpaine   File: ops.py    License: Apache License 2.0 5 votes vote down vote up
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
    if ufunc == np.add:
        if isinstance(inputs[0], Node):
            return inputs[0].__add__(inputs[1])
        else:
            return inputs[1].__add__(inputs[0])
    elif ufunc == np.subtract:
        if isinstance(inputs[0], Node):
            return inputs[0].__sub__(inputs[1])
        else:
            return inputs[1].__sub__(inputs[0])
    elif ufunc == np.multiply:
        if isinstance(inputs[0], Node):
            return inputs[0].__mul__(inputs[1])
        else:
            return inputs[1].__mul__(inputs[0])
    elif ufunc == np.divide:
        if isinstance(inputs[0], Node):
            return inputs[0].__truediv__(inputs[1])
        else:
            return inputs[1].__truediv__(inputs[0])
    elif ufunc == np.sin:
        return inputs[0].sin()
    elif ufunc == np.cos:
        return inputs[0].cos()
    elif ufunc == np.tan:
        return inputs[0].tan()
    elif ufunc == np.arcsin:
        return inputs[0].asin()
    elif ufunc == np.arccos:
        return inputs[0].acos()
    elif ufunc == np.arctan:
        return inputs[0].atan()
    elif ufunc == np.exp:
        return inputs[0].exp()
    elif ufunc == sp.special.erf:
        return inputs[0].erf()
    raise NotImplementedError('Not Implemented!') 
Example 14
Project: tributary   Author: timkpaine   File: test_ops_lazy.py    License: Apache License 2.0 5 votes vote down vote up
def test_Erf(self):
        t = tl.Node(value=2)
        out = tl.Erf(t)
        assert out() == math.erf(2) 
Example 15
Project: tributary   Author: timkpaine   File: test_ops_streaming.py    License: Apache License 2.0 5 votes vote down vote up
def test_Erf(self):
        t = ts.Timer(foo, count=2)
        out = ts.Erf(t)
        assert ts.run(out) == [math.erf(1), math.erf(2)] 
Example 16
Project: tributary   Author: timkpaine   File: ops.py    License: Apache License 2.0 5 votes vote down vote up
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
    if ufunc == np.add:
        if isinstance(inputs[0], Node):
            return inputs[0].__add__(inputs[1])
        else:
            return inputs[1].__add__(inputs[0])
    elif ufunc == np.subtract:
        if isinstance(inputs[0], Node):
            return inputs[0].__sub__(inputs[1])
        else:
            return inputs[1].__sub__(inputs[0])
    elif ufunc == np.multiply:
        if isinstance(inputs[0], Node):
            return inputs[0].__mul__(inputs[1])
        else:
            return inputs[1].__mul__(inputs[0])
    elif ufunc == np.divide:
        if isinstance(inputs[0], Node):
            return inputs[0].__truediv__(inputs[1])
        else:
            return inputs[1].__truediv__(inputs[0])
    elif ufunc == np.sin:
        return inputs[0].sin()
    elif ufunc == np.cos:
        return inputs[0].cos()
    elif ufunc == np.tan:
        return inputs[0].tan()
    elif ufunc == np.arcsin:
        return inputs[0].asin()
    elif ufunc == np.arccos:
        return inputs[0].acos()
    elif ufunc == np.arctan:
        return inputs[0].atan()
    elif ufunc == np.exp:
        return inputs[0].exp()
    elif ufunc == sp.special.erf:
        return inputs[0].erf()
    raise NotImplementedError('Not Implemented!') 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def test_erf_erfc(self):
        tolerance = 15
        for x in itertools.count(0.0, 0.001):
            if x > 5.0:
                break
            self.assertAlmostEqual(math.erf(x), -math.erf(-x), places=tolerance)
            self.assertAlmostEqual(math.erfc(x), 2.0 - math.erfc(-x), places=tolerance)

            self.assertAlmostEqual(1.0 - math.erf(x), math.erfc(x), places=tolerance)
            self.assertAlmostEqual(1.0 - math.erf(-x), math.erfc(-x), places=tolerance)
            self.assertAlmostEqual(1.0 - math.erfc(x), math.erf(x), places=tolerance)
            self.assertAlmostEqual(1.0 - math.erfc(-x), math.erf(-x), places=tolerance) 
Example 18
Project: onnx-tensorflow   Author: onnx   File: test_node.py    License: Apache License 2.0 5 votes vote down vote up
def test_erf(self):
    if legacy_opset_pre_ver(9):
      raise unittest.SkipTest("ONNX version {} doesn't support Erf.".format(
          defs.onnx_opset_version()))
    node_def = helper.make_node("Erf", ["X"], ["Y"])
    x = self._get_rnd_float32(shape=[3, 4, 5])
    output = run_node(node_def, [x])
    exp_output = np.vectorize(math.erf)(x).astype(np.float32)
    np.testing.assert_allclose(output['Y'], exp_output, rtol=1e-6, atol=1e-6) 
Example 19
Project: pyKriging   Author: capaulson   File: regressionkrige.py    License: MIT License 5 votes vote down vote up
def weightedexpimp(self, x, w):
        """weighted expected improvement (Sobester et al. 2005)"""
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = w*((y_min - self.predict_normalized(x)) * (0.5 +
                        0.5*m.erf((1./np.sqrt(2.))*((y_min -
                                  self.predict_normalized(x)) / S))))
            EI_two = ((1. - w)*(S * (1. / np.sqrt(2. * np.pi))) *
                      (np.exp(-(1./2.) * ((y_min -
                       self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 20
Project: pyKriging   Author: capaulson   File: krige.py    License: MIT License 5 votes vote down vote up
def weightedexpimp(self, x, w):
        """weighted expected improvement (Sobester et al. 2005)"""
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = w*((y_min - self.predict_normalized(x)) * (0.5 +
                        0.5*m.erf((1./np.sqrt(2.))*((y_min -
                                  self.predict_normalized(x)) / S))))
            EI_two = ((1. - w)*(S * (1. / np.sqrt(2. * np.pi))) *
                      (np.exp(-(1./2.) * ((y_min -
                       self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 21
Project: HackerrankPractice   Author: marinskiy   File: 014. Day 6 - The Central Limit Theorem I.py    License: MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2)))


# inputs 
Example 22
Project: HackerrankPractice   Author: marinskiy   File: 012. Day 5 - Normal Distribution I.py    License: MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2))) 
Example 23
Project: HackerrankPractice   Author: marinskiy   File: 013. Day 5 - Normal Distribution II.py    License: MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2))) 
Example 24
Project: HackerrankPractice   Author: marinskiy   File: 015. Day 6 - The Central Limit Theorem II.py    License: MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2)))

# inputs 
Example 25
Project: ufora   Author: ufora   File: pure_math.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, val):
        return __inline_fora(
            """fun(@unnamed_args:(val), *args) {
                   PyFloat(math.erf(val.@m))
                   }"""
            )(val) 
Example 26
Project: ufora   Author: ufora   File: MathTestCases.py    License: Apache License 2.0 5 votes vote down vote up
def test_pure_python_math_module(self):
        vals = [1, -.5, 1.5, 0, 0.0, -2, -2.2, .2]

        # not being tested: math.asinh, math.atanh, math.lgamma, math.erfc, math.acos
        def f():
            functions = [
                math.sqrt, math.cos, math.sin, math.tan, math.asin, math.atan,
                math.acosh, math.cosh, math.sinh, math.tanh, math.ceil,
                math.erf, math.exp, math.expm1, math.factorial, math.floor,
                math.log, math.log10, math.log1p
            ]
            tr = []
            for idx1 in range(len(vals)):
                v1 = vals[idx1]
                for funIdx in range(len(functions)):
                    function = functions[funIdx]
                    try:
                        tr = tr + [function(v1)]
                    except ValueError as ex:
                        pass

            return tr

        r1 = self.evaluateWithExecutor(f)
        r2 = f()
        self.assertGreater(len(r1), 100)
        self.assertTrue(numpy.allclose(r1, r2, 1e-6)) 
Example 27
Project: chainer   Author: chainer   File: test_erf.py    License: MIT License 5 votes vote down vote up
def _erf_cpu(x, dtype):
    return numpy.vectorize(math.erf, otypes=[dtype])(x) 
Example 28
Project: chainer   Author: chainer   File: erf.py    License: MIT License 5 votes vote down vote up
def label(self):
        return 'erf' 
Example 29
Project: chainer   Author: chainer   File: erf.py    License: MIT License 5 votes vote down vote up
def forward_cpu(self, x):
        global _erf_cpu
        if _erf_cpu is None:
            try:
                from scipy import special
                _erf_cpu = special.erf
            except ImportError:
                warnings.warn(
                    'SciPy is not available. Forward computation of erf in CPU'
                    ' can be slow without SciPy.',
                    chainer.warnings.PerformanceWarning)
                _erf_cpu = numpy.vectorize(math.erf)
        self.retain_inputs((0,))
        return utils.force_array(_erf_cpu(x[0]), dtype=x[0].dtype), 
Example 30
Project: chainer   Author: chainer   File: erf.py    License: MIT License 5 votes vote down vote up
def forward_gpu(self, x):
        self.retain_inputs((0,))
        return cuda.elementwise(
            'T x', 'T y',
            'y = erf(x)',
            'elementwise_erf',
        )(x[0]),