-
ceil function
A colleague of mine and I are running the "ceil" function in C and getting some wierd output. For example we run....
float q, k;
int r, s;
for (s=0; s <= 100; s++) {
q = (s/k) ;
r = ceil (q) ;
} ;
... We know from output that when k = .52 and s = 52, the program computes q = 100.00 and r = 100. That's good. But when k = .53 and s = 53, the program computes q = 100.00 and r = 101. That's weird.
Why would the ceil function round 100.00 to 100 in one case and 100.00 to 101 in another
case?
Thanks for your help,
-Keith
Assistant Professor
Florida International University
Miami, FL 33199
-
sounds suspicious to me.... what compiler and os?
-
Have no idea why but if you change q and k to double it works
Code:
#include <stdio.h>
#include <math.h>
int main()
{
double k, q;
int r, s;
s = 53;
k = .53;
q = (s/k);
r = ceil(q);
printf("\n%d\n", r);
return 0;
}
must be some dodgy type casting rule about converting doubles to floats or ints???????
-
> the program computes q = 100.00 and r = 101. That's weird.
But floating point maths is inexact at the best of times
If q is 100.0001 say, then it will print out as 100.00 (to 2 decimal places), but ceil will still round that up to the next integral value (101 in this case).
ceil doesn't care by how little a number is over 100.00, if it is, then rounding up will occur.
Changing to doubles just changes the problem - it does not make it go away. You will eventually find an example where it produces a "just-over" result, and you're back with the same problem again.
-
Mmmm, been thinking about this Salem. Would it be more accurate to split the double into 2 integers, 1 for the whole and 1 for the fractional part then just check the value of the fractional part. something like:
Code:
int ceil(double q)
{
int x, y;
x = q;
y = (q-x) * 100;
if(y > 0)
return (x + 1);
else
return x;
}
This assumes q has 2 decimal places, you can add extra 0's to the y = (q-x) * 100 for extra decimal places.
But is it accurate?
-
Thanks for all the feedback.
Changing the character types from floats to doubles seemed to resolve the problem for our inputs, but we will take Salem's broader advice for future inputs.
By the way, the gist of c-coder's suggestion was very useful.
Thanks again to all of you,
-Keith
Assistant Professor
Florida International University
Miami, FL 33199