# A computer algebra system written in pure Python

### Related tags

Science python science math computer-algebra hacktoberfest

# SymPy

See the AUTHORS file for the list of authors.

And many more people helped on the SymPy mailing list, reported bugs, helped organize SymPy's participation in the Google Summer of Code, the Google Highly Open Participation Contest, Google Code-In, wrote and blogged about SymPy...

License: New BSD License (see the LICENSE file for details) covers all files in the sympy repository unless stated otherwise.

Our mailing list is at https://groups.google.com/forum/?fromgroups#!forum/sympy.

We have community chat at Gitter. Feel free to ask us anything there. We have a very welcoming and helpful community.

To get the git version do

``````\$ git clone git://github.com/sympy/sympy.git
``````

For other options (tarballs, debs, etc.), see https://docs.sympy.org/dev/install.html.

## Documentation and Usage

For in-depth instructions on installation and building the documentation, see the SymPy Documentation Style Guide.

Everything is at:

https://docs.sympy.org/

You can generate everything at the above site in your local copy of SymPy by:

``````\$ cd doc
\$ make html
``````

Then the docs will be in _build/html. If you don't want to read that, here is a short usage:

From this directory, start Python and:

```>>> from sympy import Symbol, cos
>>> x = Symbol('x')
>>> e = 1/cos(x)
>>> print(e.series(x, 0, 10))
1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + 277*x**8/8064 + O(x**10)```

SymPy also comes with a console that is a simple wrapper around the classic python console (or IPython when available) that loads the SymPy namespace and executes some common commands for you.

To start it, issue:

``````\$ bin/isympy
``````

from this directory, if SymPy is not installed or simply:

``````\$ isympy
``````

if SymPy is installed.

## Installation

SymPy has a hard dependency on the mpmath library (version >= 0.19). You should install it first, please refer to the mpmath installation guide:

To install SymPy using PyPI, run the following command:

``````\$ pip install sympy
``````

To install SymPy using Anaconda, run the following command:

``````\$ conda install -c anaconda sympy
``````

To install SymPy from GitHub source, first clone SymPy using `git`:

``````\$ git clone https://github.com/sympy/sympy.git
``````

Then, in the `sympy` repository that you cloned, simply run:

``````\$ python setup.py install
``````

## Contributing

We welcome contributions from anyone, even if you are new to open source. Please read our Introduction to Contributing page and the SymPy Documentation Style Guide. If you are new and looking for some way to contribute, a good place to start is to look at the issues tagged Easy to Fix.

Please note that all participants in this project are expected to follow our Code of Conduct. By participating in this project you agree to abide by its terms. See CODE_OF_CONDUCT.md.

## Tests

To execute all tests, run:

``````\$./setup.py test
``````

in the current directory.

For the more fine-grained running of tests or doctests, use `bin/test` or respectively `bin/doctest`. The master branch is automatically tested by Travis CI.

To test pull requests, use sympy-bot.

## Regenerate Experimental LaTeX Parser/Lexer

The parser and lexer generated with the ANTLR4 toolchain in `sympy/parsing/latex/_antlr` and checked into the repo. Presently, most users should not need to regenerate these files, but if you plan to work on this feature, you will need the `antlr4` command-line tool (and you must ensure that it is in your `PATH`). One way to get it is:

``````\$ conda install -c conda-forge antlr=4.7.2
``````

Alternatively, follow the instructions on the ANTLR website and download the `antlr-4.7.2-complete.jar`. Then export the `CLASSPATH` as instructed and instead of creating `antlr4` as an alias, make it an executable file with the following contents:

```#!/bin/bash
java -jar /usr/local/lib/antlr-4.7.2-complete.jar "\$@"```

After making changes to `sympy/parsing/latex/LaTeX.g4`, run:

``````\$ ./setup.py antlr
``````

## Clean

To clean everything (thus getting the same tree as in the repository):

``````\$ ./setup.py clean
``````

You can also clean things with git using:

``````\$ git clean -Xdf
``````

which will clear everything ignored by `.gitignore`, and:

``````\$ git clean -df
``````

to clear all untracked files. You can revert the most recent changes in git with:

``````\$ git reset --hard
``````

WARNING: The above commands will all clear changes you may have made, and you will lose them forever. Be sure to check things with `git status`, `git diff`, `git clean -Xn` and `git clean -n` before doing any of those.

## Bugs

Our issue tracker is at https://github.com/sympy/sympy/issues. Please report any bugs that you find. Or, even better, fork the repository on GitHub and create a pull request. We welcome all changes, big or small, and we will help you make the pull request if you are new to git (just ask on our mailing list or Gitter Channel). If you further have any queries, you can find answers on Stack Overflow using the sympy tag.

## Brief History

SymPy was started by Ondřej Čertík in 2005, he wrote some code during the summer, then he wrote some more code during summer 2006. In February 2007, Fabian Pedregosa joined the project and helped fixed many things, contributed documentation and made it alive again. 5 students (Mateusz Paprocki, Brian Jorgensen, Jason Gedge, Robert Schwarz, and Chris Wu) improved SymPy incredibly during summer 2007 as part of the Google Summer of Code. Pearu Peterson joined the development during the summer 2007 and he has made SymPy much more competitive by rewriting the core from scratch, that has made it from 10x to 100x faster. Jurjen N.E. Bos has contributed pretty-printing and other patches. Fredrik Johansson has written mpmath and contributed a lot of patches.

SymPy has participated in every Google Summer of Code since 2007. You can see https://github.com/sympy/sympy/wiki#google-summer-of-code for full details. Each year has improved SymPy by bounds. Most of SymPy's development has come from Google Summer of Code students.

In 2011, Ondřej Čertík stepped down as lead developer, with Aaron Meurer, who also started as a Google Summer of Code student, taking his place. Ondřej Čertík is still active in the community but is too busy with work and family to play a lead development role.

Since then, a lot more people have joined the development and some people have also left. You can see the full list in doc/src/aboutus.rst, or online at:

The git history goes back to 2007 when development moved from svn to hg. To see the history before that point, look at https://github.com/sympy/sympy-old.

You can use git to see the biggest developers. The command:

``````\$ git shortlog -ns
``````

will show each developer, sorted by commits to the project. The command:

``````\$ git shortlog -ns --since="1 year"
``````

will show the top developers from the last year.

## Citation

To cite SymPy in publications use

Meurer A, Smith CP, Paprocki M, Čertík O, Kirpichev SB, Rocklin M, Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE, Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry MJ, Terrel AR, Roučka Š, Saboo A, Fernando I, Kulal S, Cimrman R, Scopatz A. (2017) SymPy: symbolic computing in Python. PeerJ Computer Science 3:e103 https://doi.org/10.7717/peerj-cs.103

A BibTeX entry for LaTeX users is

```@article{10.7717/peerj-cs.103,
title = {SymPy: symbolic computing in Python},
author = {Meurer, Aaron and Smith, Christopher P. and Paprocki, Mateusz and \v{C}ert\'{i}k, Ond\v{r}ej and Kirpichev, Sergey B. and Rocklin, Matthew and Kumar, Amit and Ivanov, Sergiu and Moore, Jason K. and Singh, Sartaj and Rathnayake, Thilina and Vig, Sean and Granger, Brian E. and Muller, Richard P. and Bonazzi, Francesco and Gupta, Harsh and Vats, Shivam and Johansson, Fredrik and Pedregosa, Fabian and Curry, Matthew J. and Terrel, Andy R. and Rou\v{c}ka, \v{S}t\v{e}p\'{a}n and Saboo, Ashutosh and Fernando, Isuru and Kulal, Sumith and Cimrman, Robert and Scopatz, Anthony},
year = 2017,
month = Jan,
keywords = {Python, Computer algebra system, Symbolics},
abstract = {
SymPy is an open-source computer algebra system written in pure Python. It is built with a focus on extensibility and ease of use, through both interactive and programmatic applications. These characteristics have led SymPy to become a popular symbolic library for the scientific Python ecosystem. This paper presents the architecture of SymPy, a description of its features, and a discussion of select submodules. The supplementary material provides additional examples and further outlines details of the architecture and features of SymPy.
},
volume = 3,
pages = {e103},
journal = {PeerJ Computer Science},
issn = {2376-5992},
url = {https://doi.org/10.7717/peerj-cs.103},
doi = {10.7717/peerj-cs.103}
}```

SymPy is BSD licensed, so you are free to use it whatever you like, be it academic, commercial, creating forks or derivatives, as long as you copy the BSD statement if you redistribute it (see the LICENSE file for details). That said, although not required by the SymPy license, if it is convenient for you, please cite SymPy when using it in your work and also consider contributing all your changes back, so that we can incorporate it and all of us will benefit in the end.

• #### solve has many issues with fractions

``````>>> import sympy
>>> x=sympy.var('x')

Zero is sometimes wrongly reported as a solution.

>>> sympy.solve(-(1 + x)/(2 + x)**2 + 1/(2 + x), x)
[0]

There is a corresponding "TODO" in the source code, but it would be easy to
verify if 0 is an effective solution.
(# TODO: we might have introduced unwanted solutions when multiplied by x**-m)

Note that some calculus also lead to infinite recursion.

>>> sympy.solve(1/x,x)
[...]
<type 'exceptions.RuntimeError'>: maximum recursion depth exceeded

I've patched my own sympy installation ; if I manage to find some time,
I'll try to deal with all the git stuff to produce a proper sympy patch.
``````

Original issue for #4793: http://code.google.com/p/sympy/issues/detail?id=1694 Original author: https://code.google.com/u/117997262464115802198/ Referenced issues: #4871, #5117, #5016, #5086, #5091, #5226, #5035, #4463, #4464, #5171, #4922, #5098 Original owner: https://code.google.com/u/117997262464115802198/

imported Bug Needs Review solvers
opened by wxgeo 180
• #### Introduce rewrite rules

This introduces basic rewrite rules and strategies to SymPy.

It also uses these rewrite rules to refactor the MatrixExpressions module

TODO

1. ~~Rename `as_factor_mul`. Merge with as_coeff_mmul~~
2. ~~rewrite `linear_factors` (uses a lot of `Expr` functionality)~~ I've removed this all-together. The definition isn't consistent. I'll work on this in a future PR. Currently only work in other branches of mine uses this `sympy.stats.mvnrv`
3. MatMul/MatAdd don't simplify by default (maybe?) (I'm going to wait on this.)
4. ~~simplification in MatMul/MatAdd doesn't have to traverse entire tree~~
``````rr/rl.py         - some fundamental rules
rr/strat_pure.py - strategies that have nothing to do with SymPy
rr/traverse.py   - strategies that traverse a SymPy AST
rr/strat.py      - some conglomerate strategies that do depend on SymPy
``````

`matrices/expressions/mat(add/mul).py` - Some rules written in normal python language and the use of strategies to combine those rules. Can we replace these by something higher level written in the SymPy language? If so what? These files provide examples of the sorts of rules we'll want to write. The rules are at the bottom `matrices/expressions/blockmatrix.py` -- I replaced block_collapse (a giant function) with rules. This is a good change but could have been done just as easily by adding methods to existing classes. This is a more aggressive example of using rules to program SymPy. It's rules-for-transformation rather than just rules-for-canonicalization.

opened by mrocklin 178
• #### Gsoc 3

This is my final pull request of GSOC code. I understand that the gsoc-2 pull request is still being reviewed (which makes this one look quite monstrous, with >80 commits..), but as suggested elsewhere I'm trying to submit all pull requests (i.e. this one) before the soft pencils down deadline. Also submitting this pull request is my pledge not to rebase the branch more often than absolutely necessary.

The commits in this pull request can be separated roughly into three categories (and in principle I could submit separate pull requests for each of these, although I'm not sure if this is helpful):

• new special functions (polylog, lerchphi, exponential integrals; with varying degree of support for integration)
• general improvements to integration (neater output, more clever heurstics)
• performance improvements

Over the next few days I will go through and label all the commits (according to a consistent scheme to be come up with...) in order to make reviewing easier (which will of course mean rebasing...)

opened by ness01 151
• #### Added function to calculate Cauchy's principal value in sympy/integrals/integrals.py

Added function `cauchy_principal_value` in `sympy/integrals/integrals.py` to implement calculation of Cauchy's principal value

Took help (code) and reviews by @asmeurer in #14538

Note : I found this PR (#14538) quite helpful, and since there wasn't any on-going activity for quite some time, I decided to take it up and fix the issues and also add the reviews given by @asmeurer in the original PR.

Also, If required, I will add more tests and examples for the same.

Please review this PR and give me a feedback. Thanks

#### Release Notes

• integrals
• added method `principal_value` to class `Integral` to calculate Cauchy's principal value along with tests.
opened by avishrivastava11 145
• #### Issue 3275

Application of qapply(Rotation(alpha,beta,gamma)*JzKet(1,1)) [define the symbols alpha beta and gamma](And these are dummy) would ask for the inputs of alpha,beta,gamma.The parameters used in calling the function must be used to in the method and this is not happening so I had to ask for the input.Is there anyway that I could get it working without the use of asking for input.The issue is not completely solved because the same method has to be written for every spin state.

#### References to other Issues or PRs

Built upon #18436.

#### Brief description of what is fixed or changed

This PR adds a class for representing LTI systems in transfer function form.

TODO:

• [x] adding `TransferFunction` class along with its functionality.

• [x] Rewrite unit-tests and make sure they pass.

#### Release Notes

• physics.control
• Add `TransferFunction`, `Series`, `Parallel`, and `Feedback` class for physics.control submodule
GSoC physics.control
opened by namannimmo10 134
• #### Solving solvable quintics: First implementation

According to the discussions on above links, this PR introduces solving quintics exactly (not numerically) when they are solvable.

There are a lot of constants involved. So, I created a new file and made a new class for quintics containing required constants. Also note that solving quintics exactly takes( for x5 + 15*x +12 =0 ) ~ 40 secs. The long time is attributed to solving five equations of the form x5 - R =0 somewhere in the middle of the code.

Also, I have used simplify a few times. It seems that the code became almost 3 times as fast with using simplify, than without it.

There is an extra flag; quintics. When set to true, the new roots_quintic method is called and if the quintic is solvable, the solution is returned. I am attaching a screenshot :

Here you can see the solution of x*_5 + 15_x +12 = 0.

I have not added any tests. @asmeurer Please look at the code. Let me know for changes required.

opened by prasoon2211 131
• #### Proof of concept for the new assumptions

Here is a proof of concept of how I think the new assumptions should be done, as per https://code.google.com/p/sympy/issues/detail?id=3929. Take a read of the commit messages. The basic idea is that instead of writing handlers that look for expressions like Q.zero(x*y) and return new expressions that it knows are true like Q.zero(x) and Q.zero(y), the handler system returns a set of predicate statements, and everything is done using satisfiable(). This not only makes things cleaner, and gives us a single point of contact to make the assumptions faster (the dpll algorithm), it also allows computing things that are impossible to do under the current handler system. For instance

``````>>> from sympy.assumptions.newask import newask
True
True
False
``````

It's impossible to write a handler that says "x is zero or y is zero, but we don't know which one".

I would like some feedback at this point. This code is completely proof of concept. The API is terrible (basically nonexistant). What I've got now is completely unscalable. It already is getting out of hand, and I've only got four assumptions, real, positive, zero, and nonzero.

I've completely ignored the existing ask() code, because I didn't want to spend a lot of time at this point trying to understand it (it's quite complicated), so I basically wrote the prototype from scratch. Even so, it's quite simple, and I think once you grok how the satisfiable bit works, it is easy to understand the rest.

So my biggest questions now are, do people like this idea? Do you foresee any major issues with it? Most importantly, what would be a good way to organize the new-style "handlers" (relevant fact extraction) so that it is scalable, extensible, and readable?

Update: `newask` has been changed to `satask`

assumptions
opened by asmeurer 128
• #### Rewriting the Univariate Solver

This PR aims to rewrite a cleaner and robust univariate equation solver.

• [x] polynomial
• [x] rational
• [x] real trigonometric
• [x] write 4 tests to complete coverage
• [x] correct typo
• [x] correct this failure

### Nonblocking todo

• [ ] functions solvable by LambertW
• [ ] functions that can be recast as polynomials with a change of variables this, for example; this can be factored out of solve where multiple generators are handled
• [ ] use something like this to handle the XFAILed test `test_real_imag_splitting1`, this will be handled in the set module.
solvers GSoC solvers.solveset
opened by hargup 127
• #### Ideas to introduce indexed objects (possibly representing tensors)

Hi there! I'm currently writing a system of indexed n-dimensional arrays and valued tensors.

BUGS AND ISSUES:

• [ ] create `TensorIndexType.from_data( )` / `TensorIndexType.from_symmetry( )` methods.
• [x] missing tests for `.applyfunc` on `TensExpr`.
• [x] create `.strip( )`
• [x] test `.strip( )`
• [ ] repeat all of Pernici's tests on valued tensors as well (or maybe not really all of them).
• [ ] mark all autodrop points with comments.
• [x] check that `MultiArray` never replaces `TensorSymmetry` in all objects' args.
• [x] `MultiArray` shall never autodrop.
• [ ] test many `NumericIndices` on the same tensor.
• [x] create tests with non-diagonal metric.
• [ ] create tests for MultiArray of rank zero.
• [ ] correct `args` in `TensMul`, and everywhere else
• [ ] remove `@XFAIL` from core tests.
• [x] `NumericContravariant` and `NumericCovariant`: only int indices
• [ ] Decide if `NumericContravariant` and `NumericCovariant` are to be subclasses of `Basic`.
• [x] `direct_sum` in `MultiArray`
• [x] create tests for `direct_sum`
• [ ] direct sum of tensors
• [ ] tensor product of tensor indices (and method on tensors as well).
• [ ] check args in TensorIndexType and TensorIndex
• [ ] check args in valued TensorIndexType
• [ ] generator MultiArray.create( … ) for rank 0 ?
• [ ] extend MultiArray to higher rank?
• [ ] Why in TensorHead isn't comm passed to Basic's constructor?
• [ ] more control for wrong data in constructors.
• [ ] test type( … *args ) in NumericContravariant
• [ ] construct new data from `self.args` and check equality and hash compatibility with original data.
• [ ] find all TODO and solve the problems
• [ ] remove all TODO
• [ ] should `MultiArray` be renamed `NDArray` or something else?
• [ ] can we inspect `numpy`'s code for their implementation of nDarrays, and import some features here?
opened by Upabjojr 127

#### References to other Issues or PRs

Closes #18769 Fixes #18768

#### Release Notes

• core
• Extensible `add`, `mul` and `power` functions are introduced to allow sympy objects to define what classes should be used for them in place of `Add`, `Mul` and `Pow` (e.g. matrices use `MatAdd`). This is an experimental approach aimed at enabling the behaviour of core routines (expand, collect, etc) to be customised by user-defined types (e.g. `MatAdd` rather than `Add`). This mechanism is still experimental, is not fully implemented across the core and might be changed or removed in a future release of sympy.
core
opened by mcpl-sympy 125
• #### sympy.polys.polyerrors.HeuristicGCDFailed: no luck -- when multiplying two Polys

The following code snippet produces an error for me in python3.11 using sympy 1.11.1:

``````import sympy
x,y,C = sympy.symbols("x,y,C")
a = sympy.Poly(x**4/(C**2 + 3*C + 2)*y, y, domain='ZZ(x,C)')
b = sympy.Poly((12*C**12*x**8 + 60*C**12*x**7 + 72*C**12*x**6 + 24*C**12*x**5 + 108*C**11*x**8 + 540*C**11*x**7 + 660*C**11*x**6 + 240*C**11*x**5 + 12*C**11*x**4 + 414*C**10*x**8 + 2076*C**10*x**7 + 2580*C**10*x**6 + 1008*C**10*x**5 + 84*C**10*x**4 + 876*C**9*x**8 + 4608*C**9*x**7 + 5824*C**9*x**6 + 2400*C**9*x**5 + 240*C**9*x**4 + 1194*C**8*x**8 + 6876*C**8*x**7 + 8820*C**8*x**6 + 3816*C**8*x**5 + 408*C**8*x**4 + 1203*C**7*x**8 + 7596*C**7*x**7 + 9912*C**7*x**6 + 4560*C**7*x**5 + 540*C**7*x**4 + 897*C**6*x**8 + 6348*C**6*x**7 + 8474*C**6*x**6 + 4176*C**6*x**5 + 564*C**6*x**4 + 438*C**5*x**8 + 3816*C**5*x**7 + 5236*C**5*x**6 + 2784*C**5*x**5 + 408*C**5*x**4 + 96*C**4*x**8 + 1488*C**4*x**7 + 2170*C**4*x**6 + 1344*C**4*x**5 + 240*C**4*x**4 + 288*C**3*x**7 + 484*C**3*x**6 + 384*C**3*x**5 + 96*C**3*x**4)/(72*C**13 + 864*C**12 + 4680*C**11 + 15408*C**10 + 35280*C**9 + 61056*C**8 + 83952*C**7 + 93600*C**6 + 84744*C**5 + 61920*C**4 + 35784*C**3 + 15408*C**2 + 4320*C + 576)*y**2 + (4*C**6*x**4 + 12*C**6*x**3 + 4*C**6*x**2 + 20*C**5*x**4 + 60*C**5*x**3 + 20*C**5*x**2 + 37*C**4*x**4 + 108*C**4*x**3 + 36*C**4*x**2 + 36*C**3*x**4 + 108*C**3*x**3 + 36*C**3*x**2 + 32*C**2*x**4 + 96*C**2*x**3 + 32*C**2*x**2 + 16*C*x**4 + 48*C*x**3 + 16*C*x**2)/(12*C**7 + 84*C**6 + 240*C**5 + 384*C**4 + 420*C**3 + 348*C**2 + 192*C + 48)*y + 1, y, domain='ZZ(x,C)')

a * b
``````

The traceback is:

``````Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.11/site-packages/sympy/polys/polytools.py", line 72, in wrapper
return func(f, g)
^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/polytools.py", line 4183, in __mul__
return f.mul(g)
^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/polytools.py", line 1512, in mul
result = F.mul(G)
^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/polyclasses.py", line 457, in mul
return per(dmp_mul(F, G, lev, dom))
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/densearith.py", line 807, in dmp_mul
return dup_mul(f, g, K)
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/densearith.py", line 767, in dup_mul
coeff += f[j]*g[i - j]
~~~~^~~~~~~~~
File "/usr/local/lib/python3.11/site-packages/sympy/polys/fields.py", line 497, in __mul__
return f.new(f.numer*g.numer, f.denom*g.denom)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/fields.py", line 301, in new
return f.raw_new(*numer.cancel(denom))
^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/rings.py", line 2223, in cancel
_, p, q = f.cofactors(g)
^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/rings.py", line 2139, in cofactors
h, cff, cfg = f._gcd(g)
^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/rings.py", line 2172, in _gcd
return f._gcd_ZZ(g)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/rings.py", line 2177, in _gcd_ZZ
return heugcd(f, g)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/heuristicgcd.py", line 80, in heugcd
h, cff, cfg = heugcd(ff, gg)
^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/sympy/polys/heuristicgcd.py", line 118, in heugcd
raise HeuristicGCDFailed('no luck')
sympy.polys.polyerrors.HeuristicGCDFailed: no luck
``````
opened by jaypantone 0
• #### replace(oldtype, newtype) does unexpected and superfluous constructor calls to oldtype

This refers to bullet point 1.1, replacement of types, in documentation for sympy.core.basic.replace().

Situation

When replacing `oldtype` by `newtype` in an expression `expr`, `expr.replace(oldtype, newtype)` may call the constructor for `oldtype` and create further `oldtype` objects. Since `oldtype` is to be replaced by `newtype` this objects will then immediately be replaced by `newtype` objects, so this calls are superfluous at least. Moreover they are unexpected and may have unwanted performance or other side effects.

Example

``````from sympy import Expr, Add, symbols
class MathObj(Expr): # create a new mathematical object in SymPy from Expr, just for demo
def __new__(cls, a1, a2):
obj = Expr.__new__(cls, a1, a2) # sets up self.func, self.args
print(f"__new__(MathObj, {a1}, {a2})") # show that __new__ is called
return obj
# create some term using MathObj
n, m = symbols("n m")
p = MathObj(n, MathObj(m,m)) + MathObj(MathObj(n,n), m) #prints 4 times __new__(MathObj,..)

q = p.replace(MathObj, Add) # calls and prints 2 times __new__(MathObj,...) !!

print(q) # prints 3*m + 3*n
``````

Analysis This behaviour occurs if `oldtype` is nested within `expr` (as in the example above). In this case the statement `rv = rv.func(*newargs)` in function walk() in sympy.core.basic.replace() invokes the oldtype constructor. If `rv.func == oldtype` it should invoke `newtype(*newargs)` instead. However as replace() has various usages that are all handled by this code I'm unable to verify this.

opened by Costor 0

#### Brief description of what is fixed or changed

Topological sort used `None` as a default argument on the key field as a way to set a default like this `lambda value: value`. This can be achieved in a simpler way, by simply passing the default lambda as a default argument instead of none-checking.

#### Release Notes

• utilities
• iterables: topological sort takes natural value as default parameter, instead of getting it as None
opened by michelececcacci 2

#### References to other Issues or PRs

Fixes #8634 Closes #22712

#### Brief description of what is fixed or changed

Returns output dependent on 'n' (hence varies when n is odd/even) instead of -oo.

P.S. - This is a reproduction of #22712 which has already been reviewed to be correct by a couple of maintainers of the `series` module. It was contributed before the mailmap was introduced hence I am repeating it as suggested here .

On master -

``````>>> n = Symbol('n', integer=True, positive=True)  # could be 2 or 3...
>>> limit(x**n, x, -oo)
-oo
``````

On branch -

``````>>> limit(x**n, x, -oo)
oo*sign((-1)**n)
``````

#### Release Notes

• series
• Fixes limit at negative infinity considering odd or even power.
opened by faze-geek 2

Fixes #24456

#### Brief description of what is fixed or changed

Changed the bug-fixed example in the template now it is more specific and helpful.

#### Release Notes

NO ENTRY

opened by 1e9abhi1e10 4
• #### edit template to give better bug example

From #24443:

The example for what to write when a bug is fixed could be more helpful with a specific example. The template would need to be edited, perhaps like this:

``````* Fixed a bug with log of integers. Formerly, `log(-x)` incorrectly gave `-log(x)`.
``````
opened by smichr 0
##### Releases(sympy-1.11.1)
###### SymPy
Symbolic manipulation in Python.
###### Graphic notes on Gilbert Strang's "Linear Algebra for Everyone"

Graphic notes on Gilbert Strang's "Linear Algebra for Everyone"

3.2k Jan 8, 2023
###### A simple computer program made with Python on the brachistochrone curve.

Brachistochrone-curve This is a simple computer program made with Python on the brachistochrone curve. I decided to write it after a physics lesson on

1 Dec 16, 2021
###### collection of interesting Computer Science resources

collection of interesting Computer Science resources

137 Dec 22, 2022
###### Algorithms covered in the Bioinformatics Course part of the Cambridge Computer Science Tripos

Bioinformatics This is a repository of all the algorithms covered in the Bioinformatics Course part of the Cambridge Computer Science Tripos Algorithm

16 Jun 30, 2022
3.6k Dec 27, 2022
###### 3D visualization of scientific data in Python

Mayavi: 3D visualization of scientific data in Python Mayavi docs: http://docs.enthought.com/mayavi/mayavi/ TVTK docs: http://docs.enthought.com/mayav

1.1k Jan 6, 2023
###### Datamol is a python library to work with molecules

Datamol is a python library to work with molecules. It's a layer built on top of RDKit and aims to be as light as possible.

276 Dec 19, 2022
###### Incubator for useful bioinformatics code, primarily in Python and R

Collection of useful code related to biological analysis. Much of this is discussed with examples at Blue collar bioinformatics. All code, images and

560 Dec 24, 2022
###### Karate Club: An API Oriented Open-source Python Framework for Unsupervised Learning on Graphs (CIKM 2020)

Karate Club is an unsupervised machine learning extension library for NetworkX. Please look at the Documentation, relevant Paper, Promo Video, and Ext

1.8k Dec 31, 2022
###### Probabilistic Programming in Python: Bayesian Modeling and Probabilistic Machine Learning with Aesara

PyMC3 is a Python package for Bayesian statistical modeling and Probabilistic Machine Learning focusing on advanced Markov chain Monte Carlo (MCMC) an

7.2k Dec 30, 2022
###### Statsmodels: statistical modeling and econometrics in Python

About statsmodels statsmodels is a Python package that provides a complement to scipy for statistical computations including descriptive statistics an

8.1k Dec 30, 2022
###### Kedro is an open-source Python framework for creating reproducible, maintainable and modular data science code

A Python framework for creating reproducible, maintainable and modular data science code.

7.9k Jan 1, 2023
###### PennyLane is a cross-platform Python library for differentiable programming of quantum computers.

PennyLane is a cross-platform Python library for differentiable programming of quantum computers. Train a quantum computer the same way as a neural network.

1.6k Jan 4, 2023
###### SCICO is a Python package for solving the inverse problems that arise in scientific imaging applications.

Scientific Computational Imaging COde (SCICO) SCICO is a Python package for solving the inverse problems that arise in scientific imaging applications

37 Dec 21, 2022
###### Efficient Python Tricks and Tools for Data Scientists

Why efficient Python? Because using Python more efficiently will make your code more readable and run more efficiently.

944 Dec 28, 2022
###### Float2Binary - A simple python class which finds the binary representation of a floating-point number.

Float2Binary A simple python class which finds the binary representation of a floating-point number. You can find a class in IEEE754.py file with the

3 Dec 14, 2021
###### CONCEPT (COsmological N-body CodE in PyThon) is a free and open-source simulation code for cosmological structure formation

CONCEPT (COsmological N-body CodE in PyThon) is a free and open-source simulation code for cosmological structure formation. The code should run on any Linux system, from massively parallel computer clusters to laptops.

62 Dec 8, 2022
###### A computer algebra system written in pure Python

SymPy See the AUTHORS file for the list of authors. And many more people helped on the SymPy mailing list, reported bugs, helped organize SymPy's part

9.9k Dec 31, 2022
###### A computer algebra system written in pure Python

SymPy See the AUTHORS file for the list of authors. And many more people helped on the SymPy mailing list, reported bugs, helped organize SymPy's part

9.9k Jan 8, 2023
###### Mathics is a general-purpose computer algebra system (CAS). It is an open-source alternative to Mathematica

Mathics is a general-purpose computer algebra system (CAS). It is an open-source alternative to Mathematica. It is free both as in "free beer" and as in "freedom".

535 Jan 4, 2023