Skip to main content
gamedev.net
🔒 Locked

Ceil

Started by kelaklub 5 replies 450+ views
Original Post
kelaklub
kelaklub
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.
marijnh
marijnh
#include <cmath>

double c1 = std::ceil(2.5);
float c2 = std::ceilf(2.5f);
kelaklub
kelaklub
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?
Brother Bob
Brother Bob
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.
kelaklub
kelaklub
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.
Zahlman
Zahlman
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.
rypyr
rypyr
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 ]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.