Python趣味小问题——用积分思想计算圆周率

[文本出自天外归云的博客园]

早上起来突然想求圆周率,1单位时圆的面积。

代码如下:

from math import pow, sqrt


def calc_circle_s_with(r, dy, x_slices):
    x_from_start_to_cc = sqrt(1 - pow(dy, 2))
    dx = x_from_start_to_cc / x_slices
    x_to_edge = 1 - x_from_start_to_cc
    quarter_circle_s = 0
    while x_to_edge < 1:
        rect_s = dy * dx
        quarter_circle_s += rect_s
        x_to_edge = x_to_edge + dx
        dy = sqrt(1 - pow((1 - x_to_edge), 2))
    circle_s = 4 * quarter_circle_s
    print(circle_s)


calc_circle_s_with(1, 0.0001, 10000000)

运行结果接近3.1415926,dy传的越小,x_slices传的越大,就越接近。

半径为:1

初始小矩形到圆周的距离:1 - x_from_start_to_cc

其中dy代表四分之一圆中初始小矩形的高度,x_slices代表小矩形的宽度:(1 - x_from_start_to_cc) / x_slices

四分之一圆的面积积分为:quarter_circle_s

posted @ 2019-12-08 22:09  天外归云  阅读(698)  评论(0编辑  收藏  举报