algorithm - Calculating pi in Python using geometry -
i'm posting code hope community willing assist me in ironing out bugs can't seem able tackle. it's quite short, intended guess pi, , not intended replace efficiently working approaches. not assignment.
# code broken 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): = 0 while < b: yield = + 1 circumference = 0.0 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... math import sqrt def get_y(x, r): return sqrt((r**2.0)-(x**2.0)) # first mistake: ** 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 # = 0 # while < b: # yield # = + 1 circumference = 0.0 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)
Comments
Post a Comment