# Python math.erfc() Examples

The following are code examples for showing how to use math.erfc(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
 Project: HydroGeoPy   Author: tachylyte   File: one_d_analytical.py    BSD 2-Clause "Simplified" License 6 votes
```def domenicoFlux(t, v, De, R, deg, x, c0, n):
''' t is time (T), v is velocity (L/T), De is effective hydrodynamic dispersion (including diffusion) (L^2/T),
R is retardation (-), deg is first order decay constant (1/T), x is position along path (L),
c0 is source concentration (M/L^3), n is effective porosity (-).
Return concentration (M/L^3) at position x'''
a = math.sqrt(1 + ((4 * deg * R * De) / (v**2)))
b = 1 / (2 * math.sqrt((De * t) / R))
c = (v * x) / (2 * De)
d = 0.5 * (1 + a) * math.exp(c * (1 - a)) * math.erfc((b * (x - ((v * t)/R)*a)))
e = 0.5 * (1 - a) * math.exp(c * (1 + a)) * math.erfc((b * (x + ((v * t)/R)*a)))
f = 1 / v
g = math.sqrt((R*De)/(math.pi*t))
h = math.exp(c*(1-a))
i = math.sqrt(R/(4*De*t))
j = (v*t)/R
k = x - (j*a)
l = math.exp(-1*(i*(k))**2)
m = f * g * h * l
o = ((n * v * c0) / 2) * (d + e + m)
return o ```
Example 2
 Project: sp800_22_tests   Author: dj-on-github   File: sp800_22_runs_test.py    GNU General Public License v2.0 6 votes
```def runs_test(bits):
n = len(bits)
zeroes,ones = count_ones_zeroes(bits)

prop = float(ones)/float(n)
print("  prop ",prop)

tau = 2.0/math.sqrt(n)
print("  tau ",tau)

if abs(prop-0.5) > tau:
return (False,0.0,None)

vobs = 1.0
for i in range(n-1):
if bits[i] != bits[i+1]:
vobs += 1.0

print("  vobs ",vobs)

p = math.erfc(abs(vobs - (2.0*n*prop*(1.0-prop)))/(2.0*math.sqrt(2.0*n)*prop*(1-prop) ))
success = (p >= 0.01)
return (success,p,None) ```
Example 3
```def aggregateSSRsByDate(dates, ssrs, skillset, rating, res, iter, dayIndex):
'''
Calculate Skillset Rating for a selected Skillset given a list of Top SSR Values
However, this will only calculate for the dates in the given list.
Those dates must correspond to existent SSR Values in the given SSR list
'''
sum = 0
while True:
sum = 0
rating += res
for date in dates:
for x in ssrs[skillset][date]:
sum += max(0, 2 / math.erfc(0.1 * (x - rating)) - 2)
if 2 ** (rating * 0.1) >= sum:
break
if iter == 11:
return rating, skillset, dayIndex
return aggregateSSRsByDate(dates, ssrs, skillset, rating - res, res / 2, iter + 1, dayIndex) ```
Example 4
```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 5
 Project: skultrafast   Author: Tillsten   File: backend_tester.py    BSD 3-Clause "New" or "Revised" License 5 votes
```def my_erfc(x):
return erfc(x) ```
Example 6
 Project: skultrafast   Author: Tillsten   File: backend_tester.py    BSD 3-Clause "New" or "Revised" License 5 votes
```def fast_erfc(x):
"""
Calculates the erfc near zero faster than
the libary function, but has a bigger error, which
is not a problem for us.

Parameters
----------
x: float
The array

Returns
-------
ret: float
The erfc of x.
"""
a1 = 0.278393
a2 = 0.230389
a3 = 0.000972
a4 = 0.078108
smaller = x < 0
if smaller:
x = x * -1.
bot = 1 + a1 * x + a2 * x * x + a3 * x * x * x + a4 * x * x * x * x
ret = 1. / (bot * bot * bot * bot)

if smaller:
ret = -ret + 2.

return ret ```
Example 7
 Project: HydroGeoPy   Author: tachylyte   File: one_d_analytical.py    BSD 2-Clause "Simplified" License 5 votes
```def domenicoConc(t, v, De, R, deg, x, c0):
''' t is time (T), v is velocity (L/T), De is effective hydrodynamic dispersion (including diffusion) (L^2/T),
R is retardation (-), deg is first order decay constant (1/T), x is position along path (L),
c0 is source concentration (M/L^3), n is effective porosity (-), N is input variable stehfestCoeff().
Return concentration (M/L^3) at position x'''
a = math.sqrt(1 + ((4 * deg * R * De) / (v**2)))
b = 1 / (2 * math.sqrt((De * t) / R))
c = b * ((x - ((v * t) / R)) * a)
d = math.erfc(c)
e = (v * x) / (2 * De)
f = math.exp(e * (1 - a))
g = math.erfc(b * ((x + ((v * t) / R) * a)))
h = math.exp(e * (1 + a))
i = c0  * ((f * d) + (h * g)) / 2
return i ```
Example 8
 Project: PyErf   Author: dougthor42   File: pyerf.py    GNU General Public License v3.0 5 votes
```def _erf(x):
"""
Port of cephes ``ndtr.c`` ``erf`` function.

See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
"""
T = [
9.60497373987051638749E0,
9.00260197203842689217E1,
2.23200534594684319226E3,
7.00332514112805075473E3,
5.55923013010394962768E4,
]

U = [
3.35617141647503099647E1,
5.21357949780152679795E2,
4.59432382970980127987E3,
2.26290000613890934246E4,
4.92673942608635921086E4,
]

# Shorcut special cases
if x == 0:
return 0
if x >= MAXVAL:
return 1
if x <= -MAXVAL:
return -1

if abs(x) > 1:
return 1 - erfc(x)

z = x * x
return x * _polevl(z, T, 4) / _p1evl(z, U, 5) ```
Example 9
```def __call__(self, val):
return __inline_fora(
"""fun(@unnamed_args:(val), *args) {
PyFloat(math.erfc([email protected]))
}"""
)(val) ```
Example 10
```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 11
```def _erfc_cpu(x, dtype):
return numpy.vectorize(math.erfc, otypes=[dtype])(x) ```
Example 12
```def _ndtr_cpu(x, dtype):
erfc = numpy.vectorize(
lambda x: 0.5 * math.erfc(-x / 2 ** 0.5))
return utils.force_array(erfc(x), dtype=dtype) ```
Example 13
```def _slow_ndtr_cpu(x):
return 0.5 * math.erfc(-x / 2 ** 0.5) ```
Example 14
```def label(self):
return 'erfc' ```
Example 15
```def forward_cpu(self, x):
global _erfc_cpu
if _erfc_cpu is None:
try:
from scipy import special
_erfc_cpu = special.erfc
except ImportError:
warnings.warn(
'SciPy is not available. Forward computation of erfc in'
' CPU can be slow without SciPy.',
chainer.warnings.PerformanceWarning)
_erfc_cpu = numpy.vectorize(math.erfc)
self.retain_inputs((0,))
return utils.force_array(_erfc_cpu(x[0]), dtype=x[0].dtype), ```
Example 16
```def erfc(x):
"""Elementwise complementary error function.

.. note::
Forward computation in CPU can be slow if
`SciPy <https://www.scipy.org/>`_ is not available.

Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.

Returns:
~chainer.Variable: Output variable.
"""
return Erfc().apply((x,))[0] ```
Example 17
 Project: sp800_22_tests   Author: dj-on-github   File: sp800_22_cumulative_sums_test.py    GNU General Public License v2.0 5 votes
```def normcdf(n):
return 0.5 * math.erfc(-n * math.sqrt(0.5)) ```
Example 18
 Project: sp800_22_tests   Author: dj-on-github   File: sp800_22_dft_test.py    GNU General Public License v2.0 5 votes
```def dft_test(bits):
n = len(bits)
if (n % 2) == 1:        # Make it an even number
bits = bits[:-1]

ts = list()             # Convert to +1,-1
for bit in bits:
ts.append((bit*2)-1)

ts_np = numpy.array(ts)
fs = numpy.fft.fft(ts_np)  # Compute DFT

if sys.version_info > (3,0):
mags = abs(fs)[:n//2] # Compute magnitudes of first half of sequence
else:
mags = abs(fs)[:n/2] # Compute magnitudes of first half of sequence

T = math.sqrt(math.log(1.0/0.05)*n) # Compute upper threshold
N0 = 0.95*n/2.0
print("  N0 = %f" % N0)

N1 = 0.0   # Count the peaks above the upper theshold
for mag in mags:
if mag < T:
N1 += 1.0
print("  N1 = %f" % N1)
d = (N1 - N0)/math.sqrt((n*0.95*0.05)/4) # Compute the P value
p = math.erfc(abs(d)/math.sqrt(2))

success = (p >= 0.01)
return (success,p,None) ```
Example 19
 Project: sp800_22_tests   Author: dj-on-github   File: sp800_22_monobit_test.py    GNU General Public License v2.0 5 votes
```def monobit_test(bits):
n = len(bits)

zeroes,ones = count_ones_zeroes(bits)
s = abs(ones-zeroes)
print("  Ones count   = %d" % ones)
print("  Zeroes count = %d" % zeroes)

p = math.erfc(float(s)/(math.sqrt(float(n)) * math.sqrt(2.0)))

success = (p >= 0.01)
return (success,p,None) ```
Example 20
```def normal_cdf(x):
"""Normal cumulative density function."""
# If X ~ N(0,1), returns P(X < x).
return math.erfc(-x / SQRT2) / 2.0 ```
Example 21
```def testFloatBasic(self):
x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float32)
y = (x + .5).astype(np.float32)     # no zero
z = (x + 15.5).astype(np.float32)   # all positive
k = np.arange(-0.90, 0.90, 0.25).astype(np.float32) # between -1 and 1

self._compareBoth(x, np.abs, tf.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, tf.neg)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, tf.inv)
self._compareBoth(x, np.square, tf.square)
self._compareBoth(z, np.sqrt, tf.sqrt)
self._compareBoth(z, self._rsqrt, tf.rsqrt)
self._compareBoth(x, np.exp, tf.exp)
self._compareBoth(z, np.log, tf.log)
self._compareBoth(z, np.log1p, tf.log1p)
self._compareBoth(x, np.tanh, tf.tanh)
self._compareBoth(x, self._sigmoid, tf.sigmoid)
self._compareBoth(y, np.sign, tf.sign)
self._compareBoth(x, np.sin, tf.sin)
self._compareBoth(x, np.cos, tf.cos)
self._compareBoth(k, np.arcsin, tf.asin)
self._compareBoth(k, np.arccos, tf.acos)
self._compareBoth(x, np.arctan, tf.atan)
self._compareBoth(x, np.tan, tf.tan)
self._compareBoth(
y,
np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
tf.lgamma)
self._compareBoth(x, np.vectorize(math.erf), tf.erf)
self._compareBoth(x, np.vectorize(math.erfc), tf.erfc)

self._compareBothSparse(x, np.abs, tf.abs)
self._compareBothSparse(x, np.negative, tf.neg)
self._compareBothSparse(x, np.square, tf.square)
self._compareBothSparse(z, np.sqrt, tf.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, tf.tanh)
self._compareBothSparse(y, np.sign, tf.sign)
self._compareBothSparse(x, np.vectorize(math.erf), tf.erf) ```
Example 22
```def testFloatEmpty(self):
x = np.empty((2, 0, 5), dtype=np.float32)
self._compareBoth(x, np.abs, tf.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, tf.neg)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(x, self._inv, tf.inv)
self._compareBoth(x, np.square, tf.square)
self._compareBoth(x, np.sqrt, tf.sqrt)
self._compareBoth(x, self._rsqrt, tf.rsqrt)
self._compareBoth(x, np.exp, tf.exp)
self._compareBoth(x, np.log, tf.log)
self._compareBoth(x, np.log1p, tf.log1p)
self._compareBoth(x, np.tanh, tf.tanh)
self._compareBoth(x, self._sigmoid, tf.sigmoid)
self._compareBoth(x, np.sign, tf.sign)
self._compareBoth(x, np.sin, tf.sin)
self._compareBoth(x, np.cos, tf.cos)
# Can't use vectorize below, so just use some arbitrary function
self._compareBoth(x, np.sign, tf.lgamma)
self._compareBoth(x, np.sign, tf.erf)
self._compareBoth(x, np.sign, tf.erfc)
self._compareBoth(x, np.tan, tf.tan)
self._compareBoth(x, np.arcsin, tf.asin)
self._compareBoth(x, np.arccos, tf.acos)
self._compareBoth(x, np.arctan, tf.atan)

self._compareBothSparse(x, np.abs, tf.abs)
self._compareBothSparse(x, np.negative, tf.neg)
self._compareBothSparse(x, np.square, tf.square)
self._compareBothSparse(x, np.sqrt, tf.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, tf.tanh)
self._compareBothSparse(x, np.sign, tf.sign)
self._compareBothSparse(x, np.sign, tf.erf) ```
Example 23
```def testDoubleBasic(self):
x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float64)
y = (x + .5).astype(np.float64)    # no zero
z = (x + 15.5).astype(np.float64)  # all positive
k = np.arange(-0.90, 0.90, 0.35).reshape(1, 3, 2).astype(np.float64) # between -1 and 1
self._compareBoth(x, np.abs, tf.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, tf.neg)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, tf.inv)
self._compareBoth(x, np.square, tf.square)
self._compareBoth(z, np.sqrt, tf.sqrt)
self._compareBoth(z, self._rsqrt, tf.rsqrt)
self._compareBoth(x, np.exp, tf.exp)
self._compareBoth(z, np.log, tf.log)
self._compareBoth(z, np.log1p, tf.log1p)
self._compareBoth(x, np.tanh, tf.tanh)
self._compareBoth(x, self._sigmoid, tf.sigmoid)
self._compareBoth(y, np.sign, tf.sign)
self._compareBoth(x, np.sin, tf.sin)
self._compareBoth(x, np.cos, tf.cos)
self._compareBoth(
y,
np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
tf.lgamma)
self._compareBoth(x, np.vectorize(math.erf), tf.erf)
self._compareBoth(x, np.vectorize(math.erfc), tf.erfc)
self._compareBoth(x, np.arctan, tf.atan)
self._compareBoth(k, np.arcsin, tf.asin)
self._compareBoth(k, np.arccos, tf.acos)
self._compareBoth(k, np.tan, tf.tan)

self._compareBothSparse(x, np.abs, tf.abs)
self._compareBothSparse(x, np.negative, tf.neg)
self._compareBothSparse(x, np.square, tf.square)
self._compareBothSparse(z, np.sqrt, tf.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, tf.tanh)
self._compareBothSparse(y, np.sign, tf.sign)
self._compareBothSparse(x, np.vectorize(math.erf), tf.erf) ```
Example 24
```def testHalfBasic(self):
x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float16)
y = (x + .5).astype(np.float16)    # no zero
z = (x + 15.5).astype(np.float16)  # all positive
self._compareBoth(x, np.abs, tf.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, tf.neg)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, tf.inv)
self._compareBoth(x, np.square, tf.square)
self._compareBoth(z, np.sqrt, tf.sqrt)
self._compareBoth(z, self._rsqrt, tf.rsqrt)
self._compareBoth(x, np.exp, tf.exp)
self._compareBoth(z, np.log, tf.log)
self._compareBoth(z, np.log1p, tf.log1p)
self._compareBoth(x, np.tanh, tf.tanh)
self._compareBoth(x, self._sigmoid, tf.sigmoid)
self._compareBoth(y, np.sign, tf.sign)
self._compareBoth(x, np.sin, tf.sin)
self._compareBoth(x, np.cos, tf.cos)
self._compareBoth(
y,
np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
tf.lgamma)
self._compareBoth(x, np.vectorize(math.erf), tf.erf)
self._compareBoth(x, np.vectorize(math.erfc), tf.erfc)

self._compareBothSparse(x, np.abs, tf.abs)
self._compareBothSparse(x, np.negative, tf.neg)
self._compareBothSparse(x, np.square, tf.square)
self._compareBothSparse(z, np.sqrt, tf.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, tf.tanh)
self._compareBothSparse(y, np.sign, tf.sign)
self._compareBothSparse(x, np.vectorize(math.erf), tf.erf, tol=1e-3) ```
Example 25
```def __call__(self, state, scope, pos, paramTypes, a):
try:
return math.erfc(a)
except:
raise PFARuntimeException("domain error", self.errcodeBase + 0, self.name, pos) ```
Example 26
```def aggregateSSRs(skillset, rating, res, iter, topssrs):
'''
Calculate Skillset Rating for a selected Skillset given a list of Top SSR Values
'''
sum = 0
while True:
sum = 0
rating += res
for i in range(len(topssrs[skillset])):
sum += max(0, 2 / math.erfc(0.1 * (topssrs[skillset][i][0] - rating)) - 2)
if 2 ** (rating * 0.1) >= sum:
break
if iter == 11:
return rating
return aggregateSSRs(skillset, rating - res, res / 2, iter + 1, topssrs) ```
Example 27
```def erfc(x=('FloatPin', 0.0)):
'''Return the complementary error function at `x`.'''
return math.erfc(x) ```
Example 28
```def erfc(x):
if isinstance(x, LineValue): lx = x.get_value()
else: lx = x
if lx == NAN: return LineValue(NAN)
return LineValue(math.erfc(lx)) ```
Example 29
```def erfc(x):
return math.erfc(x) ```
Example 30
```def d_normal_std_cdf(x):
return 1 - 0.5 * erfc(x / math.sqrt(2)) ```
Example 31
```def test_erfc(self):
table = [
(0.0,  1.0000000),
(0.05, 0.9436280),
(0.1,  0.8875371),
(0.15, 0.8320040),
(0.2,  0.7772974),
(0.25, 0.7236736),
(0.3,  0.6713732),
(0.35, 0.6206179),
(0.4,  0.5716076),
(0.45, 0.5245183),
(0.5,  0.4795001),
(0.55, 0.4366766),
(0.6,  0.3961439),
(0.65, 0.3579707),
(0.7,  0.3221988),
(0.75, 0.2888444),
(0.8,  0.2578990),
(0.85, 0.2293319),
(0.9,  0.2030918),
(0.95, 0.1791092),
(1.0,  0.1572992),
(1.1,  0.1197949),
(1.2,  0.0896860),
(1.3,  0.0659921),
(1.4,  0.0477149),
(1.5,  0.0338949),
(1.6,  0.0236516),
(1.7,  0.0162095),
(1.8,  0.0109095),
(1.9,  0.0072096),
(2.0,  0.0046777),
(2.1,  0.0029795),
(2.2,  0.0018628),
(2.3,  0.0011432),
(2.4,  0.0006885),
(2.5,  0.0004070),
(2.6,  0.0002360),
(2.7,  0.0001343),
(2.8,  0.0000750),
(2.9,  0.0000411),
(3.0,  0.0000221),
(3.1,  0.0000116),
(3.2,  0.0000060),
(3.3,  0.0000031),
(3.4,  0.0000015),
(3.5,  0.0000007),
(4.0,  0.0000000),
]

for x, y in table:
self.assertAlmostEqual(y, math.erfc(x), places=7)
self.assertAlmostEqual(2.0 - y, math.erfc(-x), places=7) ```
Example 32
 Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes
```def prepare_connection(self, conn):
# https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
# math fns
conn.create_function("acos", 1, math.acos)
conn.create_function("acosh", 1, math.acosh)
conn.create_function("asin", 1, math.asin)
conn.create_function("asinh", 1, math.asinh)
conn.create_function("atan", 1, math.atan)
conn.create_function("atanh", 1, math.atanh)
conn.create_function("ceil", 1, math.ceil)
conn.create_function("cos", 1, math.cos)
conn.create_function("cosh", 1, math.cosh)
conn.create_function("degrees", 1, math.degrees)
conn.create_function("erf", 1, math.erf)
conn.create_function("erfc", 1, math.erfc)
conn.create_function("exp", 1, math.exp)
conn.create_function("expm1", 1, math.expm1)
conn.create_function("fabs", 1, math.fabs)
conn.create_function("factorial", 1, math.factorial)
conn.create_function("floor", 1, math.floor)
conn.create_function("frexp", 1, math.frexp)
conn.create_function("gamma", 1, math.gamma)
conn.create_function("isfinite", 1, math.isfinite)
conn.create_function("isinf", 1, math.isinf)
conn.create_function("isnan", 1, math.isnan)
conn.create_function("lgamma", 1, math.lgamma)
conn.create_function("log", 1, math.log)
conn.create_function("log10", 1, math.log10)
conn.create_function("log1p", 1, math.log1p)
conn.create_function("log2", 1, math.log2)
conn.create_function("modf", 1, math.modf)
conn.create_function("sin", 1, math.sin)
conn.create_function("sinh", 1, math.sinh)
conn.create_function("sqrt", 1, math.sqrt)
conn.create_function("tan", 1, math.tan)
conn.create_function("tanh", 1, math.tanh)
conn.create_function("trunc", 1, math.trunc)
conn.create_function("atan2", 2, math.atan2)
conn.create_function("copysign", 2, math.copysign)
conn.create_function("fmod", 2, math.fmod)
conn.create_function("gcd", 2, math.gcd)
conn.create_function("hypot", 2, math.hypot)
conn.create_function("isclose", 2, math.isclose)
conn.create_function("ldexp", 2, math.ldexp)
conn.create_function("pow", 2, math.pow) ```
Example 33
 Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes
```def prepare_connection(self, conn):
# https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
# math fns
conn.create_function("acos", 1, math.acos)
conn.create_function("acosh", 1, math.acosh)
conn.create_function("asin", 1, math.asin)
conn.create_function("asinh", 1, math.asinh)
conn.create_function("atan", 1, math.atan)
conn.create_function("atanh", 1, math.atanh)
conn.create_function("ceil", 1, math.ceil)
conn.create_function("cos", 1, math.cos)
conn.create_function("cosh", 1, math.cosh)
conn.create_function("degrees", 1, math.degrees)
conn.create_function("erf", 1, math.erf)
conn.create_function("erfc", 1, math.erfc)
conn.create_function("exp", 1, math.exp)
conn.create_function("expm1", 1, math.expm1)
conn.create_function("fabs", 1, math.fabs)
conn.create_function("factorial", 1, math.factorial)
conn.create_function("floor", 1, math.floor)
conn.create_function("frexp", 1, math.frexp)
conn.create_function("gamma", 1, math.gamma)
conn.create_function("isfinite", 1, math.isfinite)
conn.create_function("isinf", 1, math.isinf)
conn.create_function("isnan", 1, math.isnan)
conn.create_function("lgamma", 1, math.lgamma)
conn.create_function("log", 1, math.log)
conn.create_function("log10", 1, math.log10)
conn.create_function("log1p", 1, math.log1p)
conn.create_function("log2", 1, math.log2)
conn.create_function("modf", 1, math.modf)
conn.create_function("sin", 1, math.sin)
conn.create_function("sinh", 1, math.sinh)
conn.create_function("sqrt", 1, math.sqrt)
conn.create_function("tan", 1, math.tan)
conn.create_function("tanh", 1, math.tanh)
conn.create_function("trunc", 1, math.trunc)
conn.create_function("atan2", 2, math.atan2)
conn.create_function("copysign", 2, math.copysign)
conn.create_function("fmod", 2, math.fmod)
conn.create_function("gcd", 2, math.gcd)
conn.create_function("hypot", 2, math.hypot)
conn.create_function("isclose", 2, math.isclose)
conn.create_function("ldexp", 2, math.ldexp)
conn.create_function("pow", 2, math.pow) ```
Example 34
 Project: sp800_22_tests   Author: dj-on-github   File: sp800_22_random_excursion_variant_test.py    GNU General Public License v2.0 4 votes
```def random_excursion_variant_test(bits):
n = len(bits)

x = list()             # Convert to +1,-1
for bit in bits:
x.append((bit * 2)-1)

# Build the partial sums
pos = 0
s = list()
for e in x:
pos = pos+e
s.append(pos)
sprime = [0]+s+[0] # Add 0 on each end

# Count the number of cycles J
J = 0
for value in sprime[1:]:
if value == 0:
J += 1
print("J=",J)
# Build the counts of offsets
count = [0 for x in range(-9,10)]
for value in sprime:
if (abs(value) < 10):
count[value] += 1

# Compute P values
success = True
plist = list()
for x in range(-9,10):
if x != 0:
top = abs(count[x]-J)
bottom = math.sqrt(2.0 * J *((4.0*abs(x))-2.0))
p = math.erfc(top/bottom)
plist.append(p)
if p < 0.01:
err = " Not Random"
success = False
else:
err = ""
print("x = %1.0f\t count=%d\tp = %f %s"  % (x,count[x],p,err))

if (J < 500):
print("J too small (J=%d < 500) for result to be reliable" % J)
elif success:
print("PASS")
else:
print("FAIL: Data not random")
return (success,None,plist) ```
Example 35
```def test_truncated_normal(assert_equal, assert_all_close, n, y,
mean_atol=5e-4, median_atol=8e-4, variance_rtol=1e-3):
"""Tests truncated normal distribution's statistics."""
def _normal_cdf(x):
return .5 * math.erfc(-x / math.sqrt(2))

def normal_pdf(x):
return math.exp(-(x**2) / 2.) / math.sqrt(2 * math.pi)

def probit(x):
return special_math.ndtri(x)

a = -2.
b = 2.
mu = 0.
sigma = 1.

alpha = (a - mu) / sigma
beta = (b - mu) / sigma
z = _normal_cdf(beta) - _normal_cdf(alpha)

assert_equal((y >= a).sum(), n)
assert_equal((y <= b).sum(), n)

# Burkardt, John. "The Truncated Normal Distribution".
# Department of Scientific Computing website. Florida State University.
expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma
y = y.astype(float)
actual_mean = np.mean(y)
assert_all_close(actual_mean, expected_mean, atol=mean_atol)

expected_median = mu + probit(
(_normal_cdf(alpha) + _normal_cdf(beta)) / 2.) * sigma
actual_median = np.median(y)
assert_all_close(actual_median, expected_median, atol=median_atol)

expected_variance = sigma**2 * (1 + (
(alpha * normal_pdf(alpha) - beta * normal_pdf(beta)) / z) - (
(normal_pdf(alpha) - normal_pdf(beta)) / z)**2)
actual_variance = np.var(y)
assert_all_close(
actual_variance,
expected_variance,
rtol=variance_rtol) ```