Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

comparing double value

Status
Not open for further replies.

lupien1

Programmer
Mar 1, 2005
34
CA
All variable, in the following "for loop exemple" except nbval are double type.

I have a problem with the condition "val <= valmax". When val is increment by the step value and equal to valmax the for loop break has if the val was greater than valmax. How can i correct this problem?

for (nbval = 0, val = val0; val <= valmax ; val += step)
{
values[nbval] = val;
nbval++;
}

Thank you and please excuse my english!!!
 
Try this function:
Code:
void Dbl()
{
  double x = 0.0;
  for (int i = 0; i < 10; ++i)
      x += 0.1;
  if (x == 1.0)
     printf("It's impossible!\n");
  else
     printf("10*0.1 == %20.16f (he-he)\n",x);
}
Never compare floating point number on equality. Doubles are approximations of numbers, not math real numbers.
 
Thank you both for the time you took to answer me.

We add the same problem with our fortran code and we did the same thing (val < valmax + step / 1000) to correct it. I was hoping that a special configuration can solve this problem.

Thank's again
 
No any silver bullets (soft or hard;) to solve this problem. It's an old and well-known computational mathematics issue. All your math methods must recognize and take into account this problem (in Fortran, C, C++, asm etc;)...
Get a good book about comp math...
 
Usual way to deal with equality of any floating point thing is to test +/- an acceptable error. My favourite maths methods book is Sedgwick et al. Numerical Methods in C.

 
The usual way is this
Code:
(fabs(Val1 - Val2) < 0.0001)
adjusting the number on the right for precision.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top