随机分布一些点在数轴上,x和y的绝对值都小于等于1,现在求圆周率-python篇

网上看到一个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

求高手大神们指点更简便的方法,或者如何精简代码。
不胜感激。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值