42 ms·
SymPy: Symbolic Mathematics in Python
- ivansavz 3y agoSymPy is awesome indeed! I've been using it as a teaching tool for many years. IMHO, it's the best option as compared to Mathematica/Maple/etc. because the API functions match exactly the verbs students use when learning math (solve, expand, factor, etc.). Here is a little tutorial for anyone looking to get started: https://minireference.com/static/tutorials/sympy_tutorial.pdf https://minireference.com/static/tutorials/sympy_tutorial.pd... Also available in runnable notebook format: https://colab.research.google.com/github/minireference/sympytut_notebooks/blob/master/notebooks/Intro.ipynb https://colab.research.google.com/github/minireference/sympy... (read only = http://nbviewer.ipython.org/github/minireference/sympytut_notebooks/blob/master/notebooks/Intro.ipynb http://nbviewer.ipython.org/github/minireference/sympytut_no... ) Last but not least, for anyone interested in trying SymPy without installing anything, there is always the SymPy live shell: https://live.sympy.org/ https://live.sympy.org/ (runs Python + SymPy in the browser thanks to WebAssembly)
- bloaf 3y agoThe biggest drawback of SymPy is the need to pre-define all your symbols. That makes it more difficult to handle scenarios where you're taking formulas as input because you either need to parse the equation yourself to figure out what variables were used, or have the user manually supply the symbols.
- staplung 3y agoMight not handle exactly the difficulties you're having but you can do `from sympy.abc import *`. This will create symbols for pretty much all letters (lower and upper) as well as a bunch of greek symbols (but written out, e.g. "delta").
- bloaf 3y agoImagine a scenario where you've got a database of timeseries data, say stock prices. Each price trend is identified by the stock ticker, and your users have an excel spreadsheet of several thousand equations in terms of the stock ticker (e.g. (AAPL-TSLA)/AAPL) and you want to calculate the derivative of each one of those equations with respect to each ticker symbol in each equation before pulling the data. Obviously you could find a list of every ticker symbol and create a few thousand symbols before parsing, but you don't always have the luxury of a complete/up-to-date list, or doing so might create too many symbol objects and cause performance problems.
- rav 3y agoThere `isympy -I`, which runs an IPython REPL with a preprocessor that changes unknown variables into sympy symbols, but that only helps you for interactive usage.
- throw4023042q0 3y agoI usually run a pre-processing step to identify all needed symbols and then create them dynamically. I find sympy works fine for such on-the-fly workflow. My experience is with predictive statistics and financial models.
- 3abiton 3y agoGlad to see some tutorials!
- mbustamanter 3y agoSymbolic mathematics is severely underexplored in undergraduate studies, and the little exposure I had was generally tied to proprietary software such as Mathematica and MATLAB. I learned to use it as an imperfect extension of pen-and-paper thinking, and source code for more advanced stuff gets shaky the deeper into abstraction one goes. For example, I work in a field of mathematics/engineering that requires heavy use of tensor calculations. My go-to tool for that is Maxima, however, it has limited and cumbersome packages for it (see [0]). Now for more sophisticated calculations I resort to SymPy, not necessarily because of better handling of symbolics but because of the abstractions that Python already has. Maybe someday I'll get to read the Principles by Norvig and fix Maxima to suit my needs (if anyone has better references to read Maxima's source code/implementation of tensor computations/symbolic (tensor, geometric) algebra I would be grateful to know). [0] https://arxiv.org/pdf/cs/0503073.pdf https://arxiv.org/pdf/cs/0503073.pdf
- Ginger-Pickles 3y agoFor great justice, does anyone know of any applications (other than Maple) that support WYSIWYG typeset input (not output) like Maple does? As far as I know, Wolfram/Mathematica, LaTex, SymPy, Jupyter, Sage etc all rely on typewriter text for composing and inputting math. For this (and only this) reason, Maple is the only application that ever resonated with me, because input may be written in the same form it's written by hand, and it's baffling this capability isn't more commonplace. Is this a barrier to anyone else?
- unicas 3y agoThere's a lot of them. In principle every CAS that has a TeXmacs interface can do it (FriCAS, Maxima, Reduce ... oo). E.g. https://news.ycombinator.com/item?id=19465270 https://news.ycombinator.com/item?id=19465270.
- cashsterling 3y agoMathCad works this way also, IIRC.
- jxramos 3y ago
- manojlds 3y agoAs an aside - I have a bunch of logical expressions and I need to see if they are mutually exclusive. As in, if one is true given some combination of the variables, none of the other expressions must be true for the same combination. For example Country="US" and Type="Sales" is not exclusive with Type in ("Sales", "Purchase") What would be an approach to solving this?
- pizza 3y agoMaybe prolog (or other logic programming language) or z3 (or other SAT solver)?
- jlokier 3y agoIf your logical expressions aren't too strange, and there aren't too many, that's well suited to an SMT solver, such as Z3. You might, for example, create a new logical expression for each pair of your original expressions, joining each pair with AND, and then join those AND pairs with OR. Then ask the SMT solver to generate an unsatisfiability proof.
- manojlds 3y agoThanks the suggestion was very useful and I am even close to having a prototype. Z3 is cool!
- chpatrick 3y agoSuper useful package. I hate working out maths by hand so I usually use it whenever possible.
- maxboone 3y agoUse this extensively when doing linear algebra and when I'm too lazy to do it by hand, very useful tool indeed! Especially the print(latex(...)) command has helped a ton to write large matrices in notes for courses.
- LuciBb 3y ago[dead]
- whizzter 3y agoIt's a seriously cool way to solve problems, never used it but discovered that the winner of one of the Advent of Code days in 22 or 23 basically just set up equations with SymPy and let it solve everything beating out the usual cadre of "fast-hackers" in the top.
- WanderPanda 3y agoI wish Symbloics.jl ‘s rewriting/simplification rules were as good as SymPy’s/Matlab’s. The composability of the Julia ecosystem would be really great for symbolic math
- bowsamic 3y agoUnfortunately I always found it quite slow compared to Mathematica
- verdverm 3y agoSymPy was instrumental to my PhD implementation, mainly for simplifying math expressions. Nothing was even close at the time https://github.com/verdverm/pypge https://github.com/verdverm/pypge
- rpep 3y agoI used it for this during my PhD: https://github.com/rpep/fmmgen https://github.com/rpep/fmmgen and found it very powerful. I have in the past used Mathematica, which I did think was more powerful for symbolic math to be honest, but it had the downside of not being free...!
- deleted 3y ago[deleted]
- hackerbrother 3y agoI used this to calculate answers for calculus worksheets in LaTeX format in grad school.
- tverbeure 3y agoWhen you ask ChatGPT 4.0 symbolic mathematical questions, it uses sympy under the hood, and you can get the script that generated the answer. It's great.
- SPACECADET3D 3y agoI started work on a new computer algebra system in Rust that has Python bindings: https://symbolica.io/ https://symbolica.io/ For many operations it is orders of magnitude faster than sympy.
- westurner 3y agoSymPy: https://en.wikipedia.org/wiki/SymPy https://en.wikipedia.org/wiki/SymPy - "How should logarithms be taught?" [with python and SymPy] https://news.ycombinator.com/item?id=28518565#28519356 https://news.ycombinator.com/item?id=28518565#28519356 From "SymPy - a Python library for symbolic mathematics" (2020) https://news.ycombinator.com/item?id=23767513 https://news.ycombinator.com/item?id=23767513 : > NumPy for Matlab users: https://numpy.org/doc/stable/user/numpy-for-matlab-users.html https://numpy.org/doc/stable/user/numpy-for-matlab-users.htm... > SymPy vs Matlab: https://github.com/sympy/sympy/wiki/SymPy-vs.-Matlab https://github.com/sympy/sympy/wiki/SymPy-vs.-Matlab
- lemursage 3y agoFor a numerical "physicist" (yes, the quotation marks are indispensable), Sympy was somewhat of a godsend to me. Great for prototyping even more advanced models before optimising them later on in C++. I haven't used Mathematica much, but I have a feeling that it's still more symbolically powerful (or requires less wrangling) than SymPy? I'd appreciate if somebody with more experience in Mathematica could lay it out flat for me if that's the case.
- qsort 3y agoStephen Wolfram notwithstanding, Mathematica is still far ahead of most alternatives as a CAS. Maple is good on some integrals. Their downsides are that their languages are not very well suited as general purpose languages, many times the algebraic manipulations you have to perform aren't that complicated and you'd rather work in a "real" language. Yet another case where python isn't the best in class but still workable and able to benefit from its vast general-purpose ecosystem.
- llm_trw 3y agoSagemath is a python library that has more capabilities than Mathematica. If you want to do real symbolic computation in python Sagemath is the only way to do it. That said sympy is quite a cool little library for learning.
- qsort 3y agoSagemath isn't a python library, it's a collection of packages (of which sympy is one) under a common interface. It is indeed what you would use if you wanted to do real symbolic computation in python, but it's not at the level of Mathematica or Maple. Look, we all love open source, but we aren't doing anybody any favors by pretending the open source alternative is better when it isn't. I would encourage anyone whose needs are satisfied by sympy/sagemath to opt for the open alternative, but the question was whether or not Mathematica as of now, early 2024, is better. The unfortunate reality is that it is.
- 3y ago
- gunalx 3y agoSympy is amazing, but i kinda fail to see whats news about it as its oldest commit is 14 years ago.
- 3pt14159 3y agoI've never heard of it and I've been using Python since around 2008, including mathematical stuff like Scipy / Numpy. Sometimes people like to find old stuff and share it since it's new to others.
- kragen 3y agopython3 didn't exist 14 years ago, and neither did the ipython notebook, and sympy has code specific to both. /usr/share/doc/python3-sympy/changelog.Debian.gz on my laptop shows six new versions in 02022, three new versions in 02021, and eleven new versions in 02020. is it possible you're looking at an outdated mirror of sympy? oh, i see you said 'oldest commit'. well, what's news about sympy is the 14 years of commits since then https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html says > On-Topic: Anything that good hackers would find interesting. That includes more than hacking and startups. If you had to reduce it to a sentence, the answer might be: anything that gratifies one's intellectual curiosity. and, though it's not even stated, it includes more than news
- zenburnmyface 3y agoOldest commit was from today: https://github.com/sympy/sympy https://github.com/sympy/sympy Where are you getting 14 years from?
- QuadmasterXLII 3y agoSymPy gets the job done. I typically use it in the SageMath combo library, is that still the way to go or has SymPy advanced to the point that I should be using it on its own?
- Aardwolf 3y agoSageMath looks cool, but the fact that it's a combination of many different existing tools all with their own syntax, and feature overlap, scares me off a bit since it seems like how you do things wouldn't be very internally consistent How does this aspect work out in practice?
- QuadmasterXLII 3y agoIn practice it feels like working with three libraries in a trenchcoat. However, as of five years ago it was totally worth it: the killer app for Sage was that it let you describe a problem in SymPy where you have the full power of python for loops, library support, visualization etc; and then solve it with Maxima's more powerful symbolic calculus tools. I'm not up to speed on whether SymPy has caught up to Maxima in terms of being able to solve integrals, differential equations, etc.
- idanp 3y agoI use SymPy as my calculator with https://github.com/idanpa/calcpy https://github.com/idanpa/calcpy
- Hugsun 3y agoThis looks perfect. I've found native sympy to be a little cumbersome to use.
- qorrect 3y agoSame here, I've been slogging through with raw sympy this tool looks great. How do I speed up the start time for it - any ideas? Recompile it with PyPy or similar?
- idanp 3y agoI think PyPy usually has slower startup time. Need to try to defer some of the imports to be done in the background, see how good is the outcome. Feel free to open an issue in github.
- throw4023042q0 3y agothis project is AWESOME! cool idea man
- abricq 3y agoWorking in the field of robotics, I often have to write big vectors (usually computed as the result of 3D transformations) and then compute their Jacobian (their derivative with respect to several state-variables), which quickly becomes very nasty equations. I use sympy to (i) compute these big vectors, expressed in a very declarative way, (ii) compute the jacobian and (iii) export the results in C-code, immediately importable in my code case. To illustrate what I mean by "expressing systems of equations in a declarative way", here is a toy-example of how to estimate the position of the a sensor with respect to a robot's center if you have access to a dataset containing robot positions and the sensor positions. The 'naive' approach (it very often works) is to solve an over-constrained system with a gradient-descent. To perform a gradient descent, you need a residual function and its jacobian. Here's how you would do to compute it with Sympy. (Note: you'd just have to define the `transform` and `invert` functions...) # Pose of a sensor in robot frame (to be estimated) xa, ya = symbols("xa, ya") a = Matrix([xa, ya, ta]) # Position of the robot at time t rx, ry, rt = symbols("rx, ry, rt") rk = Matrix([rx, ry, rt]) # Measure of the sensor at time t gx, gy = symbols("gx, gy") gk = Matrix([gx, gy, 0]) # Estimated x (from the measures) estimated_a = transform(invert(rk), gk) # compute the norm of the gk, squared n2_mat = norm2(estimated_a - a) n2 = sympy.collect(sympy.expand(n2_mat[0, 0]), a).simplify() # Compute the jacobian J = n2_mat.jacobian([xa, ya, ta]) # Print what is necessary for Guass-Markov regression print("\n\nres =", n2) print("\nJacobian = ", J)
- exDM69 3y agoI've used SymPy in a very similar way, in my case it was some nasty derivatives that were needed for some orbital mechanics calculations. First write down the equations, then let SymPy do the laborious math part and turn the output into C code. I'm guessing this is why you don't see a lot of SymPy projects in the wild. It was used for some intermediate calculations, and the results were turned into the product's code and the symbolic code is thrown away.
- analog31 3y agoThere might be a better way, but my habit is to include the symbolic code as a comment in the C. I've thanked myself for doing this.
- treprinum 3y agoIs there any GUI for SymPy one could easily use to solve symbolic math like Maple/Maxima/Macsyma?
- BD103 3y agoYou might find SymPy Gamma interesting: https://www.sympygamma.com https://www.sympygamma.com
- westurner 3y agoJupyterLite's default Python-compiled-to-WASM build has NumPy, SciPy, matplotlib, and SymPy installed; so you can do computer algebra with SymPy in a browser tab. https://JupyterLite.rtfd.io/ https://JupyterLite.rtfd.io/ https://github.com/jupyterlite/jupyterlite/tree/main/py/jupyterlite https://github.com/jupyterlite/jupyterlite/tree/main/py/jupy... : > Initial support for interactive visualization libraries such as: altair, bqplot, ipywidgets, matplotlib, and plotly
- notpushkin 3y agoWould Jupyter do the trick? https://jupyter.org/ https://jupyter.org/
- jks 3y agoYou can run it in Jupyter notebook. They have a lightweight implementation of that at https://live.sympy.org/ https://live.sympy.org/ but the closest counterpart to Maple would probably be SageMath, which includes sympy and a lot more. https://www.sagemath.org/ https://www.sagemath.org/
- whyever 3y agoNot sure what you mean with GUI, but you can use it with Jupyter notebooks.
- treprinum 3y agoMore like writing/clicking math (like in MS Word or some LaTeX editors) that is then converted to SymPy instead of writing stuff in Python directly.
- kragen 3y agosympy works really well in jupyter. my own demo notebooks for sympy are https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/sympy-solve.ipynb https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/sympy... (solving a multivariate quadratic with math pretty-printing) https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/tiny-pylab-examples.ipynb https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/tiny-... (my cheatsheet of quick-and-dirty numpy/pylab plots, including some sympy examples) https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/secantmin.ipynb https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/secan... (using sympy to symbolically differentiate an existing python function, which is something you can't usually do, in order to find its minimum in closed form) https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/max-power-divider.ipynb https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/max-p... (some basic circuit analysis with basic calculus with sympy) https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/latex-playground.ipynb https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/latex... (various fiddling around with mathjax formatting and sympy, including some analysis of minsky's circle algorithm from hakmem)
- tableofzero 3y agoThere is a benchmark of Sympy vs Mathematica at https://www.12000.org/my_notes/CAS_integration_tests/reports/summer_2023_Rubi_4_17_3/index.htm https://www.12000.org/my_notes/CAS_integration_tests/reports... The results were Mathematica failed to solve 1,523 problems, Sympy failed to solve 48,529. So it has some catching up to do.
- wiz21c 3y agoAlthough super interesting, the website you mention is only about integrals...
- Affric 3y agoI mean, integrating is one of the operations you might want particular help with. Especially for integrands without elementary function integrals.
- wiz21c 3y agoDo you know why there's such a big difference ? For example, is the way sympy does its job fundamentally flawed ?
- epistasis 3y agoI doubt there's any sort of fundamental flaw in sympy. Getting more and more solutions is mostly about putting in lots of work to tweak the bag of tricks. There is no universal algorithm for solving integrals. As an open source project depending on volunteers (or is it just the one major author?) I am impressed that sympy does as much as it does.
- jcla1 3y ago> There is no universal algorithm for solving integral. Not that I want to dispute this, but depending on what you meant, there is in fact such an algorithm: https://en.wikipedia.org/wiki/Risch_algorithm https://en.wikipedia.org/wiki/Risch_algorithm Though often it is not implemented because it is quite complex (its details covering two thick books) and many of the special cases it covers rarely crop up in the real world, so the effort isn't worth it. The caveat of Risch's algorithm is that it only "works" if the function you are trying to integrate has an elementary antiderivative. Many of the problems that Mathematica can solve (but SymPy fails at) involved special (i.e. non-elementary) functions.
- bluish29 3y agoA decade ago when I was interested in General Relativity I wanted to write a simple program to handle symbolic calculations for Einstein field equations (Starting with metric and calculated affine connections, ricci tensor …etc.). Sympy was an option (better because python was the only language I know well) but I found it hard and actually couldn't make it work. I used mathematica which was new for me but did it in a couple of hours. I expanded it later and used it to calculate a lot of things in a black hole paper I published later. I checked now, and it seems that on this front a lot of development in sympy made it possible that we know how very good libraries built on top of it [1] [2]. There is even now a Jupyter notebook example on schwarzschild metric [3]. [1] https://docs.einsteinpy.org https://docs.einsteinpy.org [2]https://github.com/spacetimeengineer/spacetimeengine https://github.com/spacetimeengineer/spacetimeengine [3] https://github.com/sympy/sympy/blob/master/examples/intermediate/schwarzschild.ipynb https://github.com/sympy/sympy/blob/master/examples/intermed...
- dsqrt 3y agoYou should check out Sage Manifolds [1]. It's built on top of Sage Math, but I think it can also use SymPy as computational engine. [1] https://sagemanifolds.obspm.fr/ https://sagemanifolds.obspm.fr/