- Числа в Python (FAQ)
- Целые числа (int)
- Вещественные числа (float)
- Комплексные числа (complex)
- Операции с числами
- Является ли переменная числом
- Арифметические операции
- Сравнение чисел
- Преобразования
- Ввод чисел
- Вывод чисел
- Другие полезные функции
- cmath — Mathematical functions for complex numbers¶
- Conversions to and from polar coordinates¶
- Power and logarithmic functions¶
- Trigonometric functions¶
- Hyperbolic functions¶
- Classification functions¶
- Constants¶
Числа в Python (FAQ)
Числа в Python (как и в других языках программирования) чрезвычайно простое понятие. В Python все переменные представляют собой объекты и размещаются в динамической памяти.
Базовый набор Python содержит следующие типы чисел:
- целые ( int );
- вещественные ( float ) [с десятичной точкой];
- комплексные ( complex ) [состоят из действительной и мнимой части].
Над числами в Python можно выполнять самые обычные математические операции: сложение ( + ), вычитание ( — ), возведение в степень ( ** ) и т.д.
Целые числа (int)
В Python любое число, состоящее из десятичных цифр без префикса, интерпретируется как десятичное число типа int .
>>> 0 0 >>> 20 20 >>> -20 -20 >>> type(20) >>> 100 + 20 120
Целые числа в Python представлены только одним типом — PyLongObject , реализация которого лежит в longobject.c , а сама структура выглядит так:
Любое целое число состоит из массива цифр переменной длины, поэтому в Python 3 в переменную типа int может быть записано число неограниченной длины. Единственное ограничение длины — это размер оперативной памяти.
>>> 134523345234252523523478777 ** 2 18096530413013891133013347014216107772438771969415729
Целые числа могут записываться не только как десятичные, но и как двоичные, восьмеричные или шестнадцатеричные. Для этого перед числом нужно написать символы:
- 0b (0B) – для двоичного представления;
- 0o (0O) – для восьмеричного представления;
- 0x (0X) – для шестнадцатеричного представления.
Вещественные числа (float)
Еще такие числа называют числами с плавающей точкой . Это числа, содержащие точку (десятичный разделитель) или знак экспоненты.
>>> 1.5 1.5 >>> type(1.5) >>> 3. 3.0 >>> .5 0.5 >>> .4e7 4000000.0 >>> type(.4e7) >>> 4.1e-4 0.00041
Числа типа float — неточны (из-за представления чисел с плавающей запятой в компьютере).
>>> 0.3 + 0.3 + 0.3 + 0.1 0.9999999999999999
Информацию о точности и внутреннем представлении float для вашей системы можно получить из sys.float_info
>>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
Если нужна высокая точность обычно используют модули Decimal и Fraction.
Об ограничениях и подводных камнях в работе с числами с плавающей точкой описано тут .
Комплексные числа (complex)
Комплексные числа представляют собой пару значений типа int или float , и имеют вид +j .
Отдельные части комплексного числа доступны через атрибуты real и imag
>>> num = 1.1+2j >>> num.real, num.imag (1.1, 2.0)
Операции с числами
Является ли переменная числом
Любую переменную можно проверить на тип (int, float или complex):
n = 10 >>> if type(n) == int: print(«This is int») This is int
Если вы хотите проверить, находится ли в строке число, воспользуйтесь методом isdigit()
>>> string = «404» >>> string.isdigit() True
Однако стоит помнить, что метод isdigit() не работает для отрицательных чисел и чисел с плавающей точкой.
Также для проверки на число, можно написать собственную функцию:
>>> def isInt(value): try: int(value) return True except ValueError: return False >>> isInt(123) True >>> isInt(«qwerty») False >>> isInt(«123») True >>> isInt(«-123») True >>> isInt(«123.2») False
Арифметические операции
- x + y — сложение;
- x — y — вычитание;
- x * y — умножение;
- x / y — деление;
- x // y — целочисленное деление;
- x % y — остаток от деления;
- x ** y — возведение в степень;
- -x — смена знака;
- abs(x) — модуль числа;
- divmod(x, y) — возвращает кортеж из частного и остатка от деления x на y;
- pow(x, y[, z]) — возведение числа в степень (z — деление по модулю);
- round(x[, ndigits]) — округление числа (ndigits — знаки после запятой).
Сравнение чисел
- x == y — равно;
- x != y — не равно;
- x > y — больше;
- x < y — меньше;
- x >= y — больше или равно;
- x
Преобразования
- int(x) — преобразование в целое число int ;
- float(x) — преобразование в число с плавающей точкой float ;
- complex(x) — преобразование в комплексное число complex ;
- bin(x) — целое числа в двоичную строку;
- oct(x) — целое число в восьмеричную строку;
- hex(х) — целое число в шестнадцатеричную строку;
- [int(x) for x in str(123)] — перевод целого числа 123 в список цифр этого числа;
- int(».join(str(digit) for digit in [1,2,3])) — перевод списка цифр [1,2,3] в целое число 123;
- str(x) — число в строку;
Ввод чисел
Для ввода данных в программу на языке Python используется функция input() . Эта функция считывает то что вы ввели на клавиатуре, и записывает эти данные в переменную в виде одной строки. После этого, перевести строку в число можно простыми функциями int() , float() или complex() .
Если нужен список чисел, введите несколько чисел через пробел и выполните:
my_list = [int(x) for x in input().split()] print(my_list) > [1, 2, 3]
Вывод чисел
Для вывода числа используйте print() :
>>> print(1) 1 >>> print(-1.2) -1.2 >>> print(1, 3, 4) 1 3 4
На практике возникают ситуации, когда нужно вывести число вместе со строкой (например пояснить, что означает число). Существует несколько вариантов сделать это:
>>> print(«int variable = » + str(1)) int variable = 1 >>> print(«int variable = <>«.format(1)) int variable = 1 >>> print(f’int variable = ‘) # f-строки работают в Python 3.6+ int variable = 1
Другие полезные функции
- len(str(x)) — посчитает длину числа;
- 1230 % 2 — если остаток от деления равен 0, то число четное;
- range(0,5) — диапазон чисел от 0 до 5, по которому можно итерироваться;
- int(str(123)[::-1]) — перевернет число (123 -> 321).
cmath — Mathematical functions for complex numbers¶
This module provides access to mathematical functions for complex numbers. The functions in this module accept integers, floating-point numbers or complex numbers as arguments. They will also accept any Python object that has either a __complex__() or a __float__() method: these methods are used to convert the object to a complex or floating-point number, respectively, and the function is then applied to the result of the conversion.
For functions involving branch cuts, we have the problem of deciding how to define those functions on the cut itself. Following Kahan’s “Branch cuts for complex elementary functions” paper, as well as Annex G of C99 and later C standards, we use the sign of zero to distinguish one side of the branch cut from the other: for a branch cut along (a portion of) the real axis we look at the sign of the imaginary part, while for a branch cut along the imaginary axis we look at the sign of the real part.
For example, the cmath.sqrt() function has a branch cut along the negative real axis. An argument of complex(-2.0, -0.0) is treated as though it lies below the branch cut, and so gives a result on the negative imaginary axis:
>>> cmath.sqrt(complex(-2.0, -0.0)) -1.4142135623730951j
But an argument of complex(-2.0, 0.0) is treated as though it lies above the branch cut:
>>> cmath.sqrt(complex(-2.0, 0.0)) 1.4142135623730951j
Conversions to and from polar coordinates¶
A Python complex number z is stored internally using rectangular or Cartesian coordinates. It is completely determined by its real part z.real and its imaginary part z.imag . In other words:
Polar coordinates give an alternative way to represent a complex number. In polar coordinates, a complex number z is defined by the modulus r and the phase angle phi. The modulus r is the distance from z to the origin, while the phase phi is the counterclockwise angle, measured in radians, from the positive x-axis to the line segment that joins the origin to z.
The following functions can be used to convert from the native rectangular coordinates to polar coordinates and back.
Return the phase of x (also known as the argument of x), as a float. phase(x) is equivalent to math.atan2(x.imag, x.real) . The result lies in the range [-π, π], and the branch cut for this operation lies along the negative real axis. The sign of the result is the same as the sign of x.imag , even when x.imag is zero:
>>> phase(complex(-1.0, 0.0)) 3.141592653589793 >>> phase(complex(-1.0, -0.0)) -3.141592653589793
The modulus (absolute value) of a complex number x can be computed using the built-in abs() function. There is no separate cmath module function for this operation.
Return the representation of x in polar coordinates. Returns a pair (r, phi) where r is the modulus of x and phi is the phase of x. polar(x) is equivalent to (abs(x), phase(x)) .
Return the complex number x with polar coordinates r and phi. Equivalent to r * (math.cos(phi) + math.sin(phi)*1j) .
Power and logarithmic functions¶
Return e raised to the power x, where e is the base of natural logarithms.
Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm of x. There is one branch cut, from 0 along the negative real axis to -∞.
Return the base-10 logarithm of x. This has the same branch cut as log() .
Return the square root of x. This has the same branch cut as log() .
Trigonometric functions¶
Return the arc cosine of x. There are two branch cuts: One extends right from 1 along the real axis to ∞. The other extends left from -1 along the real axis to -∞.
Return the arc sine of x. This has the same branch cuts as acos() .
Return the arc tangent of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j . The other extends from -1j along the imaginary axis to -∞j .
Hyperbolic functions¶
Return the inverse hyperbolic cosine of x. There is one branch cut, extending left from 1 along the real axis to -∞.
Return the inverse hyperbolic sine of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j . The other extends from -1j along the imaginary axis to -∞j .
Return the inverse hyperbolic tangent of x. There are two branch cuts: One extends from 1 along the real axis to ∞ . The other extends from -1 along the real axis to -∞ .
Return the hyperbolic cosine of x.
Return the hyperbolic sine of x.
Return the hyperbolic tangent of x.
Classification functions¶
Return True if both the real and imaginary parts of x are finite, and False otherwise.
Return True if either the real or the imaginary part of x is an infinity, and False otherwise.
Return True if either the real or the imaginary part of x is a NaN, and False otherwise.
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%, pass rel_tol=0.05 . The default tolerance is 1e-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.
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, including NaN . inf and -inf are only considered close to themselves.
PEP 485 – A function for testing approximate equality
Constants¶
The mathematical constant π, as a float.
The mathematical constant e, as a float.
The mathematical constant τ, as a float.
Floating-point positive infinity. Equivalent to float(‘inf’) .
Complex number with zero real part and positive infinity imaginary part. Equivalent to complex(0.0, float(‘inf’)) .
A floating-point “not a number” (NaN) value. Equivalent to float(‘nan’) .
Complex number with zero real part and NaN imaginary part. Equivalent to complex(0.0, float(‘nan’)) .
Note that the selection of functions is similar, but not identical, to that in module math . The reason for having two modules is that some users aren’t interested in complex numbers, and perhaps don’t even know what they are. They would rather have math.sqrt(-1) raise an exception than return a complex number. Also note that the functions defined in cmath always return a complex number, even if the answer can be expressed as a real number (in which case the complex number has an imaginary part of zero).
A note on branch cuts: They are curves along which the given function fails to be continuous. They are a necessary feature of many complex functions. It is assumed that if you need to compute with complex functions, you will understand about branch cuts. Consult almost any (not too elementary) book on complex variables for enlightenment. For information of the proper choice of branch cuts for numerical purposes, a good reference should be the following:
Kahan, W: Branch cuts for complex elementary functions; or, Much ado about nothing’s sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165–211.