- cmath — Mathematical functions for complex numbers¶
- Conversions to and from polar coordinates¶
- Power and logarithmic functions¶
- Trigonometric functions¶
- Hyperbolic functions¶
- Classification functions¶
- Constants¶
- Как округлить комплексное число?
- 3 ответа
- Числа в Python и методы работы с ними
- Целые числа (int) в Python
- Числа с плавающей точкой (float)
- Комплексные числа (complex)
- Проверка типа данных переменной
- Арифметические действия в Python
- Округление чисел с плавающей точкой
- Получение модуля числа
- Вывод
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.
Как округлить комплексное число?
Как я могу округлить комплексное число (например, 1.9999999999999998-2j ) как 2-2j ?
Когда я пытался использовать
Traceback (most recent call last): File "C:\Python34\FFT.py", line 22, in print(round(x,2)) TypeError: type complex doesn't define __round__ method
3 ответа
Вокруг реальной части и мнимой части отдельно и объединить их:
>>> num = 1.9999999999999998-2j >>> round(num.real, 2) + round(num.imag, 2) * 1j (2-2j)
Если все, что вы хотите сделать, это представить значение, округленное, как показано, вместо того, чтобы изменять само значение, работает следующее:
>>> x=1.9999999999999998-2j >>> print("".format(x)) 2-2j
Я бы сказал, что лучший способ сделать это как таковой
x = (1.542334+32.5322j) x = complex(round(x.real),round(x.imag))
Если вы не хотите повторять это каждый раз, когда захотите, вы можете поместить это в функцию.
def round_complex(x): return complex(round(x.real),round(x.imag))
К этому могут быть добавлены дополнительные необязательные аргументы, например, если вы хотите округлить только одну часть, например, или если вы хотите округлить до определенного числа десятичных знаков в вещественной или сложной части
def round_complex(x, PlacesReal = 0, PlacesImag = 0, RoundImag = True, RoundReal = True): if RoundImag and not RoundReal: return complex(x.real,round(x.imag,PlacesImag)) elif RoundReal and not RoundImag: return complex(round(x.real,PlacesReal),x.imag) else: #it would be a waste of space to make it do nothing if you set both to false, so it instead does what it would if both were true return complex(round(x.real,PlacesReal),round(x.imag,PlacesImag))
Так как переменные автоматически устанавливаются в true или 0, вам не нужно вводить их, если вы не хотите этого. Но их удобно иметь
Числа в Python и методы работы с ними
В Python, как и во всех популярных языках программирования, имеются целые числа (int) и числа с плавающей точкой (float). Но у Python есть и отличительная особенность – комплексные числа (complex).
Стоит также уточнить, что при присваивании переменной любого типа числа, не нужно использовать кавычки, так как они определяют строку, а не число. Пример:
str1 = '1' str2 = '2' num1 = 1 num2 = 2 print(str1+str2) # Выведет '12' print(num1+num2) # Выведет 3
Целые числа (int) в Python
В Python, как и в привычной нам математике, целыми числами являются все числа, которые лишены дробной части, то есть не имеют плавающей точки. Рассмотрим на примере:
num1 = 1 num2 = 2 # Присваиваем переменным целые числа print(num1, num2) # Выведет 1 2
Для упрощения создания больших чисел в Python используется нижнее подчеркивание, а не запятая. Пример:
num = 999_999_999 print(num) # Выведет 999999999 num = 999,999,999 print(num) # Выдаст ошибку
Числа с плавающей точкой (float)
Для отделения целой части числа в Python используется точка. Рассмотрим создание float-числа на примере:
num1 = 0.1 num2 = 0.22 # Присваиваем переменным целые числа print(num1, num2) # Выведет 0.1 0.22
Комплексные числа (complex)
Как я писал выше, Python поддерживает комплексные числа без установки дополнительных модулей. Рассмотрим создание таких чисел на примере:
# создание и сложение двух комплексных чисел num1 = 1 + 2j num2 = 2 + 4j summa = num1 + num2 print(summa) # Выведет (3+6j)
Проверка типа данных переменной
Для проверки типа данных переменной в Python используется встроенная функция type(). Рассмотрим на примере:
str = ‘1’ int = 1 float = 1.1 com1 = 1 + 2j com2 = 2 + 4j complex = com1 + com2 print(type(str)) # Выведет print(type(int)) # Выведет print(type(float)) # Выведет print(type(complex)) # Выведет
Арифметические действия в Python
Сложение делается с помощью оператора “+”. Пример:
a = 1 + 1 print(a) # Выведет 2
С помощью сложения можно преобразовать целое число в число с плавающей точкой. Рассмотрим на примере:
a = 1 + 1.0 print(a) # Выведет 2.0
Вычитание выполняется с помощью оператора “—”. Пример:
a = 1 - 1 print(a) # Выведет 0
Умножение делается с помощью оператора “*”:
a = 2 * 2 print(a) # Выведет 4
Возведение в степень выполняется с помощью оператора “**”. Пример:
Также возведение в степень можно производить с помощью функции pow():
num1 = 2 num2 = 3 print(pow(num1, num2)) # Выведет 8
Деление выполняется с помощью оператора “/”. Пример:
a = 4 / 2 print(a) # Выведет 2
Для получения остатка от деления используется оператор “%”. Пример:
a = 5 % 2 print(a) # Выведет 1
Целочисленное деление выполняется с помощью оператора “//”. Пример:
a = 5 // 2 print(a) # Выведет 2
Округление чисел с плавающей точкой
Для округления float-чисел до ближайшего целого числа используется функция round(). Рассмотрим на примере:
num1 = 1.4 num2 = 1.6 print(round(num1)) # Выведет 1 print(round(num2)) # Выведет 2
Получение модуля числа
Для получения модуля любого числа мы можем использовать функцию abs(). Рассмотрим на примере:
num1 = -2 num2 = 3 print(abs(num1)) # Выведет 2 print(abs(num2)) # Выведет 3
Вывод
Мы разобрали функции для работы с числами в Python и научились ими пользоваться. Надеюсь, эта статья оказалась для вас полезной. Удачи в ваших начинаниях!