Python math.factorial() Examples

The following are 30 code examples of math.factorial(). 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 also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 7 votes vote down vote up
def test_math_subclass(self):
        """verify subtypes of float/long work w/ math functions"""
        import math
        class myfloat(float): pass
        class mylong(long): pass

        mf = myfloat(1)
        ml = mylong(1)

        for x in math.log, math.log10, math.log1p, math.asinh, math.acosh, math.atanh, math.factorial, math.trunc, math.isinf:
            try:
                resf = x(mf)
            except ValueError:
                resf = None
            try:
                resl = x(ml)
            except ValueError:
                resl = None
            self.assertEqual(resf, resl) 
Example #2
Source Project: quadcopter-simulation   Author: hbd730   File: test_trajGen3D.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_poly_cc_k(self):
        cc = trajGen3D.get_poly_cc(4, 1, 1)
        expected = [0, 1, 2, 3]
        np.testing.assert_array_equal(cc, expected)

        cc = trajGen3D.get_poly_cc(4, 2, 2)
        expected = [0, 0, 2, 12]
        np.testing.assert_array_equal(cc, expected)

        cc = trajGen3D.get_poly_cc(8, 7, 1)
        expected = [0, 0, 0, 0, 0, 0, 0, math.factorial(7)]
        np.testing.assert_array_equal(cc, expected)

        cc = trajGen3D.get_poly_cc(8, 8, 1)
        expected = np.zeros(8)
        np.testing.assert_array_equal(cc, expected) 
Example #3
Source Project: pyscf   Author: pyscf   File: numpy_helper.py    License: Apache License 2.0 6 votes vote down vote up
def expm(a):
    '''Equivalent to scipy.linalg.expm'''
    bs = [a.copy()]
    n = 0
    for n in range(1, 14):
        bs.append(ddot(bs[-1], a))
        radius = (2**(n*(n+2))*math.factorial(n+2)*1e-16) **((n+1.)/(n+2))
        #print(n, radius, bs[-1].max(), -bs[-1].min())
        if bs[-1].max() < radius and -bs[-1].min() < radius:
            break

    y = numpy.eye(a.shape[0])
    fac = 1
    for i, b in enumerate(bs):
        fac *= i + 1
        b *= (.5**(n*(i+1)) / fac)
        y += b
    buf, bs = bs[0], None
    for i in range(n):
        ddot(y, y, 1, buf, 0)
        y, buf = buf, y
    return y 
Example #4
Source Project: NURBS-Python   Author: orbingol   File: linalg.py    License: MIT License 6 votes vote down vote up
def binomial_coefficient(k, i):
    """ Computes the binomial coefficient (denoted by *k choose i*).

    Please see the following website for details: http://mathworld.wolfram.com/BinomialCoefficient.html

    :param k: size of the set of distinct elements
    :type k: int
    :param i: size of the subsets
    :type i: int
    :return: combination of *k* and *i*
    :rtype: float
    """
    # Special case
    if i > k:
        return float(0)
    # Compute binomial coefficient
    k_fact = math.factorial(k)
    i_fact = math.factorial(i)
    k_i_fact = math.factorial(k - i)
    return float(k_fact / (k_i_fact * i_fact)) 
Example #5
Source Project: nn_dataflow   Author: stanford-mast   File: test_util.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_perm(self):
        ''' Permutations. '''
        fs_ord = set()
        fs_unord = set()
        for fs in util.factorize(512, 3):
            fs_ord.add(fs)
            fs_unord.add(frozenset(fs))

        cnt = 0
        for fs in fs_unord:
            if len(fs) == 3:
                # Permutations.
                cnt += math.factorial(3)
            elif len(fs) == 2:
                # Permutations of a, a, b.
                cnt += 3
            else:
                # Pattern a, a, a.
                cnt += 1
        self.assertEqual(len(fs_ord), cnt) 
Example #6
Source Project: pyth   Author: isaacg1   File: macros.py    License: MIT License 6 votes vote down vote up
def combinations(a, b):
    if isinstance(a, int) and isinstance(b, int):
        # compute n C r
        n, r = a, min(b, a - b)
        if r == 0:
            return 1
        if r < 0:
            r = max(b, a - b)
            if r < 0:
                return 0

        num = functools.reduce(operator.mul, range(n, n - r, -1), 1)
        den = math.factorial(r)

        return num // den

    if is_col(a) and isinstance(b, int):
        return itertools_norm(itertools.combinations, a, b)

    return unknown_types(combinations, ".c", a, b) 
Example #7
Source Project: ocelot   Author: ocelot-collab   File: wave.py    License: GNU General Public License v3.0 6 votes vote down vote up
def calc_phase_delay(coeff, w, w0):
    """
    expression for the phase -- coeff[0] + coeff[1]*(w - w0)/1! + coeff[2]*(w - w0)**2/2! + coeff[3]*(w - w0)**3/3!
    coeff is a list with
    coeff[0] =: measured in [rad]      --- phase
    coeff[1] =: measured in [fm s ^ 1] --- group delay
    coeff[2] =: measured in [fm s ^ 2] --- group delay dispersion (GDD)
    coeff[3] =: measured in [fm s ^ 3] --- third-order dispersion (TOD)
    ...
    """
    delta_w = w - w0
    _logger.debug('calculating phase delay')
    _logger.debug(ind_str + 'coeffs for compression = {}'.format(coeff))
    coeff_norm = [ci / (1e15) ** i / factorial(i) for i, ci in enumerate(coeff)]
    coeff_norm = list(coeff_norm)[::-1]
    _logger.debug(ind_str + 'coeffs_norm = {}'.format(coeff_norm))
    delta_phi = np.polyval(coeff_norm, delta_w)
    _logger.debug(ind_str + 'delta_phi[0] = {}'.format(delta_phi[0]))
    _logger.debug(ind_str + 'delta_phi[-1] = {}'.format(delta_phi[-1]))
    _logger.debug(ind_str + 'done')

    return delta_phi 
Example #8
Source Project: Deep-Learning-with-TensorFlow-Second-Edition   Author: PacktPublishing   File: core.py    License: MIT License 6 votes vote down vote up
def init_main_block(self):
        self.x_pow_cache = {}
        self.matmul_cache = {}
        self.outputs = self.b
        with tf.name_scope('linear_part') as scope:
            contribution = utils.matmul_wrapper(self.train_x, self.w[0], self.input_type)
        self.outputs += contribution
        for i in range(2, self.order + 1):
            with tf.name_scope('order_{}'.format(i)) as scope:
                raw_dot = utils.matmul_wrapper(self.train_x, self.w[i - 1], self.input_type)
                dot = tf.pow(raw_dot, i)
                if self.use_diag:
                    contribution = tf.reshape(tf.reduce_sum(dot, [1]), [-1, 1])
                    contribution /= 2.0**(i-1)
                else:
                    initialization_shape = tf.shape(dot)
                    for in_pows, out_pows, coef in utils.powers_and_coefs(i):
                        product_of_pows = tf.ones(initialization_shape)
                        for pow_idx in range(len(in_pows)):
                            pmm = self.pow_matmul(i, in_pows[pow_idx])
                            product_of_pows *= tf.pow(pmm, out_pows[pow_idx])
                        dot -= coef * product_of_pows
                    contribution = tf.reshape(tf.reduce_sum(dot, [1]), [-1, 1])
                    contribution /= float(math.factorial(i))
            self.outputs += contribution 
Example #9
Source Project: Jarvis   Author: sukeesh   File: calculator.py    License: MIT License 6 votes vote down vote up
def fact(self):
        try:
            self.a = self.num.get()
            self.buffer["text"] = str(self.a) + "!"
            if float(self.a) >= 0:
                self.an = str(math.factorial(float(self.a)))
                self.ans["text"] = self.an
                if len(self.an) > 17:
                    self.ans["text"] = "Out of Range"
            else:
                self.ans["text"] = "Error"
        except ValueError:
            self.ans["text"] = "Invalid Input "
        except TypeError:
            self.ans["text"] = "Invalid Input "
        except OverflowError:
            self.ans["text"] = "Out of range" 
Example #10
Source Project: QCPortal   Author: MolSSI   File: collection_utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def nCr(n: int, r: int) -> int:
    """
    Compute the binomial coefficient n! / (k! * (n-k)!)

    Parameters
    ----------
    n : int
        Number of samples
    r : int
        Denominator

    Returns
    -------
    ret : int
        Value
    """
    return math.factorial(n) / math.factorial(r) / math.factorial(n - r) 
Example #11
Source Project: Manabase   Author: Chris-Cunningham   File: manabase.py    License: GNU General Public License v2.0 6 votes vote down vote up
def comb(n, k):
	"""Simple combinations function, the number of ways to choose
	k objects from n given objects.

	>>> print(comb(7, 3))
	35
	>>> print(comb(7, 0))
	1
	"""
	if is_int(n) and is_int(k):
		if k >= 0 and k <= n:
			return int(math.factorial(n) / (math.factorial(k) * math.factorial(n-k)))
		else:
			return 0
	else:
		raise ValueError('Can\'t take factorials of non-integers; you passed %n and %k to comb().' % (n, k)) 
Example #12
Source Project: Python   Author: TheAlgorithms   File: sol2.py    License: MIT License 6 votes vote down vote up
def solution(n):
    """Returns the sum of the digits in the number 100!
    >>> solution(100)
    648
    >>> solution(50)
    216
    >>> solution(10)
    27
    >>> solution(5)
    3
    >>> solution(3)
    6
    >>> solution(2)
    2
    >>> solution(1)
    1
    """
    return sum([int(x) for x in str(factorial(n))]) 
Example #13
Source Project: Python   Author: TheAlgorithms   File: sol3.py    License: MIT License 6 votes vote down vote up
def solution(n):
    """Returns the sum of the digits in the number 100!
    >>> solution(1000)
    10539
    >>> solution(200)
    1404
    >>> solution(100)
    648
    >>> solution(50)
    216
    >>> solution(10)
    27
    >>> solution(5)
    3
    >>> solution(3)
    6
    >>> solution(2)
    2
    >>> solution(1)
    1
    >>> solution(0)
    1
    """
    return sum(map(int, str(factorial(n)))) 
Example #14
Source Project: ufora   Author: ufora   File: pure_math.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, val):
        if not math.floor(val) == val:
            raise ValueError(
                "factorial() only accepts integral values"
                )

        if val < 0:
            raise ValueError(
                "factorial() not defined for negative values"
                )

        ix = 1
        res = 1
        while ix <= val:
            res = res * ix
            ix = ix + 1

        return res 
Example #15
Source Project: matchpy   Author: HPAC   File: test_bipartite.py    License: MIT License 5 votes vote down vote up
def test_completeness(n, m):
    graph = BipartiteGraph(map(lambda x: (x, True), itertools.product(range(n), range(m))))
    count = sum(1 for _ in enum_maximum_matchings_iter(graph))
    expected_count = m > 0 and math.factorial(n) / math.factorial(n - m) or 0
    assert count == expected_count 
Example #16
Source Project: pyscf   Author: pyscf   File: cistring.py    License: Apache License 2.0 5 votes vote down vote up
def num_strings(n, m):
    if m < 0 or m > n:
        return 0
    else:
        return math.factorial(n) // (math.factorial(n-m)*math.factorial(m)) 
Example #17
Source Project: trader   Author: BigBrotherTrade   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def nCr(n, r):
    f = math.factorial
    return f(n) / f(r) / f(n-r) 
Example #18
Source Project: pyeclib   Author: openstack   File: pyeclib_conf_tool.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def nCr(n, r):
    f = math.factorial
    return f(n) / f(r) / f(n - r) 
Example #19
Source Project: Competitive_Programming   Author: amitrajitbose   File: NMNNMX.py    License: MIT License 5 votes vote down vote up
def C(n,r):
    if(n<r):
        return 0 #not possible
    else:
        return fact(n) // (fact(r) * fact(n-r)) 
Example #20
Source Project: residual-flows   Author: rtqichen   File: iresblock.py    License: MIT License 5 votes vote down vote up
def poisson_1mcdf(lamb, k, offset):
    if k <= offset:
        return 1.
    else:
        k = k - offset
    """P(n >= k)"""
    sum = 1.
    for i in range(1, k):
        sum += lamb**i / math.factorial(i)
    return 1 - np.exp(-lamb) * sum 
Example #21
Source Project: reinforcement-learning-an-introduction   Author: ShangtongZhang   File: car_rental_synchronous.py    License: MIT License 5 votes vote down vote up
def poisson(n, lam):
    global poisson_cache
    key = n * 10 + lam
    if key not in poisson_cache.keys():
        poisson_cache[key] = math.exp(-lam) * math.pow(lam, n) / math.factorial(n)
    return poisson_cache[key] 
Example #22
Source Project: interview-with-python   Author: thundergolfer   File: string-permutations.py    License: MIT License 5 votes vote down vote up
def test_recursive1(self):
        """ Permutations of list [A,B,C] correct """
        A = ['A', 'B', 'C']
        r = perm_recursive(A)
        self.assertEqual(set(tuple([tuple(l) for l in r])), set(self.perm_ABC))
        self.assertEqual(len(r), factorial(len(A))) 
Example #23
Source Project: interview-with-python   Author: thundergolfer   File: string-permutations.py    License: MIT License 5 votes vote down vote up
def test_recursive2(self):
        """ Permutations of str "ABC" correct """
        A = "ABC"
        r = perm_recursive(A)
        self.assertEqual(set(tuple([tuple(l) for l in r])), set(self.perm_ABC))
        self.assertEqual(len(r), factorial(len(A))) 
Example #24
Source Project: interview-with-python   Author: thundergolfer   File: string-permutations.py    License: MIT License 5 votes vote down vote up
def test_generator1(self):
        """ Generated permutations of list [A,B,C] correct """
        A = ['A', 'B', 'C']
        r = list(perm_generator(A))
        self.assertEqual(set(tuple([tuple(l) for l in r])), set(self.perm_ABC))
        self.assertEqual(len(r), factorial(len(A))) 
Example #25
Source Project: interview-with-python   Author: thundergolfer   File: string-permutations.py    License: MIT License 5 votes vote down vote up
def test_generator2(self):
        """ Generated Permutations of str "ABC" correct """
        A = "BAC"
        r = list(perm_generator(A))
        self.assertEqual(set(tuple([tuple(l) for l in r])), set(self.perm_ABC))
        self.assertEqual(len(r), factorial(len(A))) 
Example #26
Source Project: formulas   Author: vinci1it2000   File: math.py    License: European Union Public License 1.1 5 votes vote down vote up
def xfact(number, fact=math.factorial, limit=0):
    return np.nan if number < limit else int(fact(int(number or 0))) 
Example #27
Source Project: mars   Author: mars-project   File: var.py    License: Apache License 2.0 5 votes vote down vote up
def reduce_var_square(var_square, avg_diff, count, op, axis, sum_func):
    moment = op.moment
    dtype = op.dtype
    kw = dict(axis=axis, dtype=dtype, keepdims=bool(op.keepdims))

    reduced_var_square = var_square[..., moment - 2].sum(**kw) + \
        sum_func(count * avg_diff ** moment, **kw)
    for i in range(1, moment - 1):
        coeff = factorial(moment) / float(factorial(i) * factorial(moment - i))
        reduced_var_square += coeff * sum_func(var_square[..., moment - i - 2] * avg_diff ** moment, **kw)
    return reduced_var_square 
Example #28
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def testFactorial(self):
        def fact(n):
            result = 1
            for i in range(1, int(n)+1):
                result *= i
            return result
        values = range(10) + [50, 100, 500]
        random.shuffle(values)
        for x in values:
            for cast in (int, long, float):
                self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x)))
        self.assertRaises(ValueError, math.factorial, -1)
        self.assertRaises(ValueError, math.factorial, math.pi) 
Example #29
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def test_gamma(self):
        self.assertAlmostEqual(math.gamma(0.5), math.sqrt(math.pi), places=15)
        for i in xrange(1, 20):
            self.assertEqual(math.factorial(i-1), math.gamma(i))
        self.assertEqual(math.gamma(float('inf')), float('inf'))
        self.assertRaises(ValueError, math.gamma, float('-inf'))
        self.assertTrue(math.isnan(math.gamma(float('nan'))))
        for i in xrange(0, -1001, -1):
            self.assertRaises(ValueError, math.gamma, i) 
Example #30
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def test_lgamma(self):
        tolerance = 14
        self.assertAlmostEqual(math.lgamma(0.5), 0.5 * math.log(math.pi), places=15)
        for i in xrange(1, 20):
            if i > 14:
                tolerance = 13
            self.assertAlmostEqual(math.log(math.factorial(i-1)), math.lgamma(i), places=tolerance)
        self.assertEqual(math.lgamma(float('inf')), float('inf'))
        self.assertEqual(math.lgamma(float('-inf')), float('inf'))
        self.assertTrue(math.isnan(math.lgamma(float('nan'))))
        for i in xrange(0, -1001, -1):
            self.assertRaises(ValueError, math.lgamma, i)