I am a new member here and I am going to go straight to this as I spent all of my Sunday trying to hug him.
I am new to Python, having previously studied C ++ coding to a basic level (it was a 10-week university module).
I am trying to use several iterative methods to calculate Pi, but both of them are a bit inaccurate, and I'm not sure why.
The first method of study at the university is that I am sure that some of you have seen this before.
x=0.0 y=0.0 incircle = 0.0 outcircle = 0.0 pi = 0.0 i = 0 while (i<100000): x = random.uniform(-1,1) y = random.uniform(-1,1) if (x*x+y*y<=1): incircle=incircle+1 else: outcircle=outcircle+1 i=i+1 pi = (incircle/outcircle) print pi
It is essentially a generator for random (x, y) coordinates on a plane from -1 to +1 on both axes. Then, if x ^ 2 + y ^ 2 <= 1, we know that the point lies inside a circle of radius 1 in a box formed by the coordinate axes.
Depending on the position of the point, the counter increases for incircle or outcircle .
The value pi is the ratio of the values inside and outside the circle. Coordinates are generated randomly, so they must be uniform.
However, even with very high iteration values, my result for Pi is always around 3.65.
The second method is another iteration that calculates the circumference of the polygon with an increase in the number of sides until the polygon is almost surrounded, then Pi = Circle / Diameter. (I'm kind of cheated because the coding has the term math.cos (Pi), so it looks like I'm using Pi to find Pi, but this is only because you cannot easily use degrees to represent angles in Python). But even for high iterations, the final result seems to end at 3.20, which again is wrong. The code is here:
S = 0.0 C = 0.0 L = 1.0 n = 2.0 k = 3.0 while (n<2000): S = 2.0**k L = L/(2.0*math.cos((math.pi)/(4.0*n))) C = S*L n=n+2.0 k=k+1.0 pi = C/math.sqrt(2.0) print pi
I remember when I was doing my course in C ++, I was told that the problem is common, and this is not due to mathematics, but because of something inside the encoding, but I don’t remember exactly. This could be due to random number generation or restrictions on the use of floating point numbers or ... something really. It could just be my math ...
Can anyone think what the problem is?
TL; DR: Trying to calculate Pi, I can get close to it, but not very accurately, no matter how many iterations I do.
(Oh, and one more point - in the second code there is a line denoting S = 2.0 ** k. If I set "n" to something above 2000, the value of S becomes too large to process, and the code fails. How can I can this be fixed?)
Thanks!