1

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.

Axim
  • 332
  • 3
  • 11
  • 2
    Hint: `int / int = int` (and not `double`). – Seelenvirtuose Oct 30 '15 at 17:25
  • Are you running this in an IDE or from a command line? make sure you are correctly setting up your arguments, for if arg = 0 then that wouls give you the result you are finding. – dodo Oct 30 '15 at 17:27
  • @Seelenvirtuose: bingo, that is OP's problem because the Java program is throwing away the fractions *before* promoting to double. – user268396 Oct 30 '15 at 17:28

1 Answers1

4

This line is dividing integers and then stores the (truncated) result to a double

double newPi = i / j;

cast one of the variables to double if you want an accurate result

double newPi = (double) i / j;

same with

double pi = numer / denom;
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82