-7
    double formula1, formula2;
    int plus;
    int VALUE = 10000;    



  private void processFormula2()
    {
        for (int k = 0; k <= VALUE; k++) {
            if (k % 2 != 0) {
                if (plus % 2 == 0) {
                    double math = 1/k;
                    formula2 += math;
                    System.out.println("Getting Formula: "+ formula2);
                    plus++;
                } else {
                    formula2 -= 1/k;
                    plus++;
                }
               // System.out.println("Term: " + formula2);
            }
        }

    }

I am trying to get my formula to print out the result of Pi based off this formula that my teacher gave us. But for some reason it just returns 1.0, not really sure why. Any help or suggestions would be appreciated :)

Eggspurt
  • 63
  • 1
  • 9
  • 5
    There are many variables which are unknown for us like `VALUE`, `plus`, `formula2` .. Please provide all relevant parts of code .. – hagrawal7777 Nov 20 '15 at 13:38
  • Te expand on what hagrawal said... Please [edit] your post to provide us a [mcve]. Without that, we're even more in the dark than you are. – Kevin J. Chase Nov 20 '15 at 13:41
  • 2
    What is the value of 'VALUE'? Where is your 'plus' variable declared? Where is your 'formula2' variable declared? Are you aware that you should be using mixed division (1.0 / k) instead of integer division for the declaration of 'math' (you can alternatively cast 1 to a double)? – MrPublic Nov 20 '15 at 13:42
  • Sorry, I forgot to add this I apologize :/ – Eggspurt Nov 20 '15 at 13:44
  • 1
    Suggestion: put more println statements in and see what it is doing. – rghome Nov 20 '15 at 13:44
  • Possible duplicate of [Division of integers in Java](http://stackoverflow.com/questions/7220681/division-of-integers-in-java) – Teepeemm Nov 20 '15 at 15:05

2 Answers2

3

Here's the problem:

double math = 1/k;

and

formula2 -= 1/k;

k is an int variable, so the JVM won't never return a decimal number in this statement. It will take only two possible values: 0 (if k > 1) or 1 (if k == 1) because the JVM performs the division before promoting the result to double.

Try this:

formula2 -= 1/(double)k;

Take a look at Numeric Promotions

jfcorugedo
  • 9,793
  • 8
  • 39
  • 47
1

Firstly, there are multiple errors with variable declaration.

double math = 1/k;will not truly work in Java due to how integer division is handled. You must either cast '1' to a double like double math = (double)1/k; or specify that you are using mixed mode arithmetic by using double math = 1.0/k;. This is also a problem for your formula2 variable (Along with you should always initialize your variables like formula1, formula2, and plus). You must also do the same thing with formula2 -= 1/k;.

Secondly, we have no idea what you are setting those variables to in the first place, nor do we have any test cases to compare to.

MrPublic
  • 520
  • 5
  • 16