SymPy

SymPy
Developer(s)SymPy Development Team
Initial release2007; 17 years ago (2007)
Stable release
1.12[1] / 10 May 2023; 19 months ago (2023-05-10)
Repository
Written inPython
Operating systemCross-platform
TypeComputer algebra system
License3-clause BSD
Websitewww.sympy.org Edit this on Wikidata

SymPy is an open-source Python library for symbolic computation. It provides computer algebra capabilities either as a standalone application, as a library to other applications, or live on the web as SymPy Live[2] or SymPy Gamma.[3] SymPy is simple to install and to inspect because it is written entirely in Python with few dependencies.[4][5][6] This ease of access combined with a simple and extensible code base in a well known language make SymPy a computer algebra system with a relatively low barrier to entry.

SymPy includes features ranging from basic symbolic arithmetic to calculus, algebra, discrete mathematics, and quantum physics. It is capable of formatting the result of the computations as LaTeX code.[4][5]

SymPy is free software and is licensed under the 3-clause BSD. The lead developers are Ondřej Čertík and Aaron Meurer. It was started in 2005 by Ondřej Čertík.[7]

Features

The SymPy library is split into a core with many optional modules.

Currently, the core of SymPy has around 260,000 lines of code[8] (it also includes a comprehensive set of self-tests: over 100,000 lines in 350 files as of version 0.7.5), and its capabilities include:[4][5][9][10][11]

Core capabilities

Polynomials

Calculus

Solving equations

Discrete math

Matrices

Geometry

Plotting

Note, plotting requires the external Matplotlib or Pyglet module.

  • Coordinate models
  • Plotting Geometric Entities
  • 2D and 3D
  • Interactive interface
  • Colors
  • Animations

Physics

Statistics

Combinatorics

Printing

  • SageMath: an open source alternative to Mathematica, Maple, MATLAB, and Magma (SymPy is included in Sage)
  • SymEngine: a rewriting of SymPy's core in C++, in order to increase its performance. Work is currently in progress[as of?] to make SymEngine the underlying engine of Sage too.[14]
  • mpmath: a Python library for arbitrary-precision floating-point arithmetic[15]
  • SympyCore: another Python computer algebra system[16]
  • SfePy: Software for solving systems of coupled partial differential equations (PDEs) by the finite element method in 1D, 2D and 3D.[17]
  • GAlgebra: Geometric algebra module (previously sympy.galgebra).[18]
  • Quameon: Quantum Monte Carlo in Python.[19]
  • Lcapy: Experimental Python package for teaching linear circuit analysis.[20]
  • LaTeX Expression project: Easy LaTeX typesetting of algebraic expressions in symbolic form with automatic substitution and result computation.[21]
  • Symbolic statistical modeling: Adding statistical operations to complex physical models.[22]
  • Diofant: a fork of SymPy, started by Sergey B Kirpichev[23]

Dependencies

Since version 1.0, SymPy has the mpmath package as a dependency.

There are several optional dependencies that can enhance its capabilities:

  • gmpy: If gmpy is installed, SymPy's polynomial module will automatically use it for faster ground types. This can provide a several times boost in performance of certain operations.
  • matplotlib: If matplotlib is installed, SymPy can use it for plotting.
  • Pyglet: Alternative plotting package.

Usage examples

Pretty-printing

Sympy allows outputs to be formatted into a more appealing format through the pprint function. Alternatively, the init_printing() method will enable pretty-printing, so pprint need not be called. Pretty-printing will use unicode symbols when available in the current environment, otherwise it will fall back to ASCII characters.

>>> from sympy import pprint, init_printing, Symbol, sin, cos, exp, sqrt, series, Integral, Function
>>>
>>> x = Symbol("x")
>>> y = Symbol("y")
>>> f = Function("f")
>>> # pprint will default to unicode if available
>>> pprint(x ** exp(x))
 ⎛ x⎞
 ⎝ℯ ⎠
x   
>>> # An output without unicode
>>> pprint(Integral(f(x), x), use_unicode=False)
  /       
 |        
 | f(x) dx
 |        
/        
>>> # Compare with same expression but this time unicode is enabled
>>> pprint(Integral(f(x), x), use_unicode=True)

⎮ f(x) dx

>>> # Alternatively, you can call init_printing() once and pretty-print without the pprint function.
>>> init_printing()
>>> sqrt(sqrt(exp(x)))
   ____
4 ╱  x 
╲╱  ℯ  
>>> (1/cos(x)).series(x, 0, 10)
     2      4       6        8         
    x    5⋅x    61⋅x    277⋅x     ⎛ 10⎞
1 + ── + ──── + ───── + ────── + O⎝x  ⎠
    2     24     720     8064

Expansion

>>> from sympy import init_printing, Symbol, expand
>>> init_printing()
>>>
>>> a = Symbol("a")
>>> b = Symbol("b")
>>> e = (a + b) ** 3
>>> e
(a + b)³
>>> e.expand()
a³ + 3⋅a²⋅b + 3⋅a⋅b²  + b³

Arbitrary-precision example

>>> from sympy import Rational, pprint
>>> e = 2**50 / Rational(10) ** 50
>>> pprint(e)
1/88817841970012523233890533447265625

Differentiation

>>> from sympy import init_printing, symbols, ln, diff
>>> init_printing()
>>> x, y = symbols("x y")
>>> f = x**2 / y + 2 * x - ln(y)
>>> diff(f, x)
 2⋅x    
 ─── + 2
  y 
>>> diff(f, y)
    2    
   x    1
 - ── - ─
    2   y
   y
>>> diff(diff(f, x), y)
 -2⋅x
 ────
   2 
  y

Plotting

Output of the plotting example
>>> from sympy import symbols, cos
>>> from sympy.plotting import plot3d
>>> x, y = symbols("x y")
>>> plot3d(cos(x * 3) * cos(y * 5) - y, (x, -1, 1), (y, -1, 1))
<sympy.plotting.plot.Plot object at 0x3b6d0d0>

Limits

>>> from sympy import init_printing, Symbol, limit, sqrt, oo
>>> init_printing()
>>> 
>>> x = Symbol("x")
>>> limit(sqrt(x**2 - 5 * x + 6) - x, x, oo)
-5/2
>>> limit(x * (sqrt(x**2 + 1) - x), x, oo)
1/2
>>> limit(1 / x**2, x, 0)

>>> limit(((x - 1) / (x + 1)) ** x, x, oo)
 -2

Differential equations

>>> from sympy import init_printing, Symbol, Function, Eq, dsolve, sin, diff
>>> init_printing()
>>>
>>> x = Symbol("x")
>>> f = Function("f")
>>>
>>> eq = Eq(f(x).diff(x), f(x))
>>> eq
d              
──(f(x)) = f(x)
dx         
>>>    
>>> dsolve(eq, f(x))
           x
f(x) = C₁⋅ℯ

>>>
>>> eq = Eq(x**2 * f(x).diff(x), -3 * x * f(x) + sin(x) / x)
>>> eq
 2 d                      sin(x)
x ⋅──(f(x)) = -3⋅x⋅f(x) + ──────
   dx                       x   
>>>
>>> dsolve(eq, f(x))
       C₁ - cos(x)
f(x) = ───────────   

Integration

>>> from sympy import init_printing, integrate, Symbol, exp, cos, erf
>>> init_printing()
>>> x = Symbol("x")
>>> # Polynomial Function
>>> f = x**2 + x + 1
>>> f
 2        
x  + x + 1
>>> integrate(f, x)
 3    2    
x    x     
── + ── + x
3    2     
>>> # Rational Function
>>> f = x / (x**2 + 2 * x + 1)
>>> f
     x      
────────────
 2          
x  + 2⋅x + 1

>>> integrate(f, x)
               1  
log(x + 1) + ─────
             x + 1
>>> # Exponential-polynomial functions
>>> f = x**2 * exp(x) * cos(x)
>>> f
 2  x       
x ⋅ℯ ⋅cos(x)
>>> integrate(f, x)
 2  x           2  x                         x           x       
x ⋅ℯ ⋅sin(x)   x ⋅ℯ ⋅cos(x)      x          ℯ ⋅sin(x)   ℯ ⋅cos(x)
──────────── + ──────────── - x⋅ℯ ⋅sin(x) + ───────── - ─────────
     2              2                           2           2    
>>> # A non-elementary integral
>>> f = exp(-(x**2)) * erf(x)
>>> f
   2       
 -x        
ℯ   ⋅erf(x)
>>> integrate(f, x)

  ___    2   
╲╱ π ⋅erf (x)
─────────────
      4

Series

>>> from sympy import Symbol, cos, sin, pprint
>>> x = Symbol("x")
>>> e = 1 / cos(x)
>>> pprint(e)
  1   
──────
cos(x)
>>> pprint(e.series(x, 0, 10))
     2      4       6        8         
    x    5⋅x    61⋅x    277⋅x     ⎛ 10⎞
1 + ── + ──── + ───── + ────── + O⎝x  ⎠
    2     24     720     8064          
>>> e = 1/sin(x)
>>> pprint(e)
  1   
──────
sin(x)
>>> pprint(e.series(x, 0, 4))
           3        
1   x   7⋅x     ⎛ 4⎞
─ + ─ + ──── + O⎝x ⎠
x   6   360

Logical reasoning

Example 1

>>> from sympy import *
>>> x = Symbol("x")
>>> y = Symbol("y")
>>> facts = Q.positive(x), Q.positive(y)
>>> with assuming(*facts):
...     print(ask(Q.positive(2 * x + y)))
True

Example 2

>>> from sympy import *
>>> x = Symbol("x")
>>> # Assumption about x
>>> fact = [Q.prime(x)]
>>> with assuming(*fact):
...     print(ask(Q.rational(1 / x)))
True

See also

References

  1. ^ "Releases - sympy/sympy". Retrieved 6 September 2022 – via GitHub.
  2. ^ "SymPy Live". live.sympy.org. Retrieved 2021-08-25.
  3. ^ "SymPy Gamma". www.sympygamma.com. Retrieved 2021-08-25.
  4. ^ a b c "SymPy homepage". Retrieved 2014-10-13.
  5. ^ a b c Joyner, David; Čertík, Ondřej; Meurer, Aaron; Granger, Brian E. (2012). "Open source computer algebra systems: SymPy". ACM Communications in Computer Algebra. 45 (3/4): 225–234. doi:10.1145/2110170.2110185. S2CID 44862851.
  6. ^ Meurer, Aaron; Smith, Christopher P.; Paprocki, Mateusz; Čertík, Ondřej; Kirpichev, Sergey B.; Rocklin, Matthew; Kumar, AMiT; Ivanov, Sergiu; Moore, Jason K. (2017-01-02). "SymPy: symbolic computing in Python" (PDF). PeerJ Computer Science. 3: e103. doi:10.7717/peerj-cs.103. ISSN 2376-5992.
  7. ^ "SymPy vs. Mathematica · sympy/Sympy Wiki". GitHub.
  8. ^ "Sympy project statistics on Open HUB". Retrieved 2014-10-13.
  9. ^ Gede, Gilbert; Peterson, Dale L.; Nanjangud, Angadh; Moore, Jason K.; Hubbard, Mont (2013). Constrained multibody dynamics with Python: From symbolic equation generation to publication. ASME 2013 International Design Engineering Technical Conferences and Computers and Information in Engineering Conference. American Society of Mechanical Engineers. pp. V07BT10A051. doi:10.1115/DETC2013-13470. ISBN 978-0-7918-5597-3.
  10. ^ Rocklin, Matthew; Terrel, Andy (2012). "Symbolic Statistics with SymPy". Computing in Science & Engineering. 14 (3): 88–93. Bibcode:2012CSE....14c..88R. doi:10.1109/MCSE.2012.56. S2CID 18307629.
  11. ^ Asif, Mushtaq; Olaussen, Kåre (2014). "Automatic code generator for higher order integrators". Computer Physics Communications. 185 (5): 1461–1472. arXiv:1310.2111. Bibcode:2014CoPhC.185.1461M. doi:10.1016/j.cpc.2014.01.012. S2CID 42041635.
  12. ^ "Assumptions Module — SymPy 1.4 documentation". docs.sympy.org. Retrieved 2019-07-05.
  13. ^ "Continuum Mechanics — SymPy 1.4 documentation". docs.sympy.org. Retrieved 2019-07-05.
  14. ^ "GitHub - symengine/symengine: SymEngine is a fast symbolic manipulation library, written in C++". GitHub. Retrieved 2021-08-25.
  15. ^ "mpmath - Python library for arbitrary-precision floating-point arithmetic". mpmath.org. Retrieved 2021-08-25.
  16. ^ "GitHub - pearu/sympycore: Automatically exported from code.google.com/p/sympycore". GitHub. January 2021. Retrieved 2021-08-25.
  17. ^ Developers, SfePy. "SfePy: Simple Finite Elements in Python — SfePy version: 2021.2+git.13ca95f1 documentation". sfepy.org. Retrieved 2021-08-25.
  18. ^ "GitHub - pygae/galgebra: Symbolic Geometric Algebra/Calculus package for SymPy". GitHub. Retrieved 2021-08-25.
  19. ^ "Quameon - Quantum Monte Carlo in Python". quameon.sourceforge.net. Retrieved 2021-08-25.
  20. ^ "Welcome to Lcapy's documentation! — Lcapy 0.76 documentation". 2021-01-16. Archived from the original on 2021-01-16. Retrieved 2021-08-25.
  21. ^ "LaTeX Expression project documentation — LaTeX Expression 0.3.dev documentation". mech.fsv.cvut.cz. Retrieved 2021-08-25.
  22. ^ "Symbolic Statistics with SymPy". ResearchGate. Retrieved 2021-08-25.
  23. ^ "Diofant's documentation — Diofant 0.13.0a4.dev13+g8c5685115 documentation". diofant.readthedocs.io. Retrieved 2021-08-25.

Read other articles:

Tautiška GiesmeB. Indonesia: Himne NasionalLagu kebangsaan  LituaniaPenulis lirikVincas Kudirka, 1898KomponisVincas Kudirka, 1898Penggunaan1919 (digunakan kembali tahun 1988)Sampel audioberkasbantuan Vincas Kudirka Tautiška giesmė adalah lagu kebangsaan Lituania, lagu tersebut diciptakan pada tahun 1898 oleh Vincas Kudirka dan diresmikan penggunaannya pada tahun 1919. Penggunaannya sempat terhenti selama puluhan tahun saat Lituania menjadi salah satu republik Soviet, dan lagu ter...

 

Ini adalah nama Batak Toba, marganya adalah Hutabarat. Martin HutabaratAnggota Dewan Perwakilan RakyatMasa jabatan1 Oktober 2009 – 1 Oktober 2019Grup parlemenGerindraDaerah pemilihanSumatera Utara IIIMasa jabatan1 Oktober 1987 – 1 Oktober 1992Grup parlemenKarya PembangunanDaerah pemilihanJawa Tengah Informasi pribadiLahirMartin Hamonangan Hutabarat26 November 1951 (umur 72)Pematangsiantar, Sumatera Utara, IndonesiaPartai politikGerindraAfiliasi politiklainnyaGolkar ...

 

Опис файлу Опис Постер до аніме Проєкт К Джерело http://k-project.jpn.com/ Автор зображення GoHands Ліцензія див. нижче Обґрунтування добропорядного використання для статті «K (аніме)» [?] Мета використання в якості основного засобу візуальної ідентифікації у верхній частині ст...

Teluk Aqabah Semenanjung Sinai memisahkan Laut Merah (Red Sea) di bagian utara menjadi Teluk Suez (Gulf of Suez) di sebelah barat (kiri) dan Teluk Aqabah (Gulf of Aqaba), di sebelah timur (kanan). Lokasi Asia Barat Jenis samudra Gulf Sumber utama Laut Merah Daerah aliran Mesir, Israel, Yordania, dan Arab Saudi Panjang maksimum 160 km (99 mi) Lebar maksimum 24 Kedalaman maksimum 1.850 m (6.070 ft) Teluk Aqabah (Arab: خليج العقبة; transliterasi: Khalij al-'Aqab...

 

Lambang Azerbaijan Hukum kebangsaan Azerbaijan mengatur pihak-pihak mana saja yang berhak menjadi warga negara Azerbaijan. Peraturan Peraturan perundangan yang menentukan status kewarganegaraan Azerbaijan ditentukan oleh Undang-Undang Dasar Azerbaijan tahun 1995 dan Undang-Udang Kewarganegaraan Republik Azerbaijan yang disahkan pada 30 September 1998.[1][2][3] Hukum kewarganegaraan Azerbaijan utamanya menerapkan prinsip ius sanguinis.[4] Hukum tersebut juga men...

 

American sprinter Eddie HartPersonal informationFull nameEdward James HartBornApril 24, 1949 (1949-04-24) (age 74)Martinez, California, U.S. Medal record Men's athletics Representing the  United States Olympic Games 1972 Munich 4x100 m relay Edward James Eddie Hart (born April 24, 1949) is an American former track and field sprinter, winner of the gold medal in 4 × 100 m relay race at the 1972 Summer Olympics. Born in Martinez, California, Eddie Hart won the NCAA champion...

この項目「辰巳ジャンクション」は加筆依頼に出されており、内容をより充実させるために次の点に関する加筆が求められています。加筆の要点 - 1.Infoboxの設置2.その他関連情報(貼付後はWikipedia:加筆依頼のページに依頼内容を記述してください。記述が無いとタグは除去されます)(2019年8月) この記事は検証可能な参考文献や出典が全く示されていないか、不十分で

 

2nd episode of the 2nd season of Battlestar Galactica Valley of DarknessBattlestar Galactica episodeApollo (Jamie Bamber) faces down a Cylon Centurion.Episode no.Season 2Episode 2Directed byMichael RymerWritten byDavid WeddleBradley ThompsonOriginal air dateJuly 22, 2005 (2005-07-22)Guest appearances Sam Witwer as Crashdown Kate Vernon as Ellen Tigh[a] Alonso Oyarzun as Socinus Kerry Norton as Paramedic Ishay Chris Shields as Cpl. Venner Luciana Carro as Kat Bodie ...

 

Dieser Artikel behandelt den Soziologen Christof Wolf. Zum weiteren Personen siehe Christoph Wolf. Christof Wolf (2019) Christof Wolf (* 1963) ist ein deutscher Soziologe. Seit 1. Juli 2017 ist er Präsident des GESIS – Leibniz-Institut für Sozialwissenschaften in Mannheim und Köln. Wolf studierte Soziologie, Volkswirtschaftslehre, Wirtschafts- und Sozialgeschichte sowie Statistik an der Universität Hamburg. 1996 wurde er an der Universität zu Köln zum Dr. rer. pol. promoviert und habi...

2021 single by BTS Permission to DanceDigital single coverSingle by BTSA-sideButterReleasedJuly 9, 2021 (2021-07-09)GenreDance-popLength3:07Label Big Hit Sony Songwriter(s) Ed Sheeran Johnny McDaid Steve Mac Jenna Andrews Producer(s) Steve Mac Jenna Andrews Stephen Kirk BTS singles chronology Butter (2021) Permission to Dance (2021) My Universe (2021) Music videoPermission to Dance on YouTube Permission to Dance is a song by South Korean boy band BTS. It was released through Bi...

 

Death Ascendant Death Ascendant is an adventure for the 2nd edition of the Advanced Dungeons & Dragons fantasy role-playing game. Plot summary Death Ascendant is an adventure that takes place in the less civilized realm of Darkon, one of the domains of Ravenloft.[1] The player characters come to Nartok, where public hanging and child-branding have become commonplace, and learn that a secret war is happening there between two sets of spies.[1] The characters are warned abou...

 

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (ديسمبر 2018) تسرد هذه الصفحة مقالات حول سلالة حاكمة في مصر القديمة. انظر أيضًا: قائمة الفراعنة - التسلسل الزمني لمصر - ا...

Immigration from the Philippines to Spain Spanish people of Filipino ancestryTotal population200,000 (2018)[1]Including an estimated 37,000 people with Filipino citizenship only.[2]Regions with significant populationsMadrid, Barcelona, Málaga and other urban areasThe following numbers (from 2021) represent Filipinos in Spain with Filipino citizenship only.[2] Community of Madrid16,119 (43.17%) Catalonia11,765 (31.51%) Andalusia2,857 (7.65%) Baleari...

 

Film series Rush HourBlu-ray coverDirected byBrett Ratner (1–3)Screenplay byJim Kouf (1) Ross LaManna (1) Jeff Nathanson (2–3)Story byRoss LaManna (1) Jeff Nathanson (2–3)Based onCharacters createdby Ross LaMannaProduced byRoger Birnbaum Jonathan Glickman Arthur M. Sarkissian Jay Stern Robert Birnbaum Michael PoryesStarringJackie Chan Chris TuckerEdited byMark Helfrich Robert K. Lambert Mark Possy Billy Weber Don ZimmermanMusic byLalo Schifrin Mark Mothersbaugh Ira Hearshen Nile Rodgers...

 

Depuis l'adoption de la Constitution de la Cinquième République française en 1958, dix élections présidentielles ont eu lieu afin d'élire le président de la République. Cette page présente les résultats de ces élections dans la Nièvre. Synthèse des résultats du second tour La Nièvre vote traditionnellement plus à gauche que la France. Elle a en particulier placé François Mitterrand et Ségolène Royal en tête au second tour lors des élections de 1974 et 2007. En 2012, Fran...

American wrestling promotion House of HardcoreAcronymHOHFoundedOctober 6, 2012StyleProfessional wrestlingHardcore wrestlingFounder(s)Tommy DreamerOwner(s)Extreme Original Productions, Inc.Websitehouseofhardcore.net House of Hardcore (HOH) is an American wrestling promotion founded by professional wrestler Tommy Dreamer. Its slogan is No Politics, No BS, Just Wrestling. In its history, HOH has run events in twelve states and three countries. History House of Hardcore founder Tommy Dreamer, 201...

 

Public university in Batman, Turkey You can help expand this article with text translated from the corresponding article in Turkish. (August 2018) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Consider adding ...

 

Sister Sue MostellerCSJPersonalBorn1933ReligionRoman CatholicAlma materUniversity of Toronto Sue Mosteller CSJ, OC (born 1933) is a writer and teacher who lives in Toronto, Ontario, Canada. Biography Mosteller is a Sister of St. Joseph of Toronto. She first traveled from Ohio to board with the community and later entered the order after thriving under their supervision.[1][2] She holds a degree in English from the University of Toronto and taught in schools in British Col...

2015 Ugandan filmA Dog StoryOfficial posterDirected byDavidson MugumeScreenplay byDoreen MirembeProduced byDoreen MirembeStarring Doreen Mirembe Michael Wawuyo Jr. OpipoOpolot ZziwaJaubarl CinematographyDoreen MirembeEdited byMonica MugoMusic byMonica MugoProductioncompanyAmani HouseDistributed byAmani HouseRelease date June 2015 (2015-06) (Kampala Festival) Running time19 minutesCountryUgandaLanguageEnglish A Dog Story is a Ugandan short film about Atim, a young woman who tries...

 

Siberian Turkic language TuvanТыва дылTıva dılNative toRussia, Mongolia, ChinaRegionTuvaEthnicityTuvansNative speakers240,000 (2012)[1]Language familyTurkic Common TurkicSiberian TurkicSouth SiberianSayan TurkicSteppe Sayan Turkic[2][notes 1]TuvanWriting systemCyrillic scriptOfficial statusOfficial language in Russia TuvaLanguage codesISO 639-2tyvISO 639-3tyvGlottologtuvi1240  Tuviniantodj1234  TodjaELPTuva Tuha[3 ...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!