0

I am trying to implement a simple equation in Java but keep getting the wrong answer apparently due to operator precedence which I am unable to understand.

The equation is:

NewMean = ((N-1) / N) * OldMean + (Xn / N)

in a simple example: N = 6 ; OldMean = 6 ; Xn = 16

So, NewMean = 5/6 * 6 + 16/6 = 7.6667 (Correct answer)

but in code implementation on Java i get wrong answer (2.6665):

double NewMean = ((N-1)/N)*oldMean + (Xn/N);
Salman Shaukat
  • 333
  • 3
  • 14
  • 2
    What are the type of Xn, oldMean and N ? Are they all double ? – NoDataFound Oct 15 '18 at 17:19
  • Hi Thanks. Type Xn is double and N is int. and now after changing N to double I am getting the correct result. – Salman Shaukat Oct 15 '18 at 17:22
  • 1
    Since `N` is an `int`, you get the issue addressed in the [duplicate](https://stackoverflow.com/q/4685450/5221149). Simplest fix is to change `1` to `1d`. Assuming `Xn` is a `double`, that will correct result to be `7.666666666666666` – Andreas Oct 15 '18 at 17:23
  • 1
    Please stick to the Java Naming Conventions: variable names should start with lowercase. For instance, `N` should be `n` and `NewMean` should be `newMean`. – MC Emperor Oct 15 '18 at 17:40

1 Answers1

5

If the N variable is type int, then ((N-1) / N) is computed using integer division and will round 5/6 down to 0. Change N to a floating-point type and you should get the correct answer.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880