corny
corny

Reputation: 1

Need help calculating pi in python with while function

Hey I'm new to Python and decided to try to make a program that calculates pi to as many decimal places as possible.

I used radii of the circle to form two sides of a triangle, with angle x between them, and used cosine law to find the length of the opposite side. Then I multiply by 360/x to get the perimeter of a polygon with # of sides approaching infinity to make a circle.

I've tried it in a calculator and it works but in python then number is way off and I can't seem to fix it.

Can someone help me out here?

import math

n = 1

while True:
  def angle(x):
    y = 360 / x
    z = y * (  (0.5 - (math.cos(math.degrees(x))  *0.5)  )**0.5)

    print(z)

    return x

  n = (n + 1)
  angle(45 / n)

Upvotes: 0

Views: 397

Answers (2)

Jonathan Zhou
Jonathan Zhou

Reputation: 11

I think your angle(x) function wants to take a number of sides and give an approximation for pi, so the name isn't the best description of the function, but that doesn't really matter. The main issue here seems to be some confusion around function arguments and return values.

Anyway, the angle(x) function should take an input of the number of sides, which we can call sides, so we can change that to angle(sides). We can find the angle y with y = 360.0/sides.

The side length of each triangle, is (0.5-(math.cos(math.radians(y))*0.5))**0.5, because math.cos() takes an angle in radians. The function returns the function argument x (which we changed to sides), but we want to return the total perimeter of our n-gon, which is z.

The function never changes within the loop, so finally we can move the angle(sides) function to the beginning so we aren't defining the function for every value of n.

For the actual calculation, we just go over increasing values of n and print each approximation of pi. We can set a limit of 100 sides by changing the while loop to while n < 100, and we print(angle(n)) for each value of n.

Here is my refined code.

import math

def angle(sides):
    y = 360.0/sides
    z = sides * (0.5-(math.cos(math.radians(y))*0.5))**0.5
    return z

n = 1
while n < 100:
    n += 1
    print(angle(n))

Upvotes: 1

bantmen
bantmen

Reputation: 768

If you are using Python 2, try changing the line y = 360 / x with y = 360 / float(x) otherwise it does integer division.

Upvotes: 0

Related Questions