本文整理汇总了Python中math.factorial方法的典型用法代码示例。如果您正苦于以下问题:Python math.factorial方法的具体用法?Python math.factorial怎么用?Python math.factorial使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math
的用法示例。
在下文中一共展示了math.factorial方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_poly_cc_k
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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)
示例2: expm
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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
示例3: binomial_coefficient
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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))
示例4: test_perm
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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)
示例5: test_math_subclass
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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)
示例6: combinations
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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)
示例7: calc_phase_delay
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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
示例8: init_main_block
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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
示例9: fact
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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"
示例10: nCr
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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)
示例11: comb
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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))
示例12: solution
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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))])
示例13: solution
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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))))
示例14: __call__
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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
示例15: test_completeness
# 需要导入模块: import math [as 别名]
# 或者: from math import factorial [as 别名]
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