使用分而治之的方法逼近 Pi

问题描述 投票:0回答:0

我偶然发现了 this 使用分而治之的方法来近似 pi 的巧妙想法,我想用 Python 对其进行编程。遗憾的是,我在创建 Python 版本时遇到了很多问题,尤其是因为我想避免 OOP。这是我到目前为止所拥有的和工作的:

# I think pygame may be the right choice for a visualisation
import pygame
import random
import math

# Init pygame
pygame.init()
screen_width = 800
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))

def check(x, y):
    return 1 if x * x + y * y <= 1 else 0

def init():
    global process, render_list, square, index, tick, render, width, height
    process, render_list = [], []
    index, tick, render = 0, 0, 0
    width, height  = screen.get_width(), screen.get_height()
    # I don't know how to initialize the square here, because I don't want oop

def create_square(parent, x, y, s):
    inside = check(x, y) + check(x+s, y) + check(x+s, y+s) + check(x, y+s)
    area = inside / 4 * s * s

    if inside < 4 and (inside > 0 or s == 2):
        process.append((parent, x, y, s))
    else:
        render_list.append((x, y, s, area))

    return area

def compute():
    while len(process) > 0:
        parent, x, y, s = process.pop()
        p1 = create_square(parent, x, y, s/2)
        p2 = create_square(parent, x+s/2, y, s/2)
        p3 = create_square(parent, x+s/2, y+s/2, s/2)
        p4 = create_square(parent, x, y+s/2, s/2)
        area = p1 + p2 + p3 + p4
        if parent:
            parent[0].update()
        else:
            render_list.append((x, y, s, area))

def update():
    for square in render_list:
        square_area = create_square(None, square[0], square[1], square[2])
        square_area = square_area if square[3] is None else square[3]
        square[3] = square_area

def draw():
    # I have no Idea what to do here
    return -1

我主要是想重写这个脚本语言(microscript,好像是基于lua的,我也不知道)我以前没见过用Python写的,不知道怎么写完

python pi divide-and-conquer
© www.soinside.com 2019 - 2024. All rights reserved.