Python mathematical functions
Содержание:
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution
NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations
Добавляем параметры командной строки для сборки
pyfoo_c_05pyproject.tomlproject.pyfoofoo.h—foo-include-dir—foo-library-dirfooproject.pysipbuild.Projectproject.py
FooProjectsipbuild.ProjectfooFooProjectget_optionsapply_user_defaultsupdateget_optionsoptions—foo_include_dir—foo_library_dirOptionOption
- help задает описание параметра, которое можно увидеть, если запустить команду вроде sip-wheel -h
- metavar — строковое значение, которое для пользователя описывает, что должно представлять собой значение данного параметра. В нашем примере параметр metavar равен «DIR», чтобы подсказать пользователю, что значение этого параметра — директория.
- default — значение по умолчанию для параметра. В нашем примере подразумевается, что если не указаны пути к заголовочным и объектным файлам, то библиотека foo расположена там же, где и в предыдущих примерах (в папке с исходниками обвязки).
- tools — список строк, описывающих к каким командам должна применяться данная опция. В нашем примере мы добавляем параметры к sip-build, sip-install, sip-sdist и sip-wheel, поэтому tools = .
apply_user_defaultsapply_user_defaultsget_optionsself.foo_include_dirself.foo_library_dirOptiondefaultdefaultapply_user_defaultsself.foo_include_dirself.foo_library_dirupdatepyproject.tomlinclude-dirslibrary-dirsproject.pypyproject.toml
updateself.bindingspyfoopyfoopyproject.tomlinclude_dirslibrary_dirsinclude-dirslibrary-dirsself.foo_include_dirself.foo_library_dirself.foo_include_dirself.foo_library_dirNonepyfoo_c_05/foomakepyfoo_c_05sip-wheelpyfoo-0.5-cp38-cp38-manylinux1_x86_64.whlfoopyfoo_c_05sip-wheel
sip-wheel
foo
Math Methods
Method | Description |
---|---|
math.acos(x) | Returns the arc cosine value of x |
math.acosh(x) | Returns the hyperbolic arc cosine of x |
math.asin(x) | Returns the arc sine of x |
math.asinh(x) | Returns the hyperbolic arc sine of x |
math.atan(x) | Returns the arc tangent value of x |
math.atan2(y, x) | Returns the arc tangent of y/x in radians |
math.atanh(x) | Returns the hyperbolic arctangent value of x |
math.ceil(x) | Rounds a number upwards to the nearest integer, and returns the result |
math.comb(n, k) | Returns the number of ways to choose k items from n items without repetition and order |
math.copysign(x, y) | Returns a float consisting of the value of the first parameter and the sign of the second parameter |
math.cos(x) | Returns the cosine of x |
math.cosh(x) | Returns the hyperbolic cosine of x |
math.degrees(x) | Converts an angle from radians to degrees |
math.dist(p, q) | Calculates the euclidean distance between two specified points (p and q), where p and q are the coordinates of that point |
math.erf(x) | Returns the error function of x |
math.erfc(x) | Returns the complementary error function of x |
math.exp(x) | Returns the value of Ex, where E is Euler’s number (approximately 2.718281…), and x is the number passed to it |
math.expm1(x) | Returns the value of Ex — 1, where E is Euler’s number (approximately 2.718281…), and x is the number passed to it |
math.fabs(x) | Returns the absolute value of a number |
math.factorial() | Returns the factorial of a number |
math.floor(x) | Rounds a number downwards to the nearest integer, and returns the result |
math.fmod(x, y) | Returns the remainder of specified numbers when a number is divided by another number |
math.frexp() | Returns the mantissa and the exponent, of a specified value |
math.fsum(iterable) | Returns the sum of all items in an iterable (tuples, arrays, lists, etc.) |
math.gamma(x) | Returns the gamma value of x |
math.gcd() | Returns the highest value that can divide two integers |
math.hypot() | Find the Euclidean distance from the origin for n inputs |
math.isclose() | Checks whether two values are close, or not |
math.isfinite(x) | Checks whether x is a finite number |
math.isinf(x) | Check whether x is a positive or negative infinty |
math.isnan(x) | Checks whether x is NaN (not a number) |
math.isqrt(n) | Returns the nearest integer square root of n |
math.ldexp(x, i) | Returns the expression x * 2i where x is mantissa and i is an exponent |
math.lgamma(x) | Returns the log gamma value of x |
math.log(x, base) | Returns the natural logarithm of a number, or the logarithm of number to base |
math.log10(x) | Returns the base-10 logarithm of x |
math.log1p(x) | Returns the natural logarithm of 1+x |
math.log2(x) | Returns the base-2 logarithm of x |
math.perm(n, k) | Returns the number of ways to choose k items from n items with order and without repetition |
math.pow(x, y) | Returns the value of x to the power of y |
math.prod(iterable, *, start=1) | Returns the product of an iterable (lists, array, tuples, etc.) |
math.radians(x) | Converts a degree value (x) to radians |
math.remainder(x, y) | Returns the closest value that can make numerator completely divisible by the denominator |
math.sin(x) | Returns the sine of x |
math.sinh(x) | Returns the hyperbolic sine of x |
math.sqrt(x) | Returns the square root of x |
math.tan(x) | Returns the tangent of x |
math.tanh(x) | Returns the hyperbolic tangent of x |
math.trunc(x) | Returns the truncated integer parts of x |
Комплексные числа[править]
Пусть x2 = 2. Большинство из нас будут способны найти первый корень x=2{\displaystyle x={\sqrt {2}}}. Более продвинутые в математике заметят, что имеется и второй корень x=−2{\displaystyle x=-{\sqrt {2}}}. Но встретившись с выражением x2 = -2 решение смогут найти лишь немногие люди, знакомые с комплексными числами. Если вы только собираетесь стать ученым, настоятельно советуем познакомиться сейчас с этими замечательными числами перед тем, как изучить дальнейшие примеры, на которых вы сможете проверить свои новые знания.
Комплексная арифметика в Pythonправить
Python поддерживает расчеты с комплексными числами. Мнимая часть записывается через j, вместо i в математике. Комплексное число 2-3i соответственно будет записано как 2-3j. Ниже показан простой сеанс работы с комплексными числами и примеры простой комплексной арифметики:
>>> u = 2.5 + 3j # создаем комплексное >>> v = 2 # а это целое >>> w = u + v # комплексное + целое >>> w (4.5+3j) >>> a = -2 >>> b = 0.5 >>> s = a + b*1j # complex из двух float >>> s = complex(a, b) # другой способ >>> s (-2+0.5j) >>> s*w # complex*complex (-10.5-3.75j) >>> sw # complex/complex (-0.25641025641025639+ 0.28205128205128205j)
Кроме того объект типа complex легко может быть разложен на реальную и мнимую части и для него может быть найдено сопряженное (conjugate) число:
>>> s.real -2.0 >>> s.imag 0.5 >>> s.conjugate() (-2-0.5j)
Комплексные функции Pythonправить
Для работы с функциями комплексных переменных следует использовать специальную библиотеку — cmath:
>>> from cmath import sin, sinh >>> r1 = sin(8j) >>> r1 1490.4788257895502j >>> r2 = 1j*sinh(8) >>> r2 1490.4788257895502j
Definition and Usage
The method finds the Euclidean norm. The Euclidian norm is the distance from the origin to the coordinates given.
Before Python 3.8 this method could only be used to find the hypotenuse of a right-angled triangle. For two-dimensional cases, where x and y are perpendicular and base, the hypotenuse is calculated by sqrt(x*x + y*y)).
As of Python version 3.8 we can use it to calculate the Euclidean norm as well. For n-dimensional cases, the coordinates passed are assumed to be like (x1, x2, x3,
…, xn). So Euclidean length from the origin is calculated by sqrt(x1*x1 + x2*x2 +x3*x3
…. xn*xn).
For two dimensional points it is still similar to computing hypotenuse of a right-angled triangle.
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution
NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
Sr.No. | Operator & Description |
---|---|
1 |
** Exponentiation (raise to the power) |
2 |
~ + — Complement, unary plus and minus (method names for the last two are +@ and -@) |
3 |
* / % // Multiply, divide, modulo and floor division |
4 |
+ — Addition and subtraction |
5 |
>> << Right and left bitwise shift |
6 |
& Bitwise ‘AND’ |
7 |
^ | Bitwise exclusive `OR’ and regular `OR’ |
8 |
<= < > >= Comparison operators |
9 |
<> == != Equality operators |
10 |
= %= /= //= -= += *= **= Assignment operators |
11 |
is is not Identity operators |
12 |
in not in Membership operators |
13 |
not or and Logical operators |
Previous Page
Print Page
Next Page
Примеры
Пример 1: известен заранее
Если вы собираетесь вызывать только или , то прописать импорты всем модулям не составит труда. В данном случае всегда будет включать папку . Таким образом, все импорты можно писать относительно этой папки.
Пример: файлу в проекте нужно импортировать функцию из .
Решение: (или любой другой эквивалентный синтаксис импорта).
Пример 2: мог измениться
Зачастую нам требуется как запускать скрипт напрямую из командной строки, так и импортировать его как модуль в другом скрипте. Как вы увидите далее, здесь могут возникнуть проблемы, особенно в Python 3.
Пример: пусть нужно импортировать , которому нужно импортировать . Предположим, что всегда запускается напрямую, а не импортируется. Также мы хотим иметь возможность запускать напрямую.
Звучит просто, не так ли? Нам всего лишь нужно выполнить два импорта: один в и другой в .
Проблема: это один из тех случаев, когда меняется. Когда мы выполняем , содержит , а при выполнении содержит .
С импортом в нет никаких проблем. Так как этот модуль всегда запускается напрямую, мы знаем, что при его выполнении в всегда будет . Тогда импортировать можно просто с помощью .
С импортом в немного сложнее. Когда мы запускаем напрямую, содержит , поэтому в импорт будет выглядеть как . Однако если запустить напрямую, то в уже будет . Теперь импорт вызовет ошибку, так как не является папкой внутри .
Вместо этого мы могли бы попробовать . Это решает проблему при запуске напрямую, однако теперь создаёт проблему при запуске . В Python 3 это приведёт к ошибке, потому что не находится в (в Python 2 это не вызовет проблемы из-за поддержки неявных относительных импортов).
Обобщим информацию:
Запускаем | ||
---|---|---|
Нет проблем | В Py2 нет проблем, в Py3 ошибка ( не в ) | |
Ошибка ( не в ) | Нет проблем |
Использование относительного импорта будет иметь тот же эффект, что и .
Вряд ли для этой проблемы есть чистое решение, поэтому вот несколько обходных путей:
1. Использовать абсолютные импорты относительно директории (т. е. средняя колонка в таблице выше). Это гарантирует, что запуск напрямую всегда сработает. Чтобы запустить напрямую, запустите его как импортируемый модуль, а не как скрипт:
- В консоли смените директорию на .
- Запустите .
2. Использовать абсолютные импорты относительно директории (средняя колонка в таблице). Это гарантирует, что запуск напрямую всегда сработает. Чтобы запустить напрямую, можно изменить в , чтобы включить перед импортом .
Примечание Обычно этот метод работает, однако в некоторых случаях переменная может быть неправильной. В таком случае нужно использовать встроенный пакет . Подробнее в этом ответе на StackOverflow.
3. Использовать только Python 2 и неявные относительные импорты (последняя колонка в таблице).
4. Использовать абсолютные импорты относительно директории и добавить её в переменную среды . Это решение не переносимо, поэтому лучше не использовать его. О том, как добавить директорию в , читайте в этом ответе.
Пример 3: мог измениться (вариант 2)
А вот ещё одна проблема посложнее. Допустим, модуль никогда не надо запускать напрямую, но он импортируется и , которые запускаются напрямую.
В этом случае первое решение из примера выше не сработает. Тем не менее, всё ещё можно использовать остальные решения.
Пример 4: импорт из родительской директории
Если мы не изменяем и стараемся не изменять программно, то сталкиваемся со следующим основным ограничением импортов в Python: при запуске скрипта напрямую невозможно импортировать что-либо из его родительской директории.
Например, если бы нам пришлось запустить , то этот модуль не смог бы ничего импортировать из без вмешательства в или .
На первый взгляд может показаться, что относительные импорты (например ) помогут решить эту проблему. Однако запускаемый скрипт (в данном случае ) считается «модулем верхнего уровня». Попытка импортировать что-либо из директории над этим скриптом приведёт к ошибке .
Для решения этой проблемы лучше её не создавать и избегать написания скриптов, которые импортируют из родительской директории. Если этого нельзя избежать, то предпочтительным обходным путём является изменение .
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator | Description | Example |
---|---|---|
+ Addition | Adds values on either side of the operator. | a + b = 30 |
— Subtraction | Subtracts right hand operand from left hand operand. | a – b = -10 |
* Multiplication | Multiplies values on either side of the operator | a * b = 200 |
/ Division | Divides left hand operand by right hand operand | b / a = 2 |
% Modulus | Divides left hand operand by right hand operand and returns remainder | b % a = 0 |
** Exponent | Performs exponential (power) calculation on operators | a**b =10 to the power 20 |
// | Floor Division — The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) − | 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 |