首页 > 编程知识 正文

python中阶乘的表达方法是什么,python里阶乘

时间:2023-05-04 05:26:59 阅读:238742 作者:586

python中阶乘怎么表示

I am currently working on an article about calculating sines and cosines using Taylor Polynomials. These make heavy use of factorials so I started thinking about ways to streamline the process.

我目前正在撰写一篇有关使用灵巧的银耳汤多项式计算正弦和余弦的文章。 这些大量使用阶乘,因此我开始考虑简化流程的方法。

This article describes a simple project using memoization with a lookup table to pre-calculate factorials and store them for future use.

本文介绍了一个简单的项目,该项目使用带有查找表的备注来预先计算析因并将其存储以备将来使用。

Many algorithms and other processes make heavy and repeated use of values which need to be calculated, often in a way which is expensive in terms of memory and/or time. It therefore makes sense to develop some sort of mechanism whereby the values which are or are likely to be needed frequently are calculated only once.

许多算法和其他过程经常以在存储器和/或时间方面昂贵的方式大量重复使用需要计算的值。 因此,开发某种机制是有意义的,通过这种机制,经常或可能经常需要的值仅计算一次。

The use of factorials in calculating trigonometric functions mentioned above is one example. In a future article I’ll extend the principle to calculating and storing sines and cosines themselves, but of course there are many other common examples.

在上述三角函数的计算中使用阶乘是一个示例。 在以后的文章中,我将把原理扩展到计算和存储正弦和余弦本身,但是当然还有许多其他常见示例。

When considering factorials the broad outline of memoization using a lookup table is simple and obvious: just use a list of integers the highest index of which is the highest number we want the factorial of. The factorial of a given number is therefore set and retrieved using the number as the array’s index.

在考虑阶乘时,使用查找表进行记忆的大致轮廓很简单明了:只需使用整数列表,其最高索引就是我们想要阶乘的最高数字。 因此,使用该数字作为数组的索引来设置和检索给定数字的阶乘。

我们要编写什么代码? (What Are We Going to Code?)

This project consists of a small class implementing memoization of factorials up to a given maximum. Factorials are calculated in __init__ and stored in a list. There is also a method to get an individual factorial.

该项目由一个小类组成,该类实现对阶乘的记忆直至给定的最大值。 阶乘在__init__中计算并存储在列表中。 还有一种获取单个阶乘的方法。

The project consists of the following files:

该项目包含以下文件:

factorialsmemoization.py

析因记忆化 main.py

main.py

You can clone/download these from the Github repository.

您可以从Github仓库克隆/下载这些。

Let’s look at factorialsmemoization.py first.

首先让我们看一下factorialsmemoization.py

import mathclass FactorialMemoization(object): """ Memoizes factorials of integers up to the n argument of init. Provides get method to retrieve memoized factorials. """ def __init__(self, n): """ Stores factorials of numbers from 0 to n in list. """ self.factorials = [] self.memoized_to = n prev = 1 # 0! = 1 (yeah, really) self.factorials.append(1) # Multiplying by previous factorial is much more efficient # than calculating each factorial individually for i in range(1, n + 1): self.factorials.append(i * prev) prev = self.factorials[i] def get(self, n): """ Return factorial from list or raise ValueError if outside memoized range. """ if(n < 0 or n > self.memoized_to): raise ValueError("Factorial requested is outside of memoized range") else: return self.factorials[n]

The __init__ method takes as an argument the maximum number to calculate factorials of. We then create an empty list, store the maximum in self.memoized_to, and initialize a variable called prev to 1; its purpose will become clear in a moment.

__init__方法将要计算其阶乘的最大数量作为参数。 然后,我们创建一个空列表,将最大值存储在self.memoized_to ,并将名为prev的变量初始化为1; 稍后它的目的将变得很清楚。

We then append the factorial of 0 which is 1 to the list before entering a loop to calculate the rest. Note that this loop starts at 1 as we have already set 0. Within the loop we set the next factorial to the previous multiplied by the current number, hence setting prev to 1 to start with. We then set prev to the current factorial.

然后,我们在进入循环以计算余数之前将0的阶乘0(即1)添加到列表中。 请注意,此循环从1开始,因为我们已经设置了0。在循环中,我们将下一个阶乘乘以当前数,再乘以当前数字,因此将prev设置为1。 然后,将prev设置为当前的阶乘。

Finally we have the get method which checks whether the requested factorial is out of range, raising an exception if so. If n is valid it returns the relevant value from the list.

最后,我们有了get方法,该方法检查所请求的阶乘是否超出范围,如果是,则引发异常。 如果n有效,则从列表中返回相关值。

That’s factorialmemoization.py finished so we can move on to main.py.

那已经完成了factorialmemoization.py,所以我们可以继续进行main.py了

import factorialmemoizationdef main(): """ Demonstrate FactorialMemoization class. """ print("-----------------------------") print("| codedrome.com |") print("| Memoization of Factorials |") print("-----------------------------n") fm = factorialmemoization.FactorialMemoization(8) try: # test xxdhk memoized range to demonstrate exception for n in range(0, 10): print("{:d}: ".format(n), end="") print("{:d}".format(fm.get(n))) # If we call get outside memoized range it raises ValueError except ValueError as e: print(e)main()

After importing the module created above we enter the main function which first creates an instance of the FactorialMemoization class with n set to 8. We then enter a loop to print out factorials of 0 to 10 — I have deliberately overrun the range to demonstrate the exception handling.

导入上面创建的模块后,我们进入main函数,该函数首先创建n设置为8的FactorialMemoization类的实例。然后进入循环以打印出0到10的阶乘-我故意超范围以演示异常处理。

Run the program with the following in Terminal…

在终端中运行以下程序……

python3.8 main.py

python3.8 main.py

…which will give you the following output.

…这将为您提供以下输出。

As you can see we get the correct factorials up to 8 but then hit an exception with 9 which is xxdhk the calculated range.

如您所见,我们得到了最多8个正确的阶乘,但是又遇到了超出计算范围的9异常。

翻译自: https://medium.com/python-in-plain-english/memoization-of-factorials-in-python-fe27710ce85b

python中阶乘怎么表示

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。