今天写毕业设计的时候遇到了一个级数展开式,里面包含着一个求一个数组的阶乘运算,这里特来记录一下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
# -*- coding:utf-8 -*-
"""
author: 15025
time: 2021/7/18 17:58
software: PyCharm
Description:
calculate factorial of a given number
"""
class PythonStudy:
@staticmethod
def factorial(n):
num = 1
for i in range ( 1 , n + 1 ):
num * = i
return num
if __name__ = = "__main__" :
main = PythonStudy()
result = main.factorial( 4 )
print ( "The final result is: " )
print (result)
"""
The final result is:
24
"""
|
可以看到,我们正确地获得了4的阶乘值24。那么如果我们需要求一个数组中各个元素的阶乘值呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# -*- coding:utf-8 -*-
"""
author: 15025
time: 2021/7/18 17:58
software: PyCharm
Description:
calculate factorial of a given array
"""
import numpy as np
class NumpyStudy:
@staticmethod
def factorial(arr):
length = len (arr)
num_arr = np.ones(length)
for index, value in enumerate (arr):
for i in range ( 1 , value + 1 ):
num_arr[index] * = i
return num_arr
if __name__ = = "__main__" :
main = NumpyStudy()
array = np.arange( 11 )
result = main.factorial(array)
print ( "The final result is: " )
print (result)
"""
The final result is:
[1.0000e+00 1.0000e+00 2.0000e+00 6.0000e+00 2.4000e+01 1.2000e+02
7.2000e+02 5.0400e+03 4.0320e+04 3.6288e+05 3.6288e+06]
"""
|
这里我们可以看到我们成功获得了数组[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]中对应的的各个元素值的阶乘值。
到此这篇关于python计算给定数字或者数组的阶乘的文章就介绍到这了,更多相关python数组阶乘内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/u011699626/article/details/119333429