I wrote up a quick program in Java to try and find approximate values for Pi using fractions of integers. However it doesn't appear to be doing at all What I want it to do. In fact, it appears to do nothing at all, and just repeatedly print out the hard-coded starting values.
In order to figure out what's going wrong, I translated my code to Python, because I'm only just learning Java but am quite comfortable in Python. However, for some reason, it works exactly as I intended. I must've read through both versions of the code at least 10 times now, and I fail to see why one works and the other doesn't.
Anyway here's my code in Java:
public class RationalPi {
public static void main(String[] args) {
int arg;
if (args.length>0) { arg = Integer.parseInt(args[0]); }
else { arg = 10000; }
int numer = 3;
int denom = 1;
double pi = numer / denom;
for (int i=numer; i<=arg; i++) {
for (int j=i/4; j<=i/2; j++) {
if (j==0) { continue; }
double newPi = i / j;
if (Math.abs(newPi-Math.PI) < Math.abs(pi-Math.PI)) {
System.out.println("found better approximation");
numer = i;
denom = j;
pi = newPi;
}
}
System.out.println(String.format("%d /%2d == %f", numer, denom, pi));
}
}
}
And here's what I believe should be functionally identical code in Python:
from math import pi as PI
def findApproximate(arg=10000):
numer, denom = 3, 1
pi = numer / denom
for i in range(numer, arg+1):
for j in range(int(i/4), int((i/2)+1)):
if not j:
continue
newPi = i / j
if abs(newPi-PI) < abs(pi-PI):
print("Found better approximation")
numer, denom, pi = i, j, newPi
print("%d / %d == " % (numer, denom) + str(pi))
return pi
But for some reason this works perfectly while the above doesn't, and it's driving me absolutely bonkers. Please help if you can.