使用几何方法在Python中计算π

3 投票
1 回答
962 浏览
提问于 2025-04-16 12:05

我发这段代码是希望大家能帮我解决一些我自己搞不定的bug。这段代码比较短,目的是用来猜测圆周率π,并不是想取代那些已经很有效的方法。这不是一个作业。

# 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 = circumference + distance
    circumference = circumference * 4
    return circumference

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

1 个回答

8

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,尤其是当我们刚开始学习编程的时候。比如,有人可能会在使用某个功能时,发现它并没有按照预期的方式工作。这种情况下,通常需要仔细检查代码,看看是不是哪里出了问题。

有时候,解决问题的关键在于理解工具的使用方法和它的限制。很多时候,文档中会有说明,帮助我们更好地理解如何使用这些工具。如果遇到困难,可以尝试在网上搜索相关的问题,看看其他人是怎么解决的。

总之,编程是一项需要不断学习和实践的技能,遇到问题是很正常的,重要的是要保持耐心,逐步解决它们。

# 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)

撰写回答