Friday, January 28, 2011

The Nearest Integer Function In Python

Perhaps attesting to its reputation as a powerful and flexible programming language, Python contains many internal libraries to automate common or complex computational and mathematical tasks. The "math library" contains many methods to accomplish typical calculations or operations such as rounding. However, rounding decimals in Python does not round to an integer, but a whole decimal. Converting to integers requires the use of the Python math library along with the use of some built-in conversion libraries.


Python and Rounding>>f = 5.455


>>>round(f)


5.0


>>>round(f, 2) //rounds to 2 decimals


5.46


Ceiling and Floor Methods>>import math


>>>f = 3.5


>>>g = -3.5


>>>floor(f)








3.0


>>>ceil(3.5)


4.0


>>>floor(g)


-4.0


>>>ceil(g)


-3.0


Rounding and Integers>>f = 3.5


>>>round(f)


4.0


>>>int(round(f))


4.

Example Method>>import math


>>>def integerFloor(x):


. . . return int(floor(x))


>>>def integerCeiling(x):


. . . return int(ceil(x))


>>>def rounding(x, dec):


. . . if dec == 0:


. . . return int(round(x))


. . . else:


. . . return(round(x, dec))

Tags: >>>floor >>>ceil, contains many, math library, return round