Calculating pi in Python using geometry

I am posting this code with the hope that this community will want to help me smooth out some errors that I seem to be unable to resolve. It is quite short, designed to guess pi and not intended to replace already effective approaches. This is not a task.

# 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)
+3
source share
1 answer
# 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)
+8
source

Source: https://habr.com/ru/post/1793131/


All Articles