1
double x = 0;
double P = 0.327; //P is a actually function that return double and change all the time
double w1 = 1/4; //prints 0 (w1 and w2 are same as P)
double w2= 10/4; //prints 2
x=x+P*w1+(1-P)*w2; 
System.out.println(x); // prints 1.346 and the real result is 1.76425

i dont know how to overcome the problem of double that is rounding down, i tried the BigDecimal, maybe i just dont do it right..

i dont need very precise result but i do need the result 1.764. Thanks in advance.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Edan Chetrit
  • 4,713
  • 2
  • 20
  • 20

3 Answers3

3

That's because you are performing integer division (1, 4 and 10 are treated as integers, so 1/4 and 1/10 will be integer divisions).

Change w1 and w2 to:

double w1 = 1/4.0;
double w2 = 10/4.0;

This way java will perform floating point division

BackSlash
  • 21,927
  • 22
  • 96
  • 136
3

1 / 4 and 10 / 4 are integer divisions. Their result is an int, that is then widened to a double. What you want is a double division:

double w1 = 1.0 / 4

or

double w1 = 1 / 4.0
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

setScale and then use the ROUND_HALF_DOWN to rounding down in bigdecimal

   BigDecimal bigdecimal=new BigDecimal(x);
   bigdecimal.setScale(2, BigDecimal.ROUND_HALF_DOWN);
Nambi
  • 11,944
  • 3
  • 37
  • 49