Модуль math предоставляет доступ к математическим функциям и константам. Несмотря на то что числа комплексного типа (complex) являются встроенными, данный модуль их не поддерживает и всегда вызывает исключение при их использовании. Для того что бы использовать математические функции с комплексными числами обратитесь к модулю cmath.
Теория чисел
- math.factorial(x)¶
- Возвращает факториал указанного числа x.
>>> import math
>>>
>>> math.factorial(5)
120
>>>
>>> math.factorial(50)
30414093201713378043612608166064768844377641568960512000000000000
Данная функция всегда возвращает число типа int и поддерживает длинную арифметику, т.е. величина обрабатываемого числа x и возвращаемого результата ограничивается только мощностью вашего компьютера.
Если x не является целым числом (int) или если x является отрицательным, то будет вызвано исключение ValueError.
- math.gcd(x)¶
- Возвращает наибольший общий делитель (НОД) двух целых чисел a и b.
>>> import math
>>>
>>> math.gcd(45, 81)
9
Если оба числа отличны от нуля, то будет возвращено число, которое всегда делит оба эти числа:
>>> math.gcd(3886, 9048)
58
>>>
>>> 3886/58, 9048/58
(67.0, 156.0)
В случае если числа a и b являются взаимно простыми, то будет возвращена (1):
>>> math.gcd(17, 31)
1
Если одно из чисел равно нулю, то будет возвращено, другое, отличное от (0) число:
>>> math.gcd(17, 0)
17
>>>
>>> math.gcd(0, 31)
31
Если оба числа равны (0), то функция вернет (0):
>>> math.gcd(0, 0)
0
Указанные числа должны быть целыми (тип int), но могут быть как положительными, так и отрицательными:
>>> math.gcd(-4, -8)
4
>>>
>>> math.gcd(-4, -8.8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
Доступно в Python с версии 3.5.
- math.frexp(x)¶
- Возвращает кортеж из двух чисел
(m, e)
таких чтоx == m*2**e
.
>>> import math
>>>
>>> math.frexp(123)
(0.9609375, 7)
>>>
>>> 0.9609375*2**7
123.0
Число m принадлежит к типу float и всегда является таким, что 0.5 <= abs(m) < 1
, даже для тех случаев, когда значением x является произвольная степень двойки. Число e всегда целое (int):
>>> math.frexp(0.25)
(0.5, -1)
>>>
>>> math.frexp(64)
(0.5, 7)
Если x равен (0), то будет возвращено (0.0, 0)
.
Чаще всего данная функция используется тогда, когда представление чисел типа float не должно зависеть от архитектуры используемой машины.
- math.ldexp(x, i)¶
- Возвращает
x*2**i
, т.е. является обратной к функцииfrexp()
.
>>> import math
>>>
>>> math.ldexp(3, 4)
48.0
>>>
>>> math.ldexp(0.125, 8)
32.0
- math.fabs(x)¶
- Возвращает абсолютное значение (модуль) числа x. Результат всегда типа float.
>>> import math
>>>
>>> math.fabs(-3)
3.0
>>>
>>> math.fabs(-3.14)
3.14
Данная функция в отличии от встроенной функции abs()
не обрабатывает комплексные числа:
>>> math.fabs(1 + 1j) # Приведет к ошибке
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
>>>
>>>
>>> abs(1 + 1j) # Ошибки не будет
1.4142135623730951
- math.fmod(x)¶
- Возвращает остаток от деления числа x на число y, вычисленный так, как это определено в библиотеке
math
языка C.
>>> import math
>>>
>>> math.fmod(2.23, 0.2)
0.02999999999999986
Данная функция направлена на то, что бы результат был максимально приближен к значению x - n*y
для некоторого целого числа n, что бы этот результат имел тот же знак, что и x, что бы разность x - n*y == abs(y)
.
Для чисел типа float данная функция является предпочтительнее чем команда x%y
, которая в свою очередь является предпочтительной для чисел типа int, так как для некоторых случаев (например, при x = -1e-100
и 1e100
) команда x%y
может вообще выдать неправильный результат.
- math.modf(x)¶
- Возвращает кортеж из двух чисел
(f, w)
где f – дробная, а w – целая часть числа x. Результат всегда имеет тип float.
>>> import math
>>>
>>> math.modf(3)
(0.0, 3.0)
>>>
>>> math.modf(3.14)
(0.14000000000000012, 3.0)
- math.fsum(iterable)¶
- Возвращает точную сумму значений в итерируемом объекте iterable. Возвращаемый результат всегда типа float.
>>> import math
>>>
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>>
>>> math.fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
Может показаться, что эта сумма будет точной всегда, но на самом деле это не так:
>>> math.fsum([0.3, 0.3, 0.3])
0.8999999999999999
Многое зависит от используемой платформы, точнее от сборки компилятора языка C, который используется на данной платформе. Если вам нужны точные арифметические операции с десятичными дробями, то воспользуйтесь модулем decimal.
- math.copysign(x, y)¶
- Возвращает число x со знаком числа y. Возвращаемый результат всегда типа float
>>> import math
>>>
>>> math.copysign(14, -12)
-14.0
>>>
>>> math.copysign(-14, 12)
14.0
Если используемой платформой поддерживаются нули со знаком, то знак второго аргумента так же будет копироваться:
>>> math.copysign(1, -0.0)
-1.0
>>>
>>> math.copysign(0, -1)
-0.0
- math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)¶
- возвращает True если в пределах указанной точности, числа
a
иb
близки настолько, что их можно считать равными.
Допустим у нас есть два числа и мы знаем, что по сути это одно и то же число, а все мизерные различия связаны с ошибками округления и двоичной арифметикой. Мы то понимаем что это как бы одно и то же число, а вот компьютер считает иначе:
>>> import math
>>>
>>> x = 7
>>>
>>> y = (7**0.5)**2
>>> y
7.000000000000001
>>>
>>> x==y
False
Для таких ситуаций, в которых мы готовы считаться с некоторой погрешностью и подходит функция isclose()
:
>>> math.isclose(x, y)
True
Считать числа близкими или нет, определяют два параметра rel_tol
и abs_tol()
.
Параметр rel_tol
(relative tolerances) – это относительный допуск, определяемый как максимально допустимая разница между числами a
и b
относительно большего из них по модулю. По умолчанию, rel_tol = 1e-09
, это гарантирует, что числа a
и b
будут одинаковы, в пределах 9 десятичных цифр. Что бы числа считались равными, если они, допустим, отличаются меньше чем на 0.1%, то достаточно установить rel_tol = 0.001
, но в любом случае данный параметр, должен быть больше нуля:
>>> y
7.000000000000001
>>>
>>> math.isclose(y, 6.999)
False
>>>
>>> math.isclose(y, 6.999, rel_tol = 0.001)
True
Параметр abs_tol
(absolute tolerances) – это минимальный абсолютный допуск, который определяет как сравнивать значения близкие к нулю. Данный параметр должен быть не меньше нуля:
>>> x = 2**(-1000)
>>> x
9.332636185032189e-302
>>>
>>> y = 0.000000000001
>>> y
1e-12
>>>
>>> math.isclose(x, y)
False
>>>
>>> math.isclose(x, y, abs_tol = 10.e-14)
False
>>> math.isclose(x, y, abs_tol = 10.e-13)
True
Данная функция эквивалентна команде abs(a - b) <= max(rel_tol*max(abs(a), abs(b)), abs_tol)
. Значения inf, -inf считаются близкими только сами к себе, а NaN не является близким ни к одному значению, включая само NaN.
Округление чисел
- math.trunc(x)¶
- Отбрасывает дробную часть числа x.
>>> import math
>>>
>>> math.trunc(3.14)
3
>>>
>>> math.trunc(-3.14)
-3
- math.floor(x)¶
- Возвращает (lfloor x rfloor ). Данную функцию так же называют «пол» числа x, т.е. такое число, которое является наибольшим целым числом меньшим или равным x.
>>> import math
>>>
>>> math.floor(3.14)
3
>>> math.floor(-3.14)
-4
- math.ceil(x)¶
- Возвращает (lceil x rceil ). Данную функцию так же называют «потолок» числа x, т.е. такое число, которое является наименьшим целым числом большим или равным x.
>>> import math
>>>
>>> math.ceil(3.14)
4
>>> math.ceil(-3.14)
-3
Степени, логарифмирование, экспоненцирование
- math.pow(x, y)¶
- Возвращает x в степени y.
>>> import math
>>>
>>> math.pow(2, 3)
8.0
>>>
>>> math.pow(3.14, 0.5)
1.772004514666935
В ситуациях pow(x, 0.0)
или pow(0.0, x)
данная функция всегда возвращает (1) даже если x равен NaN, Inf или -Inf. Однако, если x и y являются конечными числами, причем x отрицательное, а y не целое, то будет вызвано исключение ValueError:
>>> math.pow(-2.2, 4.2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
- math.sqrt(x)¶
- Возвращает квадратный корень числа x.
>>> import math
>>>
>>> math.sqrt(4)
2.0
>>>
>>> math.sqrt(3.14)
1.772004514666935
- math.log(x[, base])¶
- Если указано только число x, то возвращается натуральный логарифм данного числа. Если указано число x и основание base, то возвращается логарифм числа по указанному основанию.
>>> import math
>>>
>>> math.log(2.78)
1.0224509277025455
>>>
>>> math.log(1024, 2)
10.0
По сути, команда log(x, base)
равносильна команде log(x)/log(base)
:
>>> math.log(1024)/math.log(2)
10.0
- math.log10(x)¶
- Возвращает десятичный логарифм числа x, вычисление которого происходит немного точнее, чем
log(x, 10)
.
>>> import math
>>>
>>> math.log10(1000)
3.0
>>>
>>> # точное значение десятичного
... # логарифма от 2 равно
... # 0.301029995663981195213738894724493026768189881462108541310
... math.log10(2)
0.3010299956639812
>>> math.log(2, 10)
0.30102999566398114
- math.log2(x)¶
- Возвращает двоичный логарифм числа x, вычисление которого происходит немного точнее, чем
log(x, 2)
.
>>> import math
>>>
>>> math.log2(2048)
11.0
>>>
>>> # точное значение двоичного
... # логарифма от 10 равно
... # 3.321928094887362347870319429489390175864831393024580612054
... math.log2(10)
3.321928094887362
>>> math.log(10, 2)
3.3219280948873626
- math.log1p(x)¶
- Возвращает натуральный логарифм от x увеличенного на (1) (
x + 1
), значение которого расчитывается более точно, особенно для небольших чисел x.
>>> import math
>>>
>>> x = 0.0001
>>>
>>> math.log1p(x)
9.999500033330834e-05
>>>
>>> math.log(x + 1)
9.999500033329732e-05
- math.exp(x)¶
- Возвращает
e**x
.
>>> import math
>>>
>>> math.exp(1)
2.718281828459045
>>>
>>> math.exp(3.14)
23.103866858722185
- math.expm1(x)¶
- Возвращает
e**x - 1
, которое вычисляется значительно точнее, чемmath.exp(x) - 1
, особенно для небольших чисел x.
>>> import math
>>>
>>> math.expm1(0.0000007)
7.000002450000572e-07
>>>
>>> math.exp(0.0000007) - 1
7.000002451018617e-07
>>>
>>> # точное значение 7.00002450005716676670847339183e-6
Тригонометрические функции
- math.sin(x)¶
- Возвращает синус угла x значение которого задано в радианах.
>>> from math import sin, pi
>>>
>>> sin(0), sin(pi/2), sin(pi/3), sin(pi/4)
(0.0, 1.0, 0.8660254037844386, 0.7071067811865475)
- math.cos(x)¶
- Возвращает косинус угла x значение которого задано в радианах.
>>> from math import cos, pi
>>>
>>> cos(0), cos(pi/2), cos(pi/3), cos(pi/4)
(1.0, 6.123233995736766e-17, 0.5000000000000001, 0.7071067811865476)
- math.tan(x)¶
- Возвращает тангенс угла x значение которого задано в радианах.
>>> from math import tan, pi
>>>
>>> tan(0), tan(pi/3), tan(pi/4)
(0.0, 1.7320508075688767, 0.9999999999999999)
При определенных значениях углов тангенс должен быть равен либо (-infty) либо (+infty), скажем (tan (3pi/2) = +infty), a (tan (-pi/2) = -infty), но вместо этого мы получаем либо очень большие либо очень маленькие значения типа float:
>>> tan(-pi/2) # должно быть -Inf, но
-1.633123935319537e+16
>>>
>>> tan(3*pi/2) # должно быть Inf, но
5443746451065123.0
- math.asin(x)¶
- Возвращает арксинус значения x, т.е. такое значение угла y (выраженного в радианах) при котором
sin(y) = x
.
>>> from math import asin, sin, pi
>>>
>>> pi/6
0.5235987755982988
>>>
>>> sin(pi/6)
0.49999999999999994
>>>
>>> asin(0.49999999999999994)
0.5235987755982988
- math.acos(x)¶
- Возвращает арккосинус значения x, т.е. возвращает такое значение угла y (выраженного в радианах) при котором
cos(y) = x
.
>>> from math import acos, cos, pi
>>>
>>> pi/11
0.28559933214452665
>>>
>>> cos(pi/11)
0.9594929736144974
>>>
>>> acos(0.9594929736144974)
0.2855993321445267
- math.atan(x)¶
- Возвращает арктангенс значения x, т.е. возвращает такое значение угла y (выраженного в радианах) при котором
tan(y) = x
.
>>> from math import atan, tan, pi
>>>
>>> pi/7
0.4487989505128276
>>>
>>> tan(pi/7)
0.4815746188075286
>>>
>>> atan(0.4815746188075286)
0.4487989505128276
- math.atan2(y, x)¶
- Возвращает арктангенс значения x/y, т.е. возвращает такое значение угла z (выраженного в радианах) при котором
tan(z) = x
.
>>> from math import atan2, atan, tan, pi
>>>
>>> atan(0.5)
0.4636476090008061
>>> atan2(1, 2)
0.4636476090008061
>>>
>>> tan(0.4636476090008061)
0.49999999999999994
Однако, данная функция, в отличие от функции atan()
, способна вычислить правильный квадрвнт в котором должно находиться значение результата. Это возможно благодаря тому, что функция принимает два аргумента (x, y)
– это координаты точки, которая является концом отрезка начатого в начале координат. Сам по себе, угол между этим отрезком и положительным направлением оси абцисс не несет информации о том где располагается конец этого отрезка, что приводит к одинаковому значению арктангенса, для разных отрезков, но функция atan2()
позволяет избежать этого, что бывает очень важно в целом ряде задач:
>>> atan(-0.5)
-0.4636476090008061
>>>
>>> atan2(-1, 2)
-0.4636476090008061
>>>
>>> atan2(1, -2)
2.677945044588987
- math.hypot(x, y)¶
- Вычисляет значение гипотенузы по заданным значениям катетов x и y. Данная функция равносильна команде
sqrt(x*x + y*y)
.
>>> import math
>>>
>>> math.hypot(3, 4)
5.0
Преобразование меры углов
- math.degrees(x)¶
- Преобразует угол x из радианной меры в градусную.
>>> from math import degrees, pi
>>>
>>> pi/2 # угол в радианах
1.5707963267948966
>>>
>>> degrees(pi/2) # тот же угол, но в градусах
90.0
- math.radians(x)¶
- Преобразует угол x из градусной меры в радианную.
>>> from math import radians, pi
>>>
>>> radians(90)
1.5707963267948966
>>>
>>> pi/2
1.5707963267948966
Гиперболические функции
- math.sinh(x)¶
- Возвращает гиперболический синус угла x заданного в радианах.
>>> import math
>>>
>>> math.sinh(0.4)
0.4107523258028155
- math.cosh(x)¶
- Возвращает гиперболический косинус угла x заданного в радианах.
>>> import math
>>>
>>> math.cosh(0.3)
1.0453385141288605
- math.tanh(x)¶
- Возвращает гиперболический тангенс угла x заданного в радианах.
>>> import math
>>>
>>> math.tanh(0.2)
0.197375320224904
- math.asinh(x)¶
- Возвращает гиперболический арксинус значения x, т.е. возвращает такое значение угла y (заданного в радианах) при котором
sinh(y) = x
.
>>> import math
>>>
>>> math.asinh(0.4107523258028155)
0.4
- math.acosh(x)¶
- Возвращает гиперболический арккосинус значения x, т.е. возвращает такое значение угла y (заданного в радианах) при котором
cosh(y) = x
.
>>> import math
>>>
>>> math.acosh(1.0453385141288605)
0.3
- math.atanh(x)¶
- Возвращает гиперболический арктангенс значения x, т.е. возвращает такое значение угла y (заданного в радианах) при котором
tanh(y) = x
.
>>> import math
>>>
>>> math.atanh(0.197375320224904)
0.2
Константы и специальные значения
- math.pi¶
- Возвращает значение математической константы (pi) с точностью, которая зависит от конкретной платформы.
>>> import math
>>>
>>> math.pi
3.141592653589793
- math.e¶
- Возвращает значение математической константы (e) с точностью, которая зависит от конкретной платформы.
>>> import math
>>>
>>> math.e
2.718281828459045
- math.inf¶
- Возвращает положительную бесконечность, значение которое является типом float и может присутствовать в математических выражениях.
>>> import math
>>>
>>> math.inf
inf
>>>
>>> math.inf**0.5
inf
Данное значение можно получить с помощью команды float('inf')
. А что бы получить отрицательную бесконечность достаточно добавить перед командой унарный оператор -
:
>>> float('inf')
inf
>>> -math.inf
-inf
Доступно в Python начиная с версии 3.5.
- math.nan¶
- Возвращает значение «не число» которое является типом float и может присутствовать в математических выражениях. Равносильно команде
float('nan')
.
>>> import math
>>>
>>> math.nan
nan
>>>
>>> float('nan')
nan
Доступно в Python начиная с версии 3.5.
- math.isinf(x)¶
- Возвращает True в случаях, когда x является отрицательной или положительной бесконечностью, иначе возвращает False.
>>> import math
>>>
>>> math.isinf(float('inf'))
True
>>> math.isinf(-math.inf)
True
>>>
>>> math.isinf(3.14)
False
- math.isnan(x)¶
- Возвращает True если x является nan, иначе возвращает False.
>>> import math
>>>
>>> math.isnan(math.nan)
True
>>> math.isnan(float('nan'))
True
>>>
>>> math.isnan(3.14)
False
- math.isfinite(x)¶
- Возвращает False если x является либо nan, либо inf или -inf, во всех остальных случаях возвращается True.
>>> from math import isfinite
>>>
>>> isfinite(float('inf'))
False
>>> isfinite(float('nan'))
False
>>>
>>> isfinite(0)
True
Специальные функции
- math.erf(x)¶
- Возвращает значение функции ошибок от указанного значения аргумента x.
>>> import math
>>>
>>> math.erf(0)
0.0
>>> math.erf(0.476936276)
0.4999999998162208
Доступно в Python начиная с версии 3.2.
- math.erfc(x)¶
- Возвращает значение дополнительной функции ошибок от указанного значения аргумента x. Эквивалентна команде
1 - erf(x)
.
>>> import math
>>>
>>> math.erfc(2)
0.0046777349810472645
>>>
>>> 1 - math.erf(2)
0.004677734981047288
Доступно в Python начиная с версии 3.2.
- math.gamma(x)¶
- Возвращает значение гамма функции от указанного аргумента x.
>>> import math
>>>
>>> for x in range(1, 20):
... print('gamma(', x/2, ') = ', math.gamma(x/2))
...
gamma( 0.5 ) = 1.7724538509055159
gamma( 1.0 ) = 1.0
gamma( 1.5 ) = 0.8862269254527578
gamma( 2.0 ) = 1.0
gamma( 2.5 ) = 1.329340388179137
gamma( 3.0 ) = 2.0
gamma( 3.5 ) = 3.323350970447842
gamma( 4.0 ) = 6.0
gamma( 4.5 ) = 11.631728396567448
gamma( 5.0 ) = 24.0
gamma( 5.5 ) = 52.342777784553526
gamma( 6.0 ) = 120.0
gamma( 6.5 ) = 287.88527781504433
gamma( 7.0 ) = 720.0
gamma( 7.5 ) = 1871.2543057977882
gamma( 8.0 ) = 5040.0
gamma( 8.5 ) = 14034.407293483413
gamma( 9.0 ) = 40320.0
gamma( 9.5 ) = 119292.46199460902
Данная функция обобщает понятие факториала, на действительные числа (и на комплексные, но в данном случае используются только действительные числа). Если (x = 0) то это вызовет исключение ValueError.
Доступно в Python начиная с версии 3.2.
- math.lgamma(x)¶
- Возвращает значение натурального логарифма от модуля гамма функции при заданном значении аргумента x.
Данная функция эквивалентна команде math.log(abs(math.gamma(x)))
.
>>> import math
>>>
>>> math.lgamma(4)
1.791759469228055
>>>
>>> math.log(abs(math.gamma(4)))
1.791759469228055
Доступно в Python начиная с версии 3.2.
Этот модуль предоставляет доступ к математическим функциям, определенным
стандартом C.
Данные функции нельзя использовать с комплексными числами; используйте
одноименные функции из модуля cmath
, если вам требуется поддержка
комплексных чисел. Различие между функциями, поддерживающими комплексные числа,
и функциями, не поддерживающими их, заключается в том, что большинство
пользователей не хотят изучать столько математики, сколько требуется для
понимания комплексных чисел. Получение исключения вместо комплексного результата
позволяет раньше обнаруживать неожиданное комплексное число, используемое в
качестве параметра, так что программист может определить, как и почему оно было
сгенерировано в первую очередь.
За исключением случаев, когда явно указано иное, все возвращаемые
значения являются числами с плавающей запятой.
Теоретико-числовые и репрезентативные функции¶
-
math.
ceil
(x)¶ -
Возвращает округление x в большую сторону, наименьшее целое число,
большее или равное x. Если x не дробное, делегируетсяx.__ceil__()
,
которая должна возвратитьIntegral
значение.
-
math.
comb
(n, k)¶ -
Возвращает количество способов выбора k позиций из n позиций
без повторения и без порядка.Вычисляется как
n! / (k! * (n - k)!)
приk <= n
и равно нулю приk > n
.Также называется биномиальным коэффициентом, потому что он эквивалентен
коэффициенту k-го члена в полиномиальном расширении выражения(1 + x) ** n
.Поднимает
TypeError
, если любой из аргументов не является целыми числами.
ПоднимаетValueError
, если любой из аргументов отрицательный.Добавлено в версии 3.8.
-
math.
copysign
(x, y)¶ -
Возвращает модуль (абсолютное значение) дробного x, но с
знаком y. На платформах, поддерживающих знаковые нули,copysign(1.0, -0.0)
возвращает -1.0.
-
math.
fabs
(x)¶ -
Возвращает абсолютное значение x.
-
math.
factorial
(x)¶ -
Возвращает x факториал как целое число. Поднимает
ValueError
, если
x не является целым или отрицательным.
-
math.
floor
(x)¶ -
Возвращает округление в меньшую сторону x, наибольшее целое число, меньшее
или равно x. Если x не дробное, делегируетсяx.__floor__()
, которая должна
возвращать значениеIntegral
.
-
math.
fmod
(x, y)¶ -
Возвращает
fmod(x, y)
, как определено библиотекой платформы C. Обратите
внимание, что выражение Pythonx % y
может не возвращать тот же результат.
Цель стандарта C состоит в том, чтобыfmod(x, y)
было точно (математически;
с бесконечной точностью) равнымx - n*y
для некоторого целого числа n,
чтобы результат имел тот же знак, что и x, и величину меньшеabs(y)
.
Pythonx % y
вместо этого возвращает результат со знаком y и может не
быть точно вычислимым для аргументов с плавающей запятой. Например,
fmod(-1e-100, 1e100)
— это-1e-100
, но результат Python-1e-100 %
—
1e1001e100-1e-100
, который не может быть представлен точно как число
с плавающей запятой, и округляется до удивительного1e100
. По этой причине
функцияfmod()
обычно предпочтительнее при работе с числами с плавающей
запятой, а функция Pythonx % y
предпочтительнее при работе с целыми
числами.
-
math.
frexp
(x)¶ -
Возвращает мантиссу и показатель степени x в виде пары
(m, e)
. m — это
число с плавающей запятой, а e — целое число, такое какx == m * 2**e
в
точности. Если x равно нулю, возвращает(0.0, 0)
, в противном случае —
0.5 <= abs(m) < 1
. Используется для «разборки» внутреннего
представления дробного числа переносимым способом.
-
math.
fsum
(iterable)¶ -
Возвращает точную сумму значения с плавающей запятой в iterable. Позволяет
избежать потери точности путём отслеживания нескольких промежуточных частичных
сумм:>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
Точность алгоритма зависит от арифметических гарантий IEEE-754 и типичного
случая, когда режим округления является половинным. В некоторых сборках,
отличных от Windows, базовая библиотека C использует сложение с расширенной
точностью и может иногда дважды округлять промежуточную сумму, вызывая её
отключение в её младшем разряде.Для дальнейшего обсуждения и двух альтернативных подходов см.
Рецепты ASPN для точного суммирования с плавающей запятой.
-
math.
gcd
(a, b)¶ -
Возвращает наибольший общий делитель целых чисел a и b. Если a или b
отличны от нуля, то значениеgcd(a, b)
является наибольшим положительным
целым числом, которое делит как a, так и b.gcd(0, 0)
возвращает0
.Добавлено в версии 3.5.
-
math.
isclose
(a, b, *, rel_tol=1e-09, abs_tol=0.0)¶ -
Возвращает
True
если значения a и b близки друг к
другу иFalse
иначе.Считают ли близкими два значения, определяется в соответствии с заданными
абсолютными и относительными допусками.rel_tol — относительный допуск. Максимально допустимая разница между
a и b относительно большего абсолютного значения a или b. Например,
чтобы установить допуск 5%, передайтеrel_tol=0.05
. Допуск по умолчанию —
1e-09
, который гарантирует, что два значения совпадают с точностью до 9
десятичных цифр. rel_tol должен быть больше нуля.abs_tol является минимальным абсолютным допуском – полезно для сравнения,
близкого к нулю. abs_tol должно быть не менее нуля.Если ошибок не возникает, результат будет следующим:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
.Специальные значения IEEE 754
NaN
,inf
и-inf
будут
обрабатываться в соответствии с правилами IEEE. В частности,NaN
не
считается близким к каким-либо другим значениям, включаяNaN
.
inf
и-inf
считаются только близкими себе.Добавлено в версии 3.5.
См.также
PEP 485 – функция для проверки приближённого равенства
-
math.
isfinite
(x)¶ -
Возвращает
True
если x не является ни бесконечностью, ни NaN,
иFalse
иначе. (Обратите внимание, что0.0
будет считается
конечным.)Добавлено в версии 3.2.
-
math.
isinf
(x)¶ -
Возвращает
True
если x — положительная или отрицательная
бесконечность, иFalse
иначе.
-
math.
isnan
(x)¶ -
Возвращает
True
если x — NaN (не число), иFalse
иначе.
-
math.
isqrt
(n)¶ -
Возвращает целочисленный квадратный корень из неотрицательного целого числа n.
Это нижний предел точного квадратного корня из n или, что эквивалентно,
наибольшего целого числа a, такого что a² ≤ n.Для некоторых приложений может быть более удобным иметь наименьшее целое число
a, такое, что n ≤ a², или, другими словами, потолок
точного квадратного корня из n. Для положительного n это можно вычислить с
помощьюa = 1 + isqrt(n - 1)
.Добавлено в версии 3.8.
-
math.
ldexp
(x, i)¶ -
Возвращает
x * (2**i)
. Это, по существу, обратная функцияfrexp()
.
-
math.
modf
(x)¶ -
Возвращает дробную и целую части x. Оба результата имеют знак x и
являются числами с плавающей запятой.
-
math.
perm
(n, k=None)¶ -
Возвращает количество способов выбрать k элементов из n элементов
без повторения и с указанием порядка.Вычисляется как
n! / (n - k)!
приk <= n
и равно нулю приk > n
.Если k не указан или имеет значение None, то k по умолчанию имеет значение
n, и функция возвращаетn!
.Поднимает
TypeError
, если любой из аргументов не является целыми числами.
ПоднимаетValueError
, если любой из аргументов отрицательный.Добавлено в версии 3.8.
-
math.
prod
(iterable, *, start=1)¶ -
Вычисляет произведение всех элементов в входном iterable. start
значение по умолчанию для умножения —1
.Когда iterable объект пуст, возвращает начальное значение. Эта функция
предназначена специально для использования с числовыми значениями и может
отклонять нечисловые типы.Добавлено в версии 3.8.
-
math.
remainder
(x, y)¶ -
Возвращает остаток x в стиле IEEE 754 по отношению к y. Для конечного x и
конечного ненулевого y это разницаx - n*y
, гдеn
— ближайшее целое
число к точному значению частногоx / y
. Еслиx / y
находится ровно
посередине между двумя последовательными целыми числами, дляn
используется
приравненное ближайшее целое число. Таким образом, остатокr = remainder(x, y)
всегда удовлетворяетabs(r) <= 0.5 * abs(y)
.Особые случаи соответствуют IEEE 754: в частности,
remainder(x, math.inf)
— это x для любого конечного x, аremainder(x, 0)
и
remainder(math.inf, x)
повышаютValueError
для любого не-NaN x.
Если результат операции с остатком равен нулю, этот ноль будет иметь тот же
знак, что и x.На платформах, использующих двоичную плавающую точку IEEE 754, результат этой
операции всегда точно представим: ошибка округления не вводится.Добавлено в версии 3.7.
-
math.
trunc
(x)¶ -
Возвращает значение
Real
x, усеченное до
Integral
(обычно целое число). Делегаты на
x.__trunc__()
.
Обратите внимание, что у frexp()
и modf()
другой шаблон
вызова/возврата, чем их эквиваленты в C: они принимают один аргумент и
возвращают пару значений, а не возвращают второе возвращаемое значение через
«выходной параметр» (в Python такого нет).
Обратите внимание, что для функций ceil()
, floor()
и modf()
все числа с плавающей запятой достаточно большой величины являются точными
целыми числами. Дробные Python обычно несут не более 53 бит точности (такая
же, как двойной тип платформы C), и в этом случае любое число с плавающей
запятой x с abs(x) >= 2**52
обязательно не содержит дробных битов.
Степенные и логарифмические функции¶
-
math.
exp
(x)¶ -
Возвращает e в степени x, где e = 2,718281… основание натурального
логарифма. Обычно эта функция более точна, чемmath.e ** x
илиpow(math.e, x)
.
-
math.
expm1
(x)¶ -
Возвращает e в степени x, минус 1. Здесь e — основание
натурального логарифма. Для небольших дробных чисел
x вычитание вexp(x) - 1
может привести к
значительной потере точности; функция
expm1()
предоставляет способ вычисления этой величины до полной точности:>>> from math import exp, expm1 >>> exp(1e-5) - 1 # дает результат с точностью до 11 мест 1.0000050000069649e-05 >>> expm1(1e-5) # результат с точностью до полной точности 1.0000050000166668e-05
Добавлено в версии 3.2.
-
math.
log
(x[, base])¶ -
С одним аргументом, возвращает натуральный логарифм x (для основания
e).С двумя аргументами, возвращает логарифм x к данному base,
вычисленный какlog(x)/log(base)
.
-
math.
log1p
(x)¶ -
Возвращает натуральный логарифм 1+x (основание e). Результат рассчитывается
с точностью для x, близкого к нулю.
-
math.
log2
(x)¶ -
Возвращает логарифм с основанием 2 x. Обычно это более точно, чем
log(x, 2)
.Добавлено в версии 3.3.
См.также
int.bit_length()
возвращает количество битов, необходимых для
представления целого числа в двоичном формате, исключая знак и ведущие нули.
-
math.
log10
(x)¶ -
Возвращает десятичный логарифм x. Обычно более точно, чем
log(x, 10)
.
-
math.
pow
(x, y)¶ -
Возвращает
x
возведеный в степеньy
. Исключительные случаи, насколько это
возможно, соответствуют Приложению F стандарта C99. В частности,pow(1.0,
и
x)pow(x, 0.0)
всегда возвращают1.0
, даже еслиx
— это ноль
или NaN. Если иx
, иy
конечны,x
отрицательно, аy
не является
целым числом, тогдаpow(x, y)
не определено и поднимает
ValueError
.В отличие от встроенного оператора
**
,math.pow()
преобразует оба
своих аргумента в типfloat
. Используйте**
или встроенную функцию
pow()
для вычисления точных целочисленных степеней.
-
math.
sqrt
(x)¶ -
Возвращает квадратный корень x.
Тригонометрические функции¶
-
math.
acos
(x)¶ -
Возвращает дуговой косинус x в радианах.
-
math.
asin
(x)¶ -
Возвращает дуговой синус x в радианах.
-
math.
atan
(x)¶ -
Возвращает арктангенс x в радианах.
-
math.
atan2
(y, x)¶ -
Возвращает
atan(y / x)
в радианах. Результат находится между-pi
и
pi
. Вектор в плоскости от начала координат до точки(x, y)
составляет
этот угол с положительной осью X. Сутьatan2()
в том, что ему известны
знаки обоих входов, поэтому он может вычислить правильный квадрант для угла.
Например,atan(1)
иatan2(1, 1)
оба являютсяpi/4
, ноatan2(-1,
— это
-1)-3*pi/4
.
-
math.
cos
(x)¶ -
Возвращает косинус x в радианах.
-
math.
dist
(p, q)¶ -
Возвращает Евклидово расстояние между двумя точками p и q,
каждая из которых задана как последовательность (или итерируемый объект) координат.
Две точки должны иметь одинаковый размер.Примерно эквивалентно:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
Добавлено в версии 3.8.
-
math.
hypot
(*coordinates)¶ -
Возвращает Евклидову норму
sqrt(sum(x**2 for x in coordinates))
. Это длина
вектора от начала координат до точки, заданной координатами.Для двумерной точки
(x, y)
это эквивалентно вычислению гипотенузы
прямоугольного треугольника с использованием теоремы Пифагораsqrt(x*x +
.
y*y)Изменено в версии 3.8: Добавлена поддержка n-мерных точек. Ранее поддерживался только двумерный.
-
math.
sin
(x)¶ -
Возвращает синус x радиан.
-
math.
tan
(x)¶ -
Возвращает тангенс x радиан.
Угловое преобразование¶
-
math.
degrees
(x)¶ -
Преобразование угла x из радиан в градусы.
-
math.
radians
(x)¶ -
Преобразование угла x из градусов в радианы.
Гиперболические функции¶
Гиперболические функции — являются аналогами тригонометрических функций, которые основаны на гиперболах
вместо окружностей.
-
math.
acosh
(x)¶ -
Возвращает обратный гиперболический косинус x.
-
math.
asinh
(x)¶ -
Возвращает обратный гиперболический синус x.
-
math.
atanh
(x)¶ -
Возвращает обратный гиперболический тангенс x.
-
math.
cosh
(x)¶ -
Возвращает гиперболический косинус x.
-
math.
sinh
(x)¶ -
Возвращает гиперболический синус x.
-
math.
tanh
(x)¶ -
Возвращает гиперболический тангенс x.
Специальные функции¶
-
math.
erf
(x)¶ -
Возвращает функцию ошибки для x.
Функция
erf()
может использоваться, чтобы вычислить традиционные
статистические функции, такие как
кумулятивное стандартное нормальное распределение:def phi(x): 'Накопительная функция распределения для стандартного нормального распределения' return (1.0 + erf(x / sqrt(2.0))) / 2.0
Добавлено в версии 3.2.
-
math.
erfc
(x)¶ -
Возвращает дополнительную функцию ошибок в x. Дополнительная функция ошибки определяется как
1.0 -
. Она используется для больших значений x, где вычитание из единицы
erf(x)
приведёт к потере значимости .Добавлено в версии 3.2.
-
math.
gamma
(x)¶ -
Возвращает Гамма функцию для x.
Добавлено в версии 3.2.
-
math.
lgamma
(x)¶ -
Возвращает натуральный логарифм абсолютного значение гамма-функции для
x.Добавлено в версии 3.2.
Константы¶
-
math.
pi
¶ -
Математическая константа π = 3,141592…, к доступной точности.
-
math.
e
¶ -
Математическая константа e = 2,718281…, к доступной точности.
-
math.
tau
¶ -
Математическая константа τ = 6,283185 …, с доступной точностью. Тау — это
постоянная окружности, равная 2π, отношению длины окружности к её радиусу.
Чтобы узнать больше о Тау, посмотрите видео Ви Харт Пи (всё ещё) ошибается и начните праздновать День тау, съев в два раза больше пирога!Добавлено в версии 3.6.
-
math.
inf
¶ -
Положительная бесконечность с плавающей запятой. (Для отрицательной
бесконечности используйте-math.inf
.) Эквивалентно выходуfloat('inf')
.Добавлено в версии 3.5.
-
math.
nan
¶ -
Значение с плавающей запятой «не число» (NaN). Эквивалентно выходу
float('nan')
.Добавлено в версии 3.5.
Детали реализации CPython: Модуль math
состоит в основном из тонких обёрток функций математической
библиотеки C. Поведение в исключительных случаях соответствует Приложению F
стандарта C99, где это необходимо. Текущая реализация будет вызывать
ValueError
для недопустимых операций, таких как sqrt(-1.0)
или
log(0.0)
(где приложение F C99 рекомендует сигнализировать о недопустимой
операции или делении на ноль), и OverflowError
для результатов, которые
переполняются (например, exp(1000.0)
). NaN не будет возвращено ни одной из
вышеперечисленных функций, если только один или несколько входных аргументов не
были NaN; в этом случае большинство функций вернут NaN, но (опять же, в
соответствии с Приложением F C99) есть некоторые исключения из этого правила,
например pow(float('nan'), 0.0)
или hypot(float('nan'), float('inf'))
.
Обратите внимание, что Python не пытается отличить сигнальные NaN от тихих NaN,
а поведение при передаче сигналов NaN остается неопределённым. Типичное
поведение — рассматривать все NaN, как если бы они были тихими.
См.также
- Модуль
cmath
- Комплексные числовые версии многих из этих функций.
1. Целочисленная арифметика
Для целых чисел определены операции
+
, -
, *
и **
. Операция
деления /
для целых чисел возвращает вещественное число (значение типа float
).
Также функция возведения в степень возвращает значение типа float
,
если показатель степени — отрицательное число.
Но есть и специальная операция целочисленного деления, выполняющегося с отбрасыванием
дробной части, которая обозначается //
(она соответствует операции div
в Паскале).
Она возвращает целое число: целую часть частного. Другая близкая ей операция − это операция взятия остатка от деления,
обозначаемая %
(она соответствует операции mod
в Паскале).
Например:
print(17 / 3) # выведет 5.66666666667 print(17 // 3) # выведет 5 print(17 % 3) # выведет 2
2. Действительные числа
В этом разделе речь пойдет о действительных числах, имеющих тип float
.
Обратите внимание, что если вы хотите считать с клавиатуры действительное
число, то результат, возращаемый функцией input()
необходимо
преобразовывать к типу float
:
x = float(input()) print(x)
Действительные (вещественные) числа представляются в виде чисел с десятичной точкой (а не запятой, как принято
при записи десятичных дробей в русских текстах). Для записи очень больших или очень маленьких
по модулю чисел используется так называемая запись «с плавающей точкой»
(также называемая «научная» запись). В этом случае число представляется в виде
некоторой десятичной дроби, называемой мантиссой, умноженной на целочисленную степень десяти
(порядок). Например, расстояние от Земли
до Солнца равно 1.496·1011, а масса молекулы воды 2.99·10-23.
Числа с плавающей точкой в программах на языке Питон, а также при вводе и выводе записываются так:
сначала пишется мантисса, затем пишется буква e
, затем пишется порядок. Пробелы внутри этой
записи не ставятся. Например, указанные выше константы можно записать в виде
1.496e11
и 2.99e-23
. Перед самим числом также может стоять знак минус.
Напомним, что результатом операции деления /
всегда является действительное число (float
),
в то время как результатом операции //
является целое число (int
).
Преобразование действительных чисел к целому производится с округлением
в сторону нуля, то есть int(1.7) == 1
, int(-1.7) == -1
.
3. Библиотека math
Для проведения вычислений с действительными числами язык Питон содержит много
дополнительных функций, собранных в библиотеку (модуль), которая называется math
.
Для использования этих функций в начале программы необходимо подключить математическую
библиотеку, что делается командой
import math
Например, пусть мы хотим округлять вещественные числа до ближайшего целого числа вверх.
Соответствующая функция ceil
от одного аргумента вызывается, например, так: math.ceil(x)
(то есть явно указывается, что из модуля math
используется функция ceil
).
Вместо числа x
может быть любое число, переменная или выражение.
Функция возращает значение, которое можно вывести на экран, присвоить
другой переменной или использовать в выражении:
import math x = math.ceil(4.2) y = math.ceil(4.8) print(x) print(y)
Другой способ использовать функции из библиотеки math
, при котором не нужно будет
при каждом использовании функции из модуля math
указывать название
этого модуля, выглядит так:
from math import ceil x = 7 / 2 y = ceil(x) print(y)
или так:
from math import * x = 7 / 2 y = ceil(x) print(y)
Ниже приведен список основных функций модуля math
. Более подробное описание
этих функций можно найти на сайте с документацией языка Питон.
Некоторые из перечисленных функций (int
, round
, abs
)
являются стандартными и не требуют подключения модуля math
для использования.
Функция | Описание |
---|---|
Округление | |
int(x) | Округляет число в сторону нуля. Это стандартная функция, для ее использования не нужно подключать модуль math . |
round(x) | Округляет число до ближайшего целого. Если дробная часть числа равна 0.5, то число округляется до ближайшего четного числа. |
round(x, n) | Округляет число x до n знаков после точки. Это стандартная функция, для ее использования не нужно подключатьмодуль math . |
floor(x) | Округляет число вниз («пол»), при этом floor(1.5) == 1 , floor(-1.5) == -2 |
ceil(x) | Округляет число вверх («потолок»), при этом ceil(1.5) == 2 , ceil(-1.5) == -1 |
abs(x) | Модуль (абсолютная величина). Это — стандартная функция. |
Корни, логарифмы | |
sqrt(x) | Квадратный корень. Использование: sqrt(x) |
log(x) | Натуральный логарифм. При вызове в виде log(x, b) возвращает логарифм по основанию b . |
e | Основание натуральных логарифмов e = 2,71828… |
Тригонометрия | sin(x) | Синус угла, задаваемого в радианах |
cos(x) | Косинус угла, задаваемого в радианах |
tan(x) | Тангенс угла, задаваемого в радианах |
asin(x) | Арксинус, возвращает значение в радианах |
acos(x) | Арккосинус, возвращает значение в радианах |
atan(x) | Арктангенс, возвращает значение в радианах |
atan2(y, x) | Полярный угол (в радианах) точки с координатами (x, y). |
degrees(x) | Преобразует угол, заданный в радианах, в градусы. |
radians(x) | Преобразует угол, заданный в градусах, в радианы. |
pi | Константа π = 3.1415… |
Ссылки на задачи доступны в меню слева. Эталонные решения теперь доступны на странице самой задачи.
Telegram
Хорошего дня! Сегодня мы научимся умножать, делить, вычитать… В каком смысле ты это уже умеешь?! А ты в этом уверен? В любом случае, повторение — это мать учения, так что устраивайся по-удобнее, мы начинаем.
Арифметические операции в python
Вы считаете, что арифметические операции — это просто? Пересчитайте. На самом деле, всё не так страшно, но расслабляться не стоит.
Начнём со всем знакомой четверки:
print(10 + 10)
# 10
print(10 - 5)
# 5
print(11 * 7)
# 77
print(10 / 2)
# 5.0
Никаких неожиданностей, правда? Не совсем, посмотрите внимательно на операцию деления. Заметили? Мы разделили целое число на его делитель, но несмотря на это, результат имеет тип float
. Взглянем на операцию деления чуть более пристально:
print(10 / 2)
# 5.0
print(100 / 3)
# 33.333333333333336
print(21 / 4)
# 5.25
print(23 / 7)
# 3.2857142857142856
Обратите внимание на деление 100 / 3
. Выполнив эту операцию, мы получили очень интересный результат 33.333333333333336
. На конце 6
?! Вспомним перевод числа в двоичную систему счисления. То есть мы можем представить любое число в виде ноликов и единичек, например:
37 = 2^5 + 2^2 + 2^0 = 100101
.
А как обстоит дело с дробями? Точно также:
0.75 = 0.5 + 0.25 = 1/2 + 1/4 = 0.11
Возникает вопрос, как перевести в двоичную систему такие дроби: 1/3
1/3 = 1/4 + 1/8 + 1/16 + 1/32 + ...
Это может продолжаться бесконечно долго. Поэтому python
прерывает выполнение таких вычислений и часто выдает такие приколы:
print(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1)
# 0.7999999999999999
print(0.1 + 0.2)
# 0.30000000000000004
print(7 / 3)
# 2.3333333333333335
Еще немного математики. Математика в каждый дом!
# Возведение в степень
print(10 ** 2)
# 100
print(2 ** 4)
# 16
print(3 ** 0.5)
# 1.7320508075688772
print(3 ** -2)
# 0.1111111111111111
# Остаток от деления
print(11 % 4)
# 3
print(101 % 7)
# 3
print(34 % 5)
# 4
# Деление нацело
print(20 // 4)
# 5
print(129 // 11)
# 11
print(100 // 61)
# 1
Операции сравнения в python
Операции сравнения в отличие от арифметические имеют всего два результата: True
и False
. Чаще всего такие операции используются в условии циклов, условных оператов, а также в некоторых функциях, например, filter
.
# Операция равенства: True, если X равен Y
print(10 == 10)
# True
print(666 == 661)
# False
# Операция неравенства: True, если X не равен Y
print(666 != 661)
# True
print(666 != 666)
# False
# Операция больше: True, если X больше Y
print(120 > 2)
# True
print(1000 > 1999)
# False
# Операция меньше: True, если X меньше Y
print(121 120)
# False
print(0 1)
# True
# Операция меньше или равно: True, если X меньше или равен Y
print(6 6)
# True
print(5 2)
# False
# Операция больше или равно: True, если X больше или равен Y
print(1000 >= 10000)
# False
print(9999 >= 9999)
# False
Логические операции в python
Логические операции, как и операции сравнения, имеют всего два возможных результата: True
и False
. Используются для объединения операций сравнения в условиях циклов, условных оператов, а также в некоторых функциях, например, filter
.
# Оператор "and" или конъюнкция.
# True, если и выражение X, и выражение Y равны True
print(10 == 10 and 10 > 2)
# True
print(666 == 661 and 9 > 0)
# False
# Оператор "or" или дизъюнкция.
# True, если или выражение X, или выражение Y равны True
print(666 == 661 or 9 > 0)
# True
print(666 == 661 or 9 0)
# False
# Оператор "not" или инверсия меняет значение на противоположное.
# True, если выражение X равно False
print(not 120 > 2)
# False
print(not 1000 999)
# True
print(not (121 121 and 10 == 2))
# True
Округление чисел в python
Всё дело в округлении! В python
есть несколько замечательных функций, которые округляют число до указанного знака. Одной из таких функций является round
:
pi = 3.14159265358979323846264338327
print(round(pi, 1))
# 3.1
print(round(pi, 2))
# 3.14
print(round(pi, 3))
# 3.12
print(round(pi, 4))
# 3.1416
print(round(pi, 10))
# 3.1415926536
print(round(pi, 15))
# 3.141592653589793
Рассмотрим любопытный пример:
print(round(2.5))
# 2
print(round(3.5))
# 4
Если на вашем лице застыл немой вопрос: «почему?», то я вас понимаю. В школе нас учили, что дроби 1.1, 1.2, 1.3, 1.4
округляются до единицы, а 1.5, ..., 1.9
до двойки. Но python
думает по-другому. Есть два типа округления: арифметическое и банковское. Именно арифметическому округлению вас учили в школе. Python
использует как раз-таки банковское округление, его еще называют округлением до ближайшего четного. Приведу еще несколько примеров:
print(round(10.51213))
# 11
print(round(23.5))
# 24
print(round(22.5))
# 22
Модуль math
Модуль math представляет собой набор математических формул. Рассмотрим несколько примеров:
import math
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign',
'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot',
'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log',
'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder',
'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
import math
# Синус 3.14 радиан
print(math.sin(3.14))
# 0.0015926529164868282
# Косинус 1.1 радиан
print(math.cos(1.1))
# 0.4535961214255773
# Возведение экспоненты в 3 степень
print(math.exp(3))
# 20.085536923187668
# Натуральный логарифм 61
print(math.log(61))
# 4.110873864173311
# Факториал четырех
print(math.factorial(4))
# 24
# Извлечение квадратного корня
print(math.sqrt(9))
# 3.0
# Алгоритм Евклида для чисел 20 и 19
print(math.gcd(20, 19))
# 1
# Вычисление гипотенузы треугольника с катетами 3 и 4
print(math.hypot(3,4))
# 5.0
# Перевод радиан в градусы
print(math.degrees(1.572))
# 90.06896539456541
# Факториал четырех
print(math.fmod(20, 3))
# 24
И это далеко не всё! Остальные функции я предлагаю вам протестировать самостоятельно : )
This module provides access to the mathematical functions defined by the C
standard.
These functions cannot be used with complex numbers; use the functions of the
same name from the cmath
module if you require support for complex
numbers. The distinction between functions which support complex numbers and
those which don’t is made since most users do not want to learn quite as much
mathematics as required to understand complex numbers. Receiving an exception
instead of a complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how and why it
was generated in the first place.
The following functions are provided by this module. Except when explicitly
noted otherwise, all return values are floats.
Number-theoretic and representation functions¶
-
math.
ceil
(x)¶ -
Return the ceiling of x, the smallest integer greater than or equal to x.
If x is not a float, delegates tox.__ceil__()
, which should return an
Integral
value.
-
math.
comb
(n, k)¶ -
Return the number of ways to choose k items from n items without repetition
and without order.Evaluates to
n! / (k! * (n - k)!)
whenk <= n
and evaluates
to zero whenk > n
.Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression(1 + x) ** n
.Raises
TypeError
if either of the arguments are not integers.
RaisesValueError
if either of the arguments are negative.New in version 3.8.
-
math.
copysign
(x, y)¶ -
Return a float with the magnitude (absolute value) of x but the sign of
y. On platforms that support signed zeros,copysign(1.0, -0.0)
returns -1.0.
-
math.
fabs
(x)¶ -
Return the absolute value of x.
-
math.
factorial
(x)¶ -
Return x factorial as an integer. Raises
ValueError
if x is not integral or
is negative.Deprecated since version 3.9: Accepting floats with integral values (like
5.0
) is deprecated.
-
math.
floor
(x)¶ -
Return the floor of x, the largest integer less than or equal to x.
If x is not a float, delegates tox.__floor__()
, which should return an
Integral
value.
-
math.
fmod
(x, y)¶ -
Return
fmod(x, y)
, as defined by the platform C library. Note that the
Python expressionx % y
may not return the same result. The intent of the C
standard is thatfmod(x, y)
be exactly (mathematically; to infinite
precision) equal tox - n*y
for some integer n such that the result has
the same sign as x and magnitude less thanabs(y)
. Python’sx % y
returns a result with the sign of y instead, and may not be exactly computable
for float arguments. For example,fmod(-1e-100, 1e100)
is-1e-100
, but
the result of Python’s-1e-100 % 1e100
is1e100-1e-100
, which cannot be
represented exactly as a float, and rounds to the surprising1e100
. For
this reason, functionfmod()
is generally preferred when working with
floats, while Python’sx % y
is preferred when working with integers.
-
math.
frexp
(x)¶ -
Return the mantissa and exponent of x as the pair
(m, e)
. m is a float
and e is an integer such thatx == m * 2**e
exactly. If x is zero,
returns(0.0, 0)
, otherwise0.5 <= abs(m) < 1
. This is used to “pick
apart” the internal representation of a float in a portable way.
-
math.
fsum
(iterable)¶ -
Return an accurate floating point sum of values in the iterable. Avoids
loss of precision by tracking multiple intermediate partial sums:>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the
typical case where the rounding mode is half-even. On some non-Windows
builds, the underlying C library uses extended precision addition and may
occasionally double-round an intermediate sum causing it to be off in its
least significant bit.For further discussion and two alternative approaches, see the ASPN cookbook
recipes for accurate floating point summation.
-
math.
gcd
(*integers)¶ -
Return the greatest common divisor of the specified integer arguments.
If any of the arguments is nonzero, then the returned value is the largest
positive integer that is a divisor of all arguments. If all arguments
are zero, then the returned value is0
.gcd()
without arguments
returns0
.New in version 3.5.
Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two
arguments were supported.
-
math.
isclose
(a, b, *, rel_tol=1e-09, abs_tol=0.0)¶ -
Return
True
if the values a and b are close to each other and
False
otherwise.Whether or not two values are considered close is determined according to
given absolute and relative tolerances.rel_tol is the relative tolerance – it is the maximum allowed difference
between a and b, relative to the larger absolute value of a or b.
For example, to set a tolerance of 5%, passrel_tol=0.05
. The default
tolerance is1e-09
, which assures that the two values are the same
within about 9 decimal digits. rel_tol must be greater than zero.abs_tol is the minimum absolute tolerance – useful for comparisons near
zero. abs_tol must be at least zero.If no errors occur, the result will be:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
.The IEEE 754 special values of
NaN
,inf
, and-inf
will be
handled according to IEEE rules. Specifically,NaN
is not considered
close to any other value, includingNaN
.inf
and-inf
are only
considered close to themselves.New in version 3.5.
See also
PEP 485 – A function for testing approximate equality
-
math.
isfinite
(x)¶ -
Return
True
if x is neither an infinity nor a NaN, and
False
otherwise. (Note that0.0
is considered finite.)New in version 3.2.
-
math.
isinf
(x)¶ -
Return
True
if x is a positive or negative infinity, and
False
otherwise.
-
math.
isnan
(x)¶ -
Return
True
if x is a NaN (not a number), andFalse
otherwise.
-
math.
isqrt
(n)¶ -
Return the integer square root of the nonnegative integer n. This is the
floor of the exact square root of n, or equivalently the greatest integer
a such that a² ≤ n.For some applications, it may be more convenient to have the least integer
a such that n ≤ a², or in other words the ceiling of
the exact square root of n. For positive n, this can be computed using
a = 1 + isqrt(n - 1)
.New in version 3.8.
-
math.
lcm
(*integers)¶ -
Return the least common multiple of the specified integer arguments.
If all arguments are nonzero, then the returned value is the smallest
positive integer that is a multiple of all arguments. If any of the arguments
is zero, then the returned value is0
.lcm()
without arguments
returns1
.New in version 3.9.
-
math.
ldexp
(x, i)¶ -
Return
x * (2**i)
. This is essentially the inverse of function
frexp()
.
-
math.
modf
(x)¶ -
Return the fractional and integer parts of x. Both results carry the sign
of x and are floats.
-
math.
nextafter
(x, y)¶ -
Return the next floating-point value after x towards y.
If x is equal to y, return y.
Examples:
-
math.nextafter(x, math.inf)
goes up: towards positive infinity. -
math.nextafter(x, -math.inf)
goes down: towards minus infinity. -
math.nextafter(x, 0.0)
goes towards zero. -
math.nextafter(x, math.copysign(math.inf, x))
goes away from zero.
See also
math.ulp()
.New in version 3.9.
-
-
math.
perm
(n, k=None)¶ -
Return the number of ways to choose k items from n items
without repetition and with order.Evaluates to
n! / (n - k)!
whenk <= n
and evaluates
to zero whenk > n
.If k is not specified or is None, then k defaults to n
and the function returnsn!
.Raises
TypeError
if either of the arguments are not integers.
RaisesValueError
if either of the arguments are negative.New in version 3.8.
-
math.
prod
(iterable, *, start=1)¶ -
Calculate the product of all the elements in the input iterable.
The default start value for the product is1
.When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.New in version 3.8.
-
math.
remainder
(x, y)¶ -
Return the IEEE 754-style remainder of x with respect to y. For
finite x and finite nonzero y, this is the differencex - n*y
,
wheren
is the closest integer to the exact value of the quotientx /
. If
yx / y
is exactly halfway between two consecutive integers, the
nearest even integer is used forn
. The remainderr = remainder(x,
thus always satisfies
y)abs(r) <= 0.5 * abs(y)
.Special cases follow IEEE 754: in particular,
remainder(x, math.inf)
is
x for any finite x, andremainder(x, 0)
and
remainder(math.inf, x)
raiseValueError
for any non-NaN x.
If the result of the remainder operation is zero, that zero will have
the same sign as x.On platforms using IEEE 754 binary floating-point, the result of this
operation is always exactly representable: no rounding error is introduced.New in version 3.7.
-
math.
trunc
(x)¶ -
Return the
Real
value x truncated to an
Integral
(usually an integer). Delegates to
x.__trunc__()
.
-
math.
ulp
(x)¶ -
Return the value of the least significant bit of the float x:
-
If x is a NaN (not a number), return x.
-
If x is negative, return
ulp(-x)
. -
If x is a positive infinity, return x.
-
If x is equal to zero, return the smallest positive
denormalized representable float (smaller than the minimum positive
normalized float,sys.float_info.min
). -
If x is equal to the largest positive representable float,
return the value of the least significant bit of x, such that the first
float smaller than x isx - ulp(x)
. -
Otherwise (x is a positive finite number), return the value of the least
significant bit of x, such that the first float bigger than x
isx + ulp(x)
.
ULP stands for “Unit in the Last Place”.
See also
math.nextafter()
andsys.float_info.epsilon
.New in version 3.9.
-
Note that frexp()
and modf()
have a different call/return pattern
than their C equivalents: they take a single argument and return a pair of
values, rather than returning their second return value through an ‘output
parameter’ (there is no such thing in Python).
For the ceil()
, floor()
, and modf()
functions, note that all
floating-point numbers of sufficiently large magnitude are exact integers.
Python floats typically carry no more than 53 bits of precision (the same as the
platform C double type), in which case any float x with abs(x) >= 2**52
necessarily has no fractional bits.
Power and logarithmic functions¶
-
math.
exp
(x)¶ -
Return e raised to the power x, where e = 2.718281… is the base
of natural logarithms. This is usually more accurate thanmath.e ** x
orpow(math.e, x)
.
-
math.
expm1
(x)¶ -
Return e raised to the power x, minus 1. Here e is the base of natural
logarithms. For small floats x, the subtraction inexp(x) - 1
can result in a significant loss of precision; theexpm1()
function provides a way to compute this quantity to full precision:>>> from math import exp, expm1 >>> exp(1e-5) - 1 # gives result accurate to 11 places 1.0000050000069649e-05 >>> expm1(1e-5) # result accurate to full precision 1.0000050000166668e-05
New in version 3.2.
-
math.
log
(x[, base])¶ -
With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base,
calculated aslog(x)/log(base)
.
-
math.
log1p
(x)¶ -
Return the natural logarithm of 1+x (base e). The
result is calculated in a way which is accurate for x near zero.
-
math.
log2
(x)¶ -
Return the base-2 logarithm of x. This is usually more accurate than
log(x, 2)
.New in version 3.3.
See also
int.bit_length()
returns the number of bits necessary to represent
an integer in binary, excluding the sign and leading zeros.
-
math.
log10
(x)¶ -
Return the base-10 logarithm of x. This is usually more accurate
thanlog(x, 10)
.
-
math.
pow
(x, y)¶ -
Return
x
raised to the powery
. Exceptional cases follow
Annex ‘F’ of the C99 standard as far as possible. In particular,
pow(1.0, x)
andpow(x, 0.0)
always return1.0
, even
whenx
is a zero or a NaN. If bothx
andy
are finite,
x
is negative, andy
is not an integer thenpow(x, y)
is undefined, and raisesValueError
.Unlike the built-in
**
operator,math.pow()
converts both
its arguments to typefloat
. Use**
or the built-in
pow()
function for computing exact integer powers.
-
math.
sqrt
(x)¶ -
Return the square root of x.
Trigonometric functions¶
-
math.
acos
(x)¶ -
Return the arc cosine of x, in radians. The result is between
0
and
pi
.
-
math.
asin
(x)¶ -
Return the arc sine of x, in radians. The result is between
-pi/2
and
pi/2
.
-
math.
atan
(x)¶ -
Return the arc tangent of x, in radians. The result is between
-pi/2
and
pi/2
.
-
math.
atan2
(y, x)¶ -
Return
atan(y / x)
, in radians. The result is between-pi
andpi
.
The vector in the plane from the origin to point(x, y)
makes this angle
with the positive X axis. The point ofatan2()
is that the signs of both
inputs are known to it, so it can compute the correct quadrant for the angle.
For example,atan(1)
andatan2(1, 1)
are bothpi/4
, butatan2(-1,
is
-1)-3*pi/4
.
-
math.
cos
(x)¶ -
Return the cosine of x radians.
-
math.
dist
(p, q)¶ -
Return the Euclidean distance between two points p and q, each
given as a sequence (or iterable) of coordinates. The two points
must have the same dimension.Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
New in version 3.8.
-
math.
hypot
(*coordinates)¶ -
Return the Euclidean norm,
sqrt(sum(x**2 for x in coordinates))
.
This is the length of the vector from the origin to the point
given by the coordinates.For a two dimensional point
(x, y)
, this is equivalent to computing
the hypotenuse of a right triangle using the Pythagorean theorem,
sqrt(x*x + y*y)
.Changed in version 3.8: Added support for n-dimensional points. Formerly, only the two
dimensional case was supported.Changed in version 3.10: Improved the algorithm’s accuracy so that the maximum error is
under 1 ulp (unit in the last place). More typically, the result
is almost always correctly rounded to within 1/2 ulp.
-
math.
sin
(x)¶ -
Return the sine of x radians.
-
math.
tan
(x)¶ -
Return the tangent of x radians.
Angular conversion¶
-
math.
degrees
(x)¶ -
Convert angle x from radians to degrees.
-
math.
radians
(x)¶ -
Convert angle x from degrees to radians.
Hyperbolic functions¶
Hyperbolic functions
are analogs of trigonometric functions that are based on hyperbolas
instead of circles.
-
math.
acosh
(x)¶ -
Return the inverse hyperbolic cosine of x.
-
math.
asinh
(x)¶ -
Return the inverse hyperbolic sine of x.
-
math.
atanh
(x)¶ -
Return the inverse hyperbolic tangent of x.
-
math.
cosh
(x)¶ -
Return the hyperbolic cosine of x.
-
math.
sinh
(x)¶ -
Return the hyperbolic sine of x.
-
math.
tanh
(x)¶ -
Return the hyperbolic tangent of x.
Special functions¶
-
math.
erf
(x)¶ -
Return the error function at
x.The
erf()
function can be used to compute traditional statistical
functions such as the cumulative standard normal distribution:def phi(x): 'Cumulative distribution function for the standard normal distribution' return (1.0 + erf(x / sqrt(2.0))) / 2.0
New in version 3.2.
-
math.
erfc
(x)¶ -
Return the complementary error function at x. The complementary error
function is defined as
1.0 - erf(x)
. It is used for large values of x where a subtraction
from one would cause a loss of significance.New in version 3.2.
-
math.
gamma
(x)¶ -
Return the Gamma function at
x.New in version 3.2.
-
math.
lgamma
(x)¶ -
Return the natural logarithm of the absolute value of the Gamma
function at x.New in version 3.2.
Constants¶
-
math.
pi
¶ -
The mathematical constant π = 3.141592…, to available precision.
-
math.
e
¶ -
The mathematical constant e = 2.718281…, to available precision.
-
math.
tau
¶ -
The mathematical constant τ = 6.283185…, to available precision.
Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to
its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still)
Wrong, and start celebrating
Tau day by eating twice as much pie!New in version 3.6.
-
math.
inf
¶ -
A floating-point positive infinity. (For negative infinity, use
-math.inf
.) Equivalent to the output offloat('inf')
.New in version 3.5.
-
math.
nan
¶ -
A floating-point “not a number” (NaN) value. Equivalent to the output of
float('nan')
.New in version 3.5.
CPython implementation detail: The math
module consists mostly of thin wrappers around the platform C
math library functions. Behavior in exceptional cases follows Annex F of
the C99 standard where appropriate. The current implementation will raise
ValueError
for invalid operations like sqrt(-1.0)
or log(0.0)
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and OverflowError
for results that overflow (for example,
exp(1000.0)
). A NaN will not be returned from any of the functions
above unless one or more of the input arguments was a NaN; in that case,
most functions will return a NaN, but (again following C99 Annex F) there
are some exceptions to this rule, for example pow(float('nan'), 0.0)
or
hypot(float('nan'), float('inf'))
.
Note that Python makes no effort to distinguish signaling NaNs from
quiet NaNs, and behavior for signaling NaNs remains unspecified.
Typical behavior is to treat all NaNs as though they were quiet.
See also
- Module
cmath
-
Complex number versions of many of these functions.