开发者

Calculating pi in Python using geometry

开发者 https://www.devze.com 2023-02-11 18:37 出处:网络
I\'m posting this code with the hope that this community will be willing to assist me in ironing out some bugs I can\'t seem to be able to tackle. It\'s quite short, is intended to guess pi, and is no

I'm posting this code with the hope that this community will be willing to assist me in ironing out some bugs I can't seem to be able to tackle. It's quite short, is intended to guess pi, and is not intended to replace already efficiently working approaches. This is not an assignment.

# this code is completely broken

from math import sqrt

def get_y(x, r):
    return sqrt((r^2.0)-(x^2.0))

def get_distance(x1, y1, x2, y2):
    return sqrt( (x2-x1)^2.0 + (y2-y1)^2.0 )

def c(r):
    def range(b):
        a = 0
        while a < b:
            yield a
            a = a + 1
    circumference = 0.0
    for x1 in range(r):
        x2 = x1 + 1.0
        y1 = get_y(x1, r)
        y2 = get_y(x2, r)
        distance = get_distance(x1, y1, x2, x2)
        circumference = cir开发者_JS百科cumference + distance
    circumference = circumference * 4
    return circumference

print get_y(0, 4)
radius = 400.0
print "%.64f" % (c(radius) / radius * 2)


# Not broken anymore, prints 3.1415559...

from math import sqrt

def get_y(x, r):
    return sqrt((r**2.0)-(x**2.0)) # First mistake: ** is exponentiation, not ^

def get_distance(x1, y1, x2, y2):
    return sqrt( (x2-x1)**2.0 + (y2-y1)**2.0 )

def c(r):
    # def range(b): # redundant
    #     a = 0
    #     while a < b:
    #         yield a
    #         a = a + 1
    circumference = 0.0
    for x1 in range(r):
        x2 = x1 + 1.0
        y1 = get_y(x1, r)
        y2 = get_y(x2, r)
        distance = get_distance(x1, y1, x2, y2) # second mistake, x2, x2 --> x2, y2
        circumference = circumference + distance
    circumference = circumference * 4
    return circumference

print get_y(0, 4)
radius = 400.0
print "%.64f" % (c(radius) / (radius * 2)) # third mistake: / radius * 2 --> / (radius*2)
0

精彩评论

暂无评论...
验证码 换一张
取 消