0

I have to stop calculation whenever the count is not a fractional number. I have the following code working on GCC. Its not complete a part of code where I got stuck is given below.

double count;
long int ticks = 256;

do
{
    count = (500e-6) / (200e-9 * ticks--);
} while (count != (unsigned long) count);

Actually at ticks = 250, count = 10 (on calculator) then it should stop but when I saw the value of count its not 10 instead it is 9.960159 (By using GDB) since it's not a whole number it stops at some other value. Now how to solve this problem...

Next-93
  • 97
  • 1
  • 7
  • 2
    @cid mod is integer division. – nicomp Jan 12 '20 at 18:51
  • The calculation is really ill-advised. And most probably it dies because of division by zero. – Antti Haapala -- Слава Україні Jan 12 '20 at 18:54
  • 1
    It smells like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Weather Vane Jan 12 '20 at 18:56
  • @nicomp ah my bad, it doesn't work in C – Cid Jan 12 '20 at 19:04
  • I suggest doing some hand simplification on your code. Neither 500e-6 nor 200e-9 is exactly representable as an IEEE 754 64-bit binary float (the commonest representation of `double`). 500e6 and 200e9 are both exact, as is 200e9/500e6. However, the general concept of stopping on a floating point number being an exact integers is risky. – Patricia Shanahan Jan 12 '20 at 19:06
  • 1
    Note that `500e-6 / 200e-9` is `2500` so perhaps reorganising as an integer multiplication will do what you need. – Weather Vane Jan 12 '20 at 19:08
  • 9.960159 is far too far off for the result of (500e-6) / (200e-9 * 250)). It is much closer to (500e-6) / (200e-9 * 251)). I suspect confusion caused by the completely unnecessary use of postfix -- instead of doing the subtraction in a separate statement. `ticks` will become 250 during evaluation of the expression in which the division is by 251. – Patricia Shanahan Jan 12 '20 at 21:56

0 Answers0