Python standard module --random module

Python provides the random module, which can be used to generate pseudo-random numbers or randomly draw based on given sequence data

Common functions

function describe scope
seed() Specify a seed to initialize the pseudorandom number generator -
random() Generate a random floating point number [0.0,1.0)
uniform(x,y) Generates a random floating point number in the specified range [x,y]
randint(x,y) Generates a random floating point number in the specified range [x,y]
randrange (x, y, step) Within the specified range, increment the data according to the step, and extract a data from it [x,y)
choice(seq) extract a data from the sequence seq -
shuffle(seq) Randomly arrange the sequence seq (change the original sequence) -

Examples of commonly used functions

insert image description here

Small application example - using Monte Carlo method to calculate pi

Source of ideas: The course of Mr. Songtian, MOOC of China University

Introduction

Regarding the Monte Carlo method, the author quoted the definition of it from Encyclopedia: a method of using random numbers (or more common pseudo-random numbers) to solve many computing problems. For more information, please click: Baidu Encyclopedia - Monte Carlo Method

Process introduction

insert image description here

Suppose we now know the formula for calculating the area of ​​a circle, but do not know the value of pi. At this time, there is a square with a side length of 1, and there is a ¼ circle inscribed in it. We throw points into the square, and the location of each point's drop point Randomly, if enough points are thrown, the ratio of the number of points x that falls in the ¼ circle to the total number of points y thrown is equal to the ratio of the area of ​​the ¼ circle to the square

import random
import math

total_num=1000*1000		# 总点数
circle_num=0	# 落在圆中的点数
for i in range(total_num):
    x,y=random.random(),random.random()		# 生成坐标用来表示点的位置
    dist=math.sqrt(x**2+y**2)		# 计算点与原点O的距离以确定点是否在圆内
    if dist<=1.0:
        circle_num+=1		# 计算出圆内点数
pii=4*(circle_num/total_num)	# 根据已知中的等式关系得出计算式
print(f'您得出的圆周率为:{pii}')
print('您的圆周率准确度大约为:{:.6f}'.format(pii/math.pi))	# 我们取math模块中的pi作为标准来查看得出的结果的准确度

operation result
insert image description here

In fact, the more total points, the higher the accuracy, and readers can try it by themselves

Guess you like

Origin blog.csdn.net/m0_54510474/article/details/121324023