Math libraries for python

5 самых полезных математических библиотек Python

Математика в Python не ограничивается простыми выражениями. Существует множество полезных библиотек и модулей, способных поднять ваши вычисления на совершенно другой уровень. В этой статье мы познакомимся с пятью самыми полезными из них.

Math

Рано или поздно наступит момент, когда вам не хватит стандартных математических операторов в Python. Например, придется найти квадратный корень, логарифм или синус. В этом вам поможет модуль Math.

>>> import math >>> math.sqrt(17) 4.123105625617661 >>> math.sin(33) 0.9999118601072672 >>> math.log(15, 2) 3.9068905956085187 

Помимо дополнительных математических функций, модуль содержит константы, такие как math.pi , math.e и бесконечность — math.inf . Функция math.isclose() поможет вам сравнивать числа с заданной точностью.

SymPy

SymPy — библиотека для работы с символьными вычислениями. С этим модулем возможно написать системы уравнений, подставить в них значения, сократить математические формулы. Результаты вычислений можно преобразовать в код LaTeX — это пригодится, если вы публикуете свои результаты в научных журналах или пишете диплом.

>>> from sympy import * . x = Symbol('x') . y, z = symbols('y, z') . expr = (x**2 + y**2) * z . expr z*(x**2 + y**2) >>> expr2 = expr.subs(x, 12) . expr2.subs(y, 3) 153*z 

NumPy

NumPy — библиотека для работы с n-мерными массивами. Они похожи на вложенные кортежи, но требуют, чтобы все элементы были одного типа. Над массивами целиком и их элементами можно проводить различные операции, недоступные для стандартных типов данных.

>>> import numpy as np >>> a = np.array([1, 0.5, -1.9], dtype=float) >>> b = np.array([[10], [10], [10]], dtype=float) c = np.array(a*b) c array([[ 10., 5., -19.], [ 10., 5., -19.], [ 10., 5., -19.]]) 

Также в этом пакете доступны продвинутые функции и методы для обработки массивов.

>>> # Ищем среднее по вертикали >>> c.mean(axis=0) array([ 10., 5., -19.]) >>> # Ищем среднее по горизонтали >>> c.mean(axis=1) array([-1.33333333, -1.33333333, -1.33333333]) 

Библиотека NumPy написана на С и очень хорошо оптимизирована, что позволяет максимально ускорить вычисления. Это делает ее основой для всех продвинутых математических библиотек Python`a.

Читайте также:  Change icon color html

SciPy

SciPy ещё больше расширяет возможности NumPy. В этой библиотеке есть множество модулей для самых разных вычислений. Например, модуль scipy.spatial позволяет работать с пространственными данными и алгоритмами, а scipy.stats — со статистикой и распределениями вероятностей. Если вы работали с MATLAB, то вам не составит труда разобраться и со SciPy.

from scipy import stats # Берем 30 значений из нормального распределения # со средним = 25 и стандартным отклонением = 10 a = stats.norm.rvs(size=30, loc=25, scale=10) # Рассчитываем эксцесс полученной выборки stats.kurtosis(a) 

Pandas

Библиотека Pandas также построена на основе NumPy. Она специализируется на работе с таблицами ( DataFrame ) и временными рядами ( Series ).

>>> import numpy as np . import pandas as pd . df = pd.DataFrame( . 'name': ['Viktor', 'Ann', 'Kim'], . 'age': [20, 35, np.nan], . 'score': [81.17, 93.7, np.nan] . >) . df name age score 0 Viktor 20.0 81.17 1 Ann 35.0 93.70 2 Kim NaN NaN 

Библиотека умеет обрабатывать таблицы не хуже полноценных табличных процессоров. Данные можно сортировать, фильтровать и группировать, загружать таблицы в разных форматах и объединять их.

>>> df[df['score'] > 90] name age score 1 Ann 35.0 93.7 

Pandas DataFrame используют практически все программы на Python, работающие с таблицами. Также на них часто обучают и проверяют нейросети.

Заключение

Мы рассмотрели самые популярные математические библиотеки Python. Каждая из них по-своему полезна. Для несложных вычислений вам подойдет модуль Math, а для работы с математическими уравнениями и выражениями — SymPy. Библиотека NumPy позволяет эффективно работать с многомерными массивами, поэтому большинство модулей, требующих сложных вычислений зависит от нее. SciPy расширяет возможности NumPy, добавляя модули, специализированные на разных областях науки и математики, а Pandas позволяет работать с таблицами и временными рядами.

Навыки работы с этими библиотеками пригодятся для разнообразных вычислений, которые то и дело требуются в программах. Умение математически обрабатывать данные на Python очень важно сферах Data science и Machine learning. Возможно, сейчас самое время подтянуть алгебру?

Практический Python для начинающих

Практический Python для начинающих

Станьте junior Python программистом за 7 месяцев

Источник

10 Best Math Libraries for Python

Many times, when you write programs you need to use special functions that others have used before you. When this happens, open source comes to the rescue and gives you a library that covers that need. Python calls theirs modules, to use modules you need to import them.Modules for mathematics are especially useful when you have the theory ready but need to use standard math for your particular problem. The Mathematics module in the Python standard library has many features. It is useful to check if you can solve your problem easily with these functions. If you need to know what functions exist you need to go through the list. However, first realize that the module implements all the C standard functions.

The simplest use of Python for math is as a calculator. To do this, start Python on the terminal and use the print function.

The simple math is available without even activating the math module but beyond addition, subtraction, division and multiplication you need to import the math module. To make the code short, import as ‘m’. Now you put m and a dot in front of any functions you use. This works the same for all modules in Python. If you want to use complex numbers, use the cmath module.

For functions beyond that, below are some libraries specialized for certain needs.

  1. The NumPy libraries handles the mathematical functions for arrays. Creating arrays of any type is possible and optimizing in memory is also supported. The N-dimensional array is fully covered. Functions that the library handles includes iteration, Fourier Transfom, linear algebra and financial functions. This library also implements a C-API so you can use the speed of C without translating your entire project.
  1. SciPy is a collection of science related software, with mathematical tasks at the center. If you need to calculate anything, this is a good place to start. The collection includes integration, optimization and sparse eigenvalues.
  1. Scikit-image is a great resource for manipulating and analysing images. The library has features for detecting lines, edges and features. It also has restoration features, for when you have images with defects on them. There are also many analysis tools available.
  1. Scikit-learn is useful for getting machine learning code together. It contains modules for classification, regression, clustering and more. The web page is full of useful examples so you can easily get started.
  1. Pandas is your goto resource for big data sets to do your data science on. Pandas supports data analysis and modeling and does it with simple and clear code. Many functions are translatable from R, so you can prototype with Pandas.
  1. Statsmodels covers your needs for statistical models. This library handles many similar things like Panda but can also import Sata files and handle time series analysis. There is a sandbox included where you can experiment with different statistical models. That particular code is not tested yet but maybe it is close enough for you to finish the job.
  1. Matplotlib: For plotting your graphs, includes animated plots.
    The earlier libraries are great for the mathematics but they have deliberately stayed away from plotting. Instead they let libraries like matplotlib handle these
    This has made matplotlib extensive and it also has many supporting software that covers mapping, plotting and electronic circuit design.
  1. Gnuplot.py is an interface package to the popular gnuplot program. It has an object oriented design so you can add your own extensions.
  1. Patsy describes statistical models in all its forms. It also has many functions that are common in R but with small differences, like how to denote exponentiation. Patsy will build matrices using formulas, very similar to the way it is done in S and R.
  1. Sympy: When you want to print your mathematical formulas you use this library. It also has the capability to evaluate expressions. It is very useful for creating formulas in your LaTeX documents. You can even run Sympy live in your browser to test it out.

Now that you have learned what projects to use for mathematics you will soon be short on processing power. To remedy that situation parallel execution is the most common solution. There are several Python libraries for this purpose.

The mpi4py library provides bindings to the standard Message Passing Interface. You need to download a standard parallel library like mpich or openmpi. Both are available in the standard repositories.

The other library is parallel python or pp. Parallel Python creates a server and many clients that take jobs from your server. This project does not implement a standard, instead you use the server and client from this same package on all your machines. This is simpler in some ways but it requires more when your project becomes big and you need other people to lend you processing power.

These libraries are all good in their own right but make sure to pick the correct one for your needs.
The choice is not irreversible but will require quite a lot of work later in a project. Your source code will need to be changed to use a new library and new faults will occur so choose wisely.

If you want to do your calculations interactively, install and use Ipython as this is an enhanced version of the command line version of Python. Also, if you have not already, consider using Jupyter. It provides you with notebook, documents and a code console on the same workspace.

The framework acts as an IDE but is aimed more at exploring the problems and the software you are developing than traditional IDEs.

For more information see this articles:

Источник

Математические библиотеки Python

Математика в Python

Боитесь математики? Не раз пытались решить задачки по математике с помощью технологий? Не вы одни. Сегодня в Python можно решить почти все математические задачи. В данной статье мы рассмотрим способы имплементации различных математических операций в Python.

Python является универсальным языком, который используется в процессе веб-разработки создания сайта, работе с базами данных и научными вычислениями. В данном руководстве будет рассмотрено, как математические библиотеки Python повлияли на научные вычисления.

Итак, давайте разберем самые популярные математические библиотеки Python.

Python библиотеки для математики

Python стал очень популярным из-за обилия библиотек. Каждая библиотека ориентирована на разработку приложений и решений всех проблем, что могут возникнуть во время процесса. Математические операции удобно выполняются в Python из-за его внимания к минимализму в сочетании с полезностью. Для математических операций в Python есть сразу несколько библиотек.

Библиотека Math в Python

Math является самым базовым математическим модулем Python. Охватывает основные математические операции, такие как сумма, экспонента, модуль и так далее. Эта библиотека не используется при работе со сложными математическими операциями, такими как умножение матриц. Расчеты, выполняемые с помощью функций библиотеки math, также выполняются намного медленнее. Тем не менее, эта библиотека подходит для выполнения основных математических операций.

Пример: Вы можете найти экспоненту от 3, используя функцию exp() библиотеки math следующим образом:

Источник

Оцените статью