search
HomeBackend DevelopmentPython TutorialSummary of commonly used mathematical functions in Python's math module

This article mainly introduces the common mathematical functions in the math module of Python, and also analyzes the priority# of the operators. ##Made a list, friends in need can refer to it

In mathematics, in addition to the four operations of addition, subtraction, multiplication and division - this is primary school mathematics - there are other more operations, such as multiplication Square, square root, logarithm operations, etc. To implement these operations, you need to use a module in Python: Math

module (

module) is a very important thing in Python. You can think of it as an extension tool for Python. In other words, Python provides some usable things by default, but these provided by default are far from meeting the needs of programming practice, so someone has specially made some other tools. These tools are called "modules"

Any Pythoner can write modules and put these modules online for others to use.

After installing Python, some modules are installed by default. This is called the "standard library". The modules in the "standard library" do not need to be installed and can be used directly.

If the module is not included in the standard library, it needs to be installed before it can be used. As for the installation method of the module, I especially recommend using pip to install it. I’m just mentioning it here, it will be discussed specifically later, impatient readers can google it themselves.


Use the math module
The math module is in the standard library, so you don’t need to install it and you can use it directly. The usage method is:


>>> import math

Use import to reference the math module, and then you can use the tools provided by this module. For example, to get the pi:


>>> math.pi
3.141592653589793

What can this module do? It can be seen with the following method:


>>> dir(math)
['doc', 'name', 'package', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

dir(module) is a very useful command through which you can view the tools contained in any module. As can be seen from the above list, in the math module, you can calculate positive sin(a), cos(a), sqrt(a)...

We call these functions , that is, the module math provides various calculation functions, such as calculating exponentiation, you can use the pow function. But how to use it?

Python is a very thoughtful girl. She has already provided a command that allows us to see how to use each function.


>>> help(math.pow)

Enter the above command in interactive

mode, then press Enter and see the following message:


Help on built-in function pow in module math:

 
pow(...)
 pow(x, y)

 Return x**y (x to the power of y).

Here shows the usage and related instructions of the pow function in the math module.

The first line means that here is the help information of the built-in function pow of the math module (the so-called built-in is called a built-in function, which means that this function is included in Python by default)

The third line represents the parameters of this
function. There are two. It is also the calling method of the function. The fourth line is a description of the function. It returns the result of x**y and will be explained later. The meaning of x**y. Finally, press the q key to return to the Python interactive modeAn additional information seen from the above is that the pow function and x**y are equivalent, and both calculate the yth power of x.


>>> 4**2
16
>>> math.pow(4,2)
16.0
>>> 4*2
8

Please note that there is a big difference between 4**2 and 4*2.

Using a similar method, you can view the usage of any function in the math module.

Regarding the issue of "function", I will not elaborate on it in depth here. I will just understand it based on what I have learned in mathematics. There will be a chapter dedicated to functions later.

The following are several commonly used examples of functions in the math module. Readers can compare them with their own debugging.

>>> math.sqrt(9)
3.0
>>> math.floor(3.14)
3.0
>>> math.floor(3.92)
3.0
>>> math.fabs(-2) # 等价于 abs(-2)
2.0
>>> abs(-2)
2
>>> math.fmod(5,3) # 等价于 5%3
2.0
>>> 5%3
2


Several common functions

There are several commonly used functions. Let’s list them. It doesn’t matter if you can’t remember them. Just know that they are there. Just google them when you use them.
Find the absolute value

>>> abs(10)
10
>>> abs(-10)
10
>>> abs(-1.2)
1.2
Rounding

>>> round(1.234)
1.0
>>> round(1.234,2)
1.23

>>> # 如果不清楚这个函数的用法,可以使用下面方法看帮助信息
>>> help(round)

Help on built-in function round in module builtin:

round(...)
 round(number[, ndigits]) -> floating point number

 Round a number to a given precision in decimal digits (default 0 digits).
 This always returns a floating point number. Precision may be negative.


Operation Priority

Since primary school mathematics, we have studied the issue of priority of operations. For example, among the four arithmetic operations, "multiplication and division first, then addition and subtraction" mean that multiplication and division have higher priority than addition and subtraction.
For the same level, calculation is performed in the order of "left to right".

The following

table

lists the priority order of various operations in Python. However, in general, there is no need to memorize it, and it can be understood according to mathematics. Since humans have invented mathematics, the operations performed in computers do not need to rewrite a new set of specifications. They only need to comply with mathematics. Just hit it.

##|Bitwise OR^Bitwise XOR&Bitwise AND>Shift##+, -*,/,%+x,-x~x**x.attributex[index]x [index:index]f(arguments...)(experession,...)[expression,...]{key:datum,...}'expression,...'String
Operator
Description
lambda Lambda Expression
or Boolean "or"
and Boolean "AND"
not x Boolean "NOT"
in, not in Member Test
is, is not Identity Test
, >=, !=, == Compare
Addition and subtraction
Multiplication, division and remainder
Positive and negative signs
Bitwise flip
Index
Attribute reference
subscript
Addressing segment
Function call
Binding or tuple display
List display
Dictionary display
Conversion
#The above table lists all the operators used in Python, yes Listed in order from lowest to highest. Although there are many that I still don’t know how to use, I’ll list them first so that I can come back and check them out when I need them later.


Finally, what I want to mention is the ultimate killer in operations: parentheses. As long as there are parentheses, the contents inside the parentheses are calculated first. This is a consensus in mathematics and requires no explanation.

The above is the detailed content of Summary of commonly used mathematical functions in Python's math module. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.