Ceil

Started by
5 comments, last by kelaklub 20 years ago
Microsoft excel has a CEILING method that will ceil a number to a certain precision. Does anyone know if something similar is available for C++. Thanks.
Advertisement
#include <cmath>

double c1 = std::ceil(2.5);
float c2 = std::ceilf(2.5f);
I was thinking more along the line if you had a number like 7.1, and you needed to take the CEIL to the nearest one sixteenth of an inch(0.0625). Excel lets you do CEILING(7.1, 0.0625) and gives back 7.125. Is there a c++ way to do this?
This will round v to nearest multiple of q.
v = 7.1;q = 1/16;r = q*round(v/q);

round() is a function that rounds to nearest integer (code taken from a MALTAB script of mine). Replace round with ceil/floor to round up/down to nearest multiple.
That is so awesome. I was doing something stupid like iterating through a for loop, to acheive the same result. But what you suggested is just so much more cleaner, probably alot more efficient to. Thanks much.
If it''s that valuable to you, you should probably encapsulate it in a function:

double granularCeil(double input, double quantum) {
return std::ceil(input/quantum) * quantum;
}

Handling a quantum of 0 gracefully, dealing with floats (and possibly other numeric types? Do you maybe have a Rational number class you''d want to do this with?) etc. is left as an exercise for the reader.
quote:Original post by kelaklub
I was ... iterating through a for loop ... But what you suggested is just so much more cleaner, probably alot more efficient to..


Probably?!?!?

[ CodeDread ]

This topic is closed to new replies.

Advertisement