Ceil and floor in python

Python Ceil and Floor: A Step-By-Step Guide

The Python ceil() function rounds a number up to the nearest integer, or whole number. Python floor() rounds decimals down to the nearest whole number. Both of these functions are part of the math Python library.

When programming in Python, you may encounter a scenario where you want to round a number to the nearest integer.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

That’s where the Python math.floor() and math.ceil() methods come in. You can use the math.floor() method to calculate the nearest integer to a decimal number. The math.ceil() method rounds a number down to its nearest integer.

This tutorial will discuss using the floor and ceil methods to return the floor or ceiling of a provided value. We’ll walk through examples of each of these methods in a program to showcase how they work.

Python Floor Function

The Python math.floor() method rounds a number down to the nearest integer. This method takes one argument: the number you want to return. In Python 3, math.floor() returns an integer value.

Читайте также:  Best html css site

Calculating the floor of a number is a common mathematical function in Python. The floor of a number refers to the nearest Python integer value which is less than or equal to the number. To put it another way, the floor of a number is the number rounded down to its nearest integer value.

The Python math module includes a method that can be used to calculate the floor of a number: math.floor(). math.floor() takes in one parameter, which is the number whose floor value you want to calculate.

Here’s the syntax for the floor() function:

import math math.floor(number)

The Python floor() division function is part of the math library. In order to use it, we first need to import the math library. You can import the math library into your program using a Python import statement.

Floor() Python Example

Say that we are working in a coffee shop. We want to create a calculator that rounds down the quantities of the beans we have available to their nearest whole number. This makes it easier for us to understand the quantity of much coffee we have left.

We could round down the quantity of a bean to its nearest whole number using the following code:

import math quantity = 250.92 rounded = math.floor(quantity) print(rounded)

Our code returns the smallest integer closest to 250.92, which is: 250.

On the first line, we import the math library. Next, we define a Python variable called quantity. This variable stores the quantity of the bean we have in storage. We use the math.floor() function to round down the quantity variable to its nearest whole number.

In this case, the nearest whole number to 250.92 is 250. Our code returned 250.

We can use the math.floor() method on negative numbers. Let’s say that we are writing a program that calculates the quantity of many beans we’ll have left at the end of the month.

Our program has projected that, given how many sales we have seen so far, we will have a negative amount of beans. In other words, we will run out of beans. We print the math.floor() output to the console.

We want to round down our value to the nearest whole number. This will let us know the quantity of beans to order, based on current demand:

import math quantity_projection = -25.21 rounded = math.floor(quantity_projection) print(rounded)

The program has rounded down our negative value to the nearest whole integer, which in this case is -26.

Python Ceil

The math.ceil() method is the opposite of the math.floor() method. math.ceil() rounds a number up to the nearest integer. Like math.floor(), math.ceil() returns an integer value.

Whereas floor rounds down a number to its nearest whole value, ceil rounds a number up to its nearest whole value.

Here’s the syntax for the math.ceil() method:

import math math.ceil(number)

The syntax for the ceil function is the same as the syntax for math.floor(). Both methods take in one parameter: the number you want to process using the method. The ceil() function returns the ceiling number of a float, or the largest integer closest to it.

ceil() Python Example

Let’s discuss an example of the math.ceil() method in action. Say that we have decided we want to calculate the ceiling value of each bean quantity. In other words, we want to know the smallest whole number above each bean quantity. We want to calculate this so we know how many beans to order in our next shipment.

We could use the following code to round up the bean quantity we have to the nearest whole number:

import math quantity = 22.15 rounded = math.ceil(quantity) print(rounded)

Our code returns: 23. The math.ceil() function has rounded up our quantity to the nearest whole integer not less than the quantity, which in this case is 23.

Similarly, we can use math.ceil() on negative numbers. Let’s use the example of the program we discussed earlier to show how this works. Instead of finding the floor value of our remaining quantity, we want to find the ceiling value. We could do so using this program:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

import math quantity_projection = -25.21 rounded = math.floor(quantity_projection) print(rounded)

Our code returns: -26. Our program has rounded our quantity projection up to the nearest whole number, which in this case was -26.

Python Floor Division and Ceil vs. Round

The Python round() method searches for the nearest number, which could include decimals, while math.floor() and ceil() round up and down to the nearest integer(), respectively.

If you wanted to round a number like 105.2529 to two decimal places, you’d want to use round() instead of floor() or ceil().

If you’re interested in learning more using the round() method, check out our tutorial on Python round.

Conclusion

The math.floor() method allows you round a number down to its nearest whole integer. math.ceil() method allows you to round a number up to its nearest whole integer.

This tutorial discussed using both the math.floor() and math.ceil() functions to round numbers in Python. We walked through an example of each of these methods in a program.

To learn more about coding in Python, read our complete How to Learn Python guide.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

Модуль Math в Python

Модуль Math в Python обеспечивает доступ к математическим функциям, определенным стандартом C. Итак, мы можем выполнять множество сложных математических операций с помощью функций Math. Учебник разработан с использованием некоторых основных функций и примеров математического модуля.

Математические функции – floor(), ceil(), fabs(x)

Математический модуль является частью установки в Python, поэтому мы можем просто импортировать его в нашу программу и использовать.

Функция floor() используется для приведения значения floor к заданному числу. Аналогичным образом функция ceil() используется для получения максимального значения заданного числа. Таким образом, эти две функции используются для округления значения, либо минимального, либо максимального значения.

Функция fabs() используется для получения абсолютного значения заданного числа. Смотрите пример кода ниже.

import math number = -2.34 print('The given number is :', number) print('Floor value is :', math.floor(number)) print('Ceiling value is :', math.ceil(number)) print('Absolute value is :', math.fabs(number))
The given number is : -2.34 Floor value is : -3 Ceiling value is : -2 Absolute value is : 2.34

Функции exp(), expm1() и log()

Функция exp() математического модуля используется для получения e ^ x. Функция expm1() возвращает (e ^ x) -1. Для небольшого значения x прямое вычисление exp (x) -1 может привести к значительной потере точности, в то время как expm1 (x) может выдавать результат с полной точностью.

Функция log() используется для получения значения журнала. Смотрите пример кода.

import math number = 1e-4 # small value of of x print('The given number (x) is :', number) print('e^x (using exp() function) is :', math.exp(number)-1) print('e^x (using expml() function) is :', math.expm1(number)) print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))

И вы получите такой результат:

The given number (x) is : 0.0001 e^x (using exp() function) is : 0.0001000050001667141 e^x (using expml() function) is : 0.00010000500016667084 log(fabs(x), base) is : -3.999999999999999

Математические тригонометрические функции

Все тригонометрические функции доступны в математическом модуле python, поэтому вы можете легко вычислить их, используя функции sin(), cos(), tan(), acos(), asin(), atan() и т.д.

Также вы можете конвертировать углы из градуса в радиан и радиан в градус. Смотрите пример кода.

import math angleInDegree = 45 angleInRadian = math.radians(angleInDegree) print('The given angle is :', angleInRadian) print('sin(x) is :', math.sin(angleInRadian)) print('cos(x) is :', math.cos(angleInRadian)) print('tan(x) is :', math.tan(angleInRadian))

Итак, на выходе вы получите:

Функция math в python

sqrt(x)

Мы можем использовать функцию sqrt(x), чтобы получить квадратный корень из x. Ниже приведен простой пример функции math sqrt.

import math x = 16 y = 10 z = 11.2225 print('sqrt of 16 is ', math.sqrt(x)) print('sqrt of 10 is ', math.sqrt(y)) print('sqrt of 11.2225 is ', math.sqrt(z))

Результатом приведенного выше математического примера sqrt является:

sqrt of 16 is 4.0 sqrt of 10 is 3.1622776601683795 sqrt of 11.2225 is 3.35

Модуль PI

В математическом модуле Python «PI» является константой, которую можно использовать в математических вычислениях, например, в области круга.

import math print('PI value = ', math.pi) radius = 4 print('Area of Circle with Radius 4 =', math.pi * (radius ** 2))

Приведенный выше пример программы на Python выдаст следующий результат.

PI value = 3.141592653589793 Area of Circle with Radius 4 = 50.26548245743669

Источник

Оцените статью