- Lesson 12 — Importing modules and the math module in Python
- Libraries
- math
- math module methods
- ceil() , floor() , and random()
- fabs() and abs()
- sin() , cos() , tan()
- acos() , asin() , atan()
- pow() and sqrt()
- exp() , log() , log2() , log10()
- Division
- The remainder after division
- Модуль Math в Python
- Синтаксис и подключение
- Константы модуля Math
- Список функций
- Теоретико-числовые функции и функции представления
- Степенные и логарифмические функции
Lesson 12 — Importing modules and the math module in Python
In the previous lesson, Tuples, sets, and dictionaries in Python, we learned about multi-dimensional lists in Python. In today’s tutorial, we’re going to learn to use libraries. Mainly, the math library.
Libraries
Libraries (or modules) provides us with useful data types, functions, and tools for making even better programs. They’re made so we don’t have to re-write something someone else has already written for us. If we make our programs using existing modules, the development process will be much more comfortable and quick.
We import libraries using the import command, at the beginning of our source file.
Then, we call module functions as they were in the module’s methods:
We can also choose to only import certain functions:
from module_name import function_name
Then, the function would be globally accessible:
We could even make everything from the module be accessible globally. However, be careful with this approach and use it only if you know exactly what you’re doing:
math
First, let’s introduce you to the Python math module — math . We have to import it in order to use it:
#!/usr/bin/python3 import math
The module provides 2 fundamental constants for us: pi and e . pi , as you all know, is the number Pi ( 3.1415. ), and e is Euler’s number, the base of the natural logarithm ( 2.7182. ). I’m sure you’ll get how to work with them. For completeness’ sake, let’s print these constants to the console:
import math print("Pi: %f" % (math.pi)) print("e: %f" % (math.e))
Console application Pi: 3.141593 e: 2.718282
As you can see, we can call everything from the math module.
math module methods
Now, let’s go over the methods that the math module provides.
ceil() , floor() , and random()
All of these functions are related to rounding. ceil() always rounds upwards and floor() rounds downwards no matter what. If you just need ordinary rounding, use the global round() function which takes a decimal number as a parameter and returns the rounded number as a double data type in the way we learned in school (from 0.5 it rounds upwards, otherwise downwards). The round() function is from the standard set of functions and isn’t dependent on the math module.
We’ll certainly use round() very often. I’ve used the other functions for things such as determining the number of pages in a guestbook. If we had 33 comments and we only printed 10 comments per page, these comments would take up 3.3 pages. The result must be rounded up since we would actually need 4 pages.
import math print(round(3.1)) print(round(3.6)) print(math.ceil(3.1)) print(math.floor(3.6))
Console application 3 4 4 3
fabs() and abs()
The fabs() method takes a decimal ( float ) number as a parameter and returns its absolute value (which is always positive). We also have the global abs() function which works with integers.
import math print(math.fabs(-2.2)) print(math.fabs(2.2)) print(abs(-2)) print(abs(2))
Console application 2.2 2.2 2 2
sin() , cos() , tan()
These classic trigonometric functions all take an angle as a float , which has to be entered in radians (not degrees if your country uses them). To convert degrees to radians we multiply them by (Math.PI / 180) . The return value is also a float .
acos() , asin() , atan()
These are inverse trigonometric (arcus, sometimes cyclometric) functions, which return the original angle according to its trigonometric value. The parameter is a float and the returned angle is in radians (also as a float ). If we wanted the angle in degrees, we’d have to divide the radians by (180 / Math.PI) .
pow() and sqrt()
pow() takes two parameters. The first is the base of the power and the second is the exponent. If we wanted to calculate 2 3 , the code for it would be as follows:
import math print(math.pow(2, 3))
sqrt() is an abbreviation for SQuare RooT, which returns the square root of the number given as a float . Both functions return a float as the result.
import math print(math.sqrt(12))
exp() , log() , log2() , log10()
exp() returns Euler’s number raised to the given exponent. log() returns the natural logarithm of the given number or the logarithm of the base entered as the second parameter. log10() returns the decadic logarithm of the number and log2() returns the binary logarithm.
import math print(math.log(16, 4)) print(math.log10(1000)) print(math.log2(32))
Console application 2.0 3.0 5.0
Hopefully, you noticed that the method list lacks any general root function. We, however, can calculate it using the functions the math module provides.
We know that roots work like this: the 3rd root of 8 = 8^(1/3) . Therefore, we can write the following bit of code:
import math print(math.pow(8, (1/3)))
Division
Programming languages often differ in how they perform the division of numbers. You need to be aware of these issues to avoid being, unpleasantly, surprised afterwards. Let’s write a simple program:
a = 5 / 2 b = 5.0 / 2 c = 5 / 2.0 d = 5.0 / 2.0 e = 5 // 2 f = 5.0 // 2 g = 5 // 2.0 h = 5.0 // 2.0 print(a) print(b) print(c) print(d) print(e) print(f) print(g) print(h)
We divide 5 / 2 several times in the code. Mathematically, it’s 2.5 . Nonetheless, the results will not be the same in all cases. Can you guess what we’ll get in each case? Go ahead, give it a try
The program output will be the following:
Console application 2.5 2.5 2.5 2.5 2 2.0 2.0 2.0
We see the result of division using the / operator is always decimal ( float ). It doesn’t really matter what the data type of the variable we’re assigning the result to is. If we wanted to perform whole-number division, we’d have to use the // operator. As you can see, it returns decimal numbers for decimal inputs, but the value is always a whole number ( .0 ).
The remainder after division
In our applications, we often need the remainder after integer division (i.e. modulo). In our example 5 // 2 , the integer result is 2 and modulo is 1 (what’s left over). Modulo is often used to determine whether a number is even (remainder of division by 2 is 0 ). You would use it, for example, to draw a checkerboard and fill in the fields based on whether they are even or odd, calculate the deviance of your position in a square grid, and so on.
In Python, as in C-like languages in general, modulo is a percent sign, i.e. % :
Well, that’s all I’ve got for today. In the next lesson, Solved tasks for Python lessons 10-12, we’ll learn to declare custom functions and to decompose our programs into multiple logical parts.
In the following exercise, Solved tasks for Python lessons 10-12, we’re gonna practice our knowledge from previous lessons.
Модуль Math в Python
Python библиотека math содержит наиболее применяемые математические функции и константы. Все вычисления происходят на множестве вещественных чисел.
Если вам нужен соответствующий аппарат для комплексного исчисления, модуль math не подойдёт. Используйте вместо него cmath . Там вы найдёте комплексные версии большинства популярных math -функций.
Синтаксис и подключение
Чтобы подключить модуль, необходимо в начале программы прописать следующую инструкцию:
Теперь с помощью точечной нотации можно обращаться к константам и вызывать функции этой библиотеки. Например, так:
Константы модуля Math
math.pi Представление математической константы π = 3.141592…. «Пи» — это отношение длины окружности к её диаметру.
math.e Число Эйлера или просто e . Иррациональное число, которое приблизительно равно 2,71828.
math.tau Число τ — это отношение длины окружности к её радиусу. Т.е
import math > print(math.tau) print(math.tau == 2 * math.pi) > True
math.inf Положительная бесконечность.
Для оперирования отрицательной бесконечно большой величиной, используйте -math.inf
Константа math.inf эквивалента выражению float(«inf») .
math.nan NaN означает — «не число».
Аналогичная запись: float(«nan») .
Список функций
Теоретико-числовые функции и функции представления
math.ceil() Функция округляет аргумент до большего целого числа.
math.comb(n, k) Число сочетаний из n по k . Показывает сколькими способами можно выбрать k объектов из набора, где находится n объектов. Формула:
Решим задачу : На столе лежат шесть рубинов. Сколько существует способов выбрать два из них?
💭 Можете подставить числа в формулу, и самостоятельно проверить правильность решения.
math.copysign() Функция принимает два аргумента. Возвращает первый аргумент, но со знаком второго.
math.fabs() Функция возвращает абсолютное значение аргумента:
math.factorial() Вычисление факториала. Входящее значение должно быть целочисленным и неотрицательным.
math.floor() Антагонист функции ceil() . Округляет число до ближайшего целого, но в меньшую сторону.
math.fmod(a, b) Считает остаток от деления a на b . Является аналогом оператора » % » с точностью до типа возвращаемого значения.
math.frexp(num) Возвращает кортеж из мантиссы и экспоненты аргумента. Формула:
, где M — мантисса, E — экспонента.
print(math.frexp(10)) > (0.625, 4) # проверим print(pow(2, 4) * 0.625) > 10.0
math.fsum() Вычисляет сумму элементов итерируемого объекта. Например, вот так она работает для списка:
summable_list = [1, 2, 3, 4, 5] print(math.fsum(summable_list)) > 15.0
math.gcd(a, b) Возвращает наибольший общий делитель a и b . НОД — это самое большое число, на которое a и b делятся без остатка.
a = 5 b = 15 print(math.gcd(a, b)) > 5
math.isclose(x, y) Функция возвращает True , если значения чисел x и y близки друг к другу, и False в ином случае. Помимо пары чисел принимает ещё два необязательных именованных аргумента:
- rel_tol — максимально допустимая разница между числами в процентах;
- abs_tol — минимально допустимая разница.
math.isfinite() Проверяет, является ли аргумент NaN , False или же бесконечностью. True , если не является, False — в противном случае.
norm = 3 inf = float(‘inf’) print(math.isfinite(norm)) > True print(math.isfinite(inf)) > False
math.isinf() True , если аргумент — положительная/отрицательная бесконечность. False — в любом другом случае.
not_inf = 42 inf = math.inf print(math.isinf(not_inf)) > False print(math.isinf(inf)) > True
math.isnan() Возврат True , если аргумент — не число ( nan ). Иначе — False .
not_nan = 0 nan = math.nan print(math.isnan(not_nan)) > False print(math.isnan(nan)) > True
math.isqrt() Возвращает целочисленный квадратный корень аргумента, округлённый вниз.
math.ldexp(x, i) Функция возвращает значение по формуле:
возвращаемое значение = x * (2 ** i) print(math.ldexp(3, 2)) > 12.0
math.modf() Результат работы modf() — это кортеж из двух значений:
math.perm(n, k) Возвращает число размещений из n по k . Формула:
Задача : Посчитать количество вариантов распределения трёх билетов на концерт Стаса Михайлова для пяти фанатов.
Целых 60 способов! Главное — не запутаться в них, и не пропустить концерт любимого исполнителя!
math.prod() Принимает итерируемый объект. Возвращает произведение элементов.
multiple_list = [2, 3, 4] print(math.prod(multiple_list)) > 24
math.remainder(m, n) Возвращает результат по формуле:
где x — ближайшее целое к выражению m/n число.
print(math.remainder(55, 6)) > 1.0 print(math.remainder(4, 6)) > -2.0
math.trunc() trunc() вернёт вам целую часть переданного в неё аргумента.
Степенные и логарифмические функции
math.exp(x) Возвращает e в степени x . Более точный аналог pow(math.e, x) .
print(math.exp(3)) > 20.085536923187668
math.expm1(x) Вычисляет значение выражения exp(x) — 1 и возвращает результат.
print(math.expm1(3)) > 19.085536923187668 print(math.expm1(3) == (math.exp(3) — 1)) > True
math.log() Функция работает, как с одним, так и с двумя параметрами .
1 аргумент: вернёт значение натурального логарифма (основание e ):
2 аргумента: вернёт значение логарифма по основанию, заданному во втором аргументе:
☝️ Помните, это читается, как простой вопрос: «в какую степень нужно возвести число 4 , чтобы получить 16 «. Ответ, очевидно, 2 . Функция log() с нами согласна.
math.log1p() Это натуральный логарифм от аргумента (1 + x) :
print(math.log(5) == math.log1p(4)) > True
math.log2() Логарифм по основанию 2 . Работает точнее, чем math.log(x, 2) .
math.log10() Логарифм по основанию 10 . Работает точнее, чем math.log(x, 10) .
math.pow(a, b) Функция выполняет возведение числа a в степень b и возвращает затем вещественный результат.