Wednesday, May 06, 2009

Python math.ceil and math.floor

A couple of posts ago I have already been discussing the round function on Python which you can use to round your float variables. When discussing round we have to discuss the floor and ceil functions which are in the math library which ships with Python.

The functions floor and ceil are used to "round" a number to the nearest int value and still keep it as a float. For example floor will always "round" down to the nearest int value however will not make the float a int value. So if we floor 1.9 the result will be 1.0 and for ceil it will be the other way around. A example of ceil 1.2 will result in 2.0 and 2.1 will result in 3.0

To be able to use the floor and ceil functions you have to import the math class first by using the import command. A example is shown below with some example of math.floor(x) and math.ceil(x).


Post a Comment