0

Im wrinting app which has that piece of code, where t->tick is float:

usleep(1000);
t->tick = t->tick + 0.001;
printf("tick is %f, firing time is %f\n", t->tick, t->firing_time);

i found that there is error in usleep?:

tick is 0.313000, firing time is 2.000000
tick is 0.314000, firing time is 2.000000
tick is 0.314999, firing time is 2.000000
tick is 0.315999, firing time is 2.000000

How to get rid of that error ?

JosiP
  • 2,619
  • 5
  • 29
  • 33

2 Answers2

2

There's no error, you simply do not understand how binary floating-point math works.

zvrba
  • 24,186
  • 3
  • 55
  • 65
0

Looks like a rounding stability error in printf.

Try: printf("tick is %.3f, firing time is %.3f\n", t->tick, t->firing_time);

ocsid80
  • 111
  • 1
  • nope, cause when im testing condition firing_time==tick, i always got false – JosiP Jun 14 '11 at 12:38
  • 3
    @josip You can't compare floating point numbers like that. The usual approach is to subtract the two floats, and check to see if the result is smaller than a given value, like 0.001. – dandan78 Jun 14 '11 at 12:38
  • Where do you see a comparison operation here? – ocsid80 Jun 14 '11 at 12:39
  • 1
    This is not `printf`'s doing, it is fundamental to floating point arithmetic. There is no perfectly accurate representation for 0.001, so there can not be perfectly accurate mathematics involving that quantity. – dmckee --- ex-moderator kitten Jun 14 '11 at 12:45