-4

Question That Needs To Be Solved: http://i62.tinypic.com/23rtieb.png

I have this problem I need to solve using Java. However I tried but was not able to. Here is what I have done so far.

public class Cirlce {
    public static void main(String[] args) {
        int counter = 0;
        double pi = 0;
        final String piCharacter = "\u03C0";
        double num = 10000;
        int e = 0;
        for (int i = 0; i < 10000; i++) {

            // r^2 = x^2 + y^2
            double dx = Math.random();
            double dy = Math.random();
            double r = Math.sqrt(dx * dx + dy * dy);

            if (r < 1) {
                counter++;
                pi = 4 * counter / 1000;
            }
            e++;
            if (e == counter) {

                System.out.println(pi);
                counter += 1000;
            }


            System.out.println("The Approximated Value Of " + piCharacter + " is: " + pi);
        }
    }
}

The answer is that I need 10 outputs that are close to the value of pi.

rgettman
  • 176,041
  • 30
  • 275
  • 357
Arjun Dhiman
  • 164
  • 8
  • Note that your `if(e==counter)` is only going to return true a handful of times, then never return true again. I would actually recommend using nested loops here - an outer one where the index goes from 0 to 9, and an inner one where the index goes from 0 to 999. You should print out your estimate of pi at the end of each iteration of the outer loop. – Dawood ibn Kareem Apr 22 '14 at 21:33
  • Can you show me how you would solve this problem? – Arjun Dhiman Apr 22 '14 at 21:35
  • `counter` is being used to count the number of hits inside the circle, but it is also erroneously being used to try to match every 1000th loop iteration. `e` is being incremented every time around the loop, making it a virtual duplicate of `i`, the loop variable. What a mess. – David Conrad Apr 22 '14 at 21:37
  • Zero, I explained how I would solve the problem. I hope you're not asking me for actual code. – Dawood ibn Kareem Apr 22 '14 at 21:42
  • Thank You For The Help, I Think I Got What Question Was Asking. – Arjun Dhiman Apr 22 '14 at 22:19

1 Answers1

2

One problem is in this line:

pi = 4 * counter / 1000;

4, counter and 1000 are all int, so you are doing integer arithmetic here. You'll need to make at least one of the values a double, for example:

pi = 4.0 * counter / 1000;

There are some other errors. For example, why are you doing counter += 1000;? Cleanup your code and make sure you understand exactly what each statement does.

Jesper
  • 202,709
  • 46
  • 318
  • 350