网上看到一个python的面试题,可能大家也在课上或者其他地方碰到过,本人不是码代码的,但是纯出于兴趣在学习Python,花了大概半小时才搞定。代码可能有些冗长,但是欢迎赐教!
题目很难用一句话概括,见下图:
随机分布一些点在数轴上,x和y的绝对值都小于等于1,现在求圆周率。
因为不单单想求出来Pi的值,也想把图画出来:
求解这个问题的方法我也想了几分钟,基本也就是4乘以(半径内的点的数量(圆内的点)除以所有的点的数量),即为Pi的值
怎么得来的就是圆的面积除以跟圆相切的正方形的面积:
公式特别简单,一下就得出来了。
import random
import matplotlib.pyplot as plt
# define the input value for how many dots in total
n = input("Please specify how many dots you need in total: ")
n = int(n) #make sure n is a int, since the input is str
# generate array of x and y axis values for both inside and outside of the circle
i = 0
# initialize x and y axis value array
x = []
y = []
# total point inside the circle and in total
num_point_circle = 0
num_point_total = 0
# array for x and y axis coordinates inside circle
point_circle_x = []
point_circle_y = []
# array for x and y axis coordinates outside circle
point_out_x = []
point_out_y = []
# generate the array for x and y axis
while i < n:
x.append(random.uniform(-1, 1))
y.append(random.uniform(-1, 1))
distance = x[i] ** 2 + y[i] ** 2
# check if coordinates is inside circle
if distance <= 1:
num_point_circle += 1
point_circle_x.append(x[i])
point_circle_y.append(y[i])
# the rest is outside circle
elif distance > 1:
point_out_x.append(x[i])
point_out_y.append(y[i])
num_point_total += 1
i += 1
# calculate pi
pi = 4.0000 * num_point_circle / num_point_total
# output the value of pi
print("Pi is now value at : ", pi)
# plot dots for in and outside a circle
plt.scatter(point_circle_x, point_circle_y, color='red')
plt.scatter(point_out_x, point_out_y, color='blue')
# plot circle
circle = plt.Circle((0, 0), 1, color='black', alpha=0.7, fill=False, linewidth=4)
plt.gca().add_patch(circle)
plt.axis([-1, 1, -1, 1])
plt.show()
结果,如果随机取10个点:
pi=2.4
取100个点:
Pi = 2.96
1000个点:
Pi=3.232
1000个点:
Pi=3.1424
最后50000个点:
Pi=3.15208
你会发现1万个点的时候反而更接近于真实的Pi的值,当然因为点都是随机的,如果输入50万个点的话:
Pi = 3.1416
求高手大神们指点更简便的方法,或者如何精简代码。
不胜感激。