search
HomeBackend DevelopmentPython TutorialDetailed explanation of mathematics and random numbers in the Python standard library (math package, random package)

We have seen the most basic mathematical operation functions of Python in Python operations. In addition, math package has been supplemented with more functions. Of course, if you want more advanced mathematical functions, you can consider choosing the numpy and scipy projects outside the standard library. They not only Supports array and matrix operations, and a wealth of mathematical and physical equations are available.

In addition, the random package can be used to generate random numbers. Random numbers can not only be used for mathematical purposes, but are often embedded into algorithms to improve algorithm efficiency and improve program security.

math package

math package mainly handles math-related operations. The math package defines two constants:

math.e   # 自然常数e
math.pi  # 圆周率pi

In addition, the math package also has various calculation functions(For the functions of the following functions, please refer to the mathematics manual)

math.ceil(x)       # 对x向上取整,比如x=1.2,返回2
math.floor(x)      # 对x向下取整,比如x=1.2,返回1
math.pow(x,y)      # 指数运算,得到x的y次方
math.log(x)        # 对数,默认基底为e。可以使用base参数,来改变对数的基地。比如math.log(100,base=10)
math.sqrt(x)       # 平方根
 
三角函数: math.sin(x), math.cos(x), math.tan(x), math.asin(x), math.acos(x), math.atan(x)

These functions all receive a radian x in (radian) units as a parameter.

角度和弧度互换: math.degrees(x), math.radians(x)
双曲函数: math.sinh(x), math.cosh(x), math.tanh(x), math.asinh(x), math.acosh(x), math.atanh(x)
特殊函数: math.erf(x), math.gamma(x)

random package

# #If you already understand the principle of pseudo-random number, then you can use the following:

random.seed(x)

To change the seed of the random number generator. If you don’t understand the principle, you don’t have to set the seed specifically, Python will choose the seed for you.

##1) Random selection and sorting

random.choice(seq)   # 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
random.sample(seq,k) # 从序列中随机挑选k个元素
random.shuffle(seq)  # 将序列的所有元素随机排序

2) Randomly generate real numbers

The real numbers generated below conform to the uniform distribution, which means that every number within a certain range appears Equal probabilities:
##

random.random()          # 随机生成下一个实数,它在[0,1)范围内。
random.uniform(a,b)      # 随机生成下一个实数,它在[a,b]范围内。

The real numbers generated below conform to other distributions (you can refer to some Statistics books to understand these distributions):

random.gauss(mu,sigma)    # 随机生成符合高斯分布的随机数,mu,sigma为高斯分布的两个参数。 
random.expovariate(lambd) # 随机生成符合指数分布的随机数,lambd为指数分布的参数。

In addition, there are logarithmic distribution, normal distribution, Pareto distribution, and Weibull distribution. Please refer to the following link:
##

docs.python.org/library/random.html

假设我们有一群人参加舞蹈比赛,为了公平起见,我们要随机排列他们的出场顺序。我们下面利用random包实现:

import random
all_people = ['Tom', 'Vivian', 'Paul', 'Liya', 'Manu', 'Daniel', 'Shawn']
random.shuffle(all_people)for i,name in enumerate(all_people):    print(i,':'+name)

【相关推荐】

1. 分享Python中random模块生成随机数的实例教程

2. Python random() 函数的实例教程

3. 分享一篇Python中random(随机生成数)的实例教程

4. 分享Python random生成某区间内不重复的N个随机数的方法实例

5. Python random模块(获取随机数)常用方法和使用例子

6. Python random模块常用方法

7. Python 模块学习:random 随机数生成

The above is the detailed content of Detailed explanation of mathematics and random numbers in the Python standard library (math package, random package). 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
Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

What is the difference between arrays and lists in Python?What is the difference between arrays and lists in Python?May 05, 2025 am 12:06 AM

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

What module is commonly used to create arrays in Python?What module is commonly used to create arrays in Python?May 05, 2025 am 12:02 AM

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft