Scipy python что это

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

SciPy library main repository

License

scipy/scipy

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

SciPy (pronounced «Sigh Pie») is an open-source software for mathematics, science, and engineering. It includes modules for statistics, optimization, integration, linear algebra, Fourier transforms, signal and image processing, ODE solvers, and more.

  • Website:https://scipy.org
  • Documentation:https://docs.scipy.org/doc/scipy/
  • Development version of the documentation:https://scipy.github.io/devdocs
  • Mailing list:https://mail.python.org/mailman3/lists/scipy-dev.python.org/
  • Source code:https://github.com/scipy/scipy
  • Contributing:https://scipy.github.io/devdocs/dev/index.html
  • Bug reports:https://github.com/scipy/scipy/issues
  • Code of Conduct:https://docs.scipy.org/doc/scipy/dev/conduct/code_of_conduct.html
  • Report a security vulnerability:https://tidelift.com/docs/security
  • Citing in your work:https://www.scipy.org/citing-scipy/

SciPy is built to work with NumPy arrays, and provides many user-friendly and efficient numerical routines, such as routines for numerical integration and optimization. Together, they run on all popular operating systems, are quick to install, and are free of charge. NumPy and SciPy are easy to use, but powerful enough to be depended upon by some of the world’s leading scientists and engineers. If you need to manipulate numbers on a computer and display or publish the results, give SciPy a try!

For the installation instructions, see our install guide.

We appreciate and welcome contributions. Small improvements or fixes are always appreciated; issues labeled as «good first issue» may be a good starting point. Have a look at our contributing guide.

Читайте также:  Имя переменной динамически php

Writing code isn’t the only way to contribute to SciPy. You can also:

  • review pull requests
  • triage issues
  • develop tutorials, presentations, and other educational materials
  • maintain and improve our website
  • develop graphic design for our brand assets and promotional materials
  • help with outreach and onboard new contributors
  • write grant proposals and help with other fundraising efforts

If you’re unsure where to start or how your skills fit in, reach out! You can ask on the mailing list or here, on GitHub, by leaving a comment on a relevant issue that is already open.

If you are new to contributing to open source, this guide helps explain why, what, and how to get involved.

Источник

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

Библиотека Python SciPy – это набор удобных функций, построенных на NumPy и математических алгоритмах.

  • В настоящее время библиотека SciPy поддерживает интеграцию, градиентную оптимизацию, специальные функции, средства решения обыкновенных дифференциальных уравнений, инструменты параллельного программирования и многое другое. Другими словами, мы можем сказать, что если что-то есть в общем учебнике числовых вычислений, высока вероятность того, что вы найдете его реализацию в SciPy.
  • Интерактивный сеанс с SciPy – это, по сути, среда обработки данных и прототипирования системы, такая же, как MATLAB, Octave, Scilab или R-lab.
  • SciPy – это проект с открытым исходным кодом, выпущенный под лицензией BSD.

Почему SciPy?

SciPy предоставляет высокоуровневые команды и классы для управления данными и визуализации данных, что значительно увеличивает мощность интерактивного сеанса Python.

Помимо математических алгоритмов в SciPy, программисту доступно все, от классов, веб-подпрограмм и баз данных до параллельного программирования, что упрощает и ускоряет разработку сложных и специализированных приложений.

Поскольку SciPy имеет открытый исходный код, разработчики по всему миру могут вносить свой вклад в разработку дополнительных модулей, что очень полезно для научных приложений, использующих SciPy.

Установка библиотеки SciPy

Мы обсудим некоторые основные функции и важные особенности SciPy, но перед установкой SciPy. Мы можем установить пакеты SciPy, просто используя pip, выполните следующую команду в терминале (добавьте sudo, если необходимо):

Чтобы установить этот пакет с помощью conda run:

conda install -c anaconda scipy

Импорт

Чтобы начать использовать Scipy в наших проектах python, мы просто импортируем Scipy как:

Взаимодействие с Numpy

Как мы уже знаем, SciPy построен на NumPy, поэтому для всех основных нужд мы можем использовать сами функции NumPy:

Функции из numpy и numpy.lib.scimath также содержатся в SciPy, но рекомендуется использовать их напрямую, а не проходить через SciPy в этом случае.

Работа с polynomial

В SciPy есть два способа работы с polynomial. Первый использует класс poly1d. Этот класс принимает коэффициенты или корни для инициализации и формирует полиномиальный объект. Когда мы печатаем этот объект, мы видим, что он напечатан, как polynomial. Давайте посмотрим на пример кода:

from numpy import poly1d # We'll use some functions from numpy remember!! # Creating a simple polynomial object using coefficients somePolynomial = poly1d([1,2,3]) # Printing the result # Notice how easy it is to read the polynomial this way print(somePolynomial) # Let's perform some manipulations print("\nSquaring the polynomial: \n") print(somePolynomial* somePolynomial) #How about integration, we just have to call a function # We just have to pass a constant say 3 print("\nIntegrating the polynomial: \n") print(somePolynomial.integ(k=3)) #We can also find derivatives in similar way print("\nFinding derivative of the polynomial: \n") print(somePolynomial.deriv()) # We can also solve the polynomial for some value, # let's try to solve it for 2 print("\nSolving the polynomial for 2: \n") print(somePolynomial(2))

Пример работы с polynomial

Другой способ работы с polynomial – использовать массив коэффициентов. Существуют функции, доступные для выполнения операций с polynomial, представленными в виде последовательностей, первый метод выглядит намного проще в использовании и дает вывод в удобочитаемой форме, поэтому я предпочитаю первый для примера.

Читайте также:  Php email form with checkboxes

Линейная алгебра

SciPy обладает очень быстрыми возможностями линейной алгебры, поскольку он построен с использованием библиотек ATLAS LAPACK и BLAS. Библиотеки доступны даже для использования, если вам нужна более высокая скорость, но в этом случае вам придется копнуть глубже.

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

Давайте посмотрим на процедуру линейной алгебры на примере. Мы попытаемся решить систему линейной алгебры, что легко сделать с помощью команды scipy linalg.solve.

Этот метод ожидает входную матрицу и вектор правой части:

# Import required modules/ libraries import numpy as np from scipy import linalg # We are trying to solve a linear algebra system which can be given as: # 1x + 2y =5 # 3x + 4y =6 # Create input array A= np.array([[1,2],[3,4]]) # Solution Array B= np.array([[5],[6]]) # Solve the linear algebra X= linalg.solve(A,B) # Print results print(X) # Checking Results print("\n Checking results, following vector should be all zeros") print(A.dot(X)-B)

Пример составляющей вектора выхода

Интеграция SciPy

Подпакет интеграции scipy предоставляет различные методы интеграции. Мы можем посмотреть на них, просто набрав:

Попробуем интегрировать лямбда функцию в скрипт:

# Import required packages from scipy import integrate # Using quad as we can see in list quad is used for simple integration # arg1: A lambda function which returns x squared for every x # We'll be integrating this function # arg2: lower limit # arg3: upper limit result= integrate.quad(lambda x: x**2, 0,3) print(result)

Пример составляющей интеграции

Преобразование Fourier

Анализ Fourier помогает нам выразить функцию, как сумму периодических компонентов и восстановить сигнал из этих компонентов.

Давайте посмотрим на простой пример преобразования Fourier. Мы будем строить сумму двух синусов:

# Import Fast Fourier Transformation requirements from scipy.fftpack import fft import numpy as np # Number of sample points N = 600 # sample spacing T = 1.0 / 800.0 x = np.linspace(0.0, N*T, N) y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x) yf = fft(y) xf = np.linspace(0.0, 1.0/(2.0*T), N//2) # matplotlib for plotting purposes import matplotlib.pyplot as plt plt.plot(xf, 2.0/N * np.abs(yf[0:N//2])) plt.grid() plt.show()

Графическая составляющая Фурье

Специальные функции

В специальном подпакете SciPy есть определения множества функций математической физики. Доступны следующие функции: эри, Бессель, бета, эллиптическая, гамма, гипергеометрическая, Кельвина, Матье, параболический цилиндр, сфероидальная волна и струве. Давайте посмотрим на функцию Бесселя.

Читайте также:  Lambda function array python

Функции Бесселя – это семейство решений дифференциального уравнения Бесселя с вещественным или комплексным порядком альфа.

Давайте лучше рассмотрим это на примере, пример представляет собой круглый барабан, закрепленный на краю:

# Import special package from scipy import special import numpy as np def drumhead_height(n, k, distance, angle, t): kth_zero = special.jn_zeros(n, k)[-1] return np.cos(t) * np.cos(n*angle) * special.jn(n, distance*kth_zero) theta = np.r_[0:2*np.pi:50j] radius = np.r_[0:1:50j] x = np.array([r * np.cos(theta) for r in radius]) y = np.array([r * np.sin(theta) for r in radius]) z = np.array([drumhead_height(1, 1, r, theta, 0.5) for r in radius]) # Plot the results for visualization import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure() ax = Axes3D(fig) ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()

Пример графической составляющей Бесселя

Некоторые функции, такие как функция бинарной энтропии, функция шага Хевисайда и функция линейного изменения, легко реализовать с помощью существующих функций NumPy и SciPy и, следовательно, не включены в этот пакет.

Вывод

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

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

Источник

SciPy User Guide#

SciPy is a collection of mathematical algorithms and convenience functions built on NumPy . It adds significant power to Python by providing the user with high-level commands and classes for manipulating and visualizing data.

Subpackages#

SciPy is organized into subpackages covering different scientific computing domains. These are summarized in the following table:

Physical and mathematical constants

Fast Fourier Transform routines

Integration and ordinary differential equation solvers

Interpolation and smoothing splines

N-dimensional image processing

Orthogonal distance regression

Optimization and root-finding routines

Sparse matrices and associated routines

Spatial data structures and algorithms

Statistical distributions and functions

SciPy subpackages need to be imported separately, for example:

>>> from scipy import linalg, optimize 

Below, you can find the complete user guide organized by subpackages.

  • Special functions ( scipy.special )
  • Integration ( scipy.integrate )
  • Optimization ( scipy.optimize )
  • Interpolation ( scipy.interpolate )
  • Fourier Transforms ( scipy.fft )
  • Signal Processing ( scipy.signal )
  • Linear Algebra ( scipy.linalg )
  • Sparse Arrays ( scipy.sparse )
  • Sparse eigenvalue problems with ARPACK
  • Compressed Sparse Graph Routines ( scipy.sparse.csgraph )
  • Spatial data structures and algorithms ( scipy.spatial )
  • Statistics ( scipy.stats )
  • Multidimensional image processing ( scipy.ndimage )
  • File IO ( scipy.io )

Executable tutorials#

Below you can also find tutorials in MyST Markdown format. These can be opened as Jupyter Notebooks with the help of the Jupytext extension.

Источник

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