Archived

This topic is now archived and is closed to further replies.

kelaklub

Ceil

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 ]

Share this post


Link to post
Share on other sites