我发布了这段代码,希望这个社区能够帮助我解决一些我似乎无法解决的问题.它很短,旨在猜测pi,并不打算取代已经有效的工作方法.这不是一项任务.
# 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)
解决方法:
# 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)
标签:python,algorithm