0

I am using double array in my program and trying to assign it a value using one basic formula. But I am getting wrong result.

class temp
{
public static void main(String args[])
{

double ary_x[]=new double[5];
double diff=0.1d;
ary_x[0]=2.1d;
int num=5;

for(int i=1;i<num;i++)
      {
          ary_x[i]=ary_x[i-1]+diff;   
      }

}
}

Rather than getting values like 2.1, 2.2, 2.3, 2.4 and 2.5 I am getting values like 2.1, 2.2, 2.000000000000003, 2.000000000000004 and 2.000000000000005 . But if I enter initial value 2.5 and add 0.5 each time then it is giving me the proper output. Why I am getting values like this ? Please help me. Thank you :)

  • Potential Duplicate of: http://stackoverflow.com/questions/1661273/floating-point-arithmetic-not-producing-exact-results – Mshnik Feb 24 '15 at 17:32
  • See also: http://stackoverflow.com/questions/588004/is-floating-point-math-broken – assylias Feb 24 '15 at 17:32

0 Answers0