Simplification in sympy - sympy

I am new to sympy, and I cannot understand why the result of the following piece of code does not results in f(x)=0
from sympy import *
f = Function('f')
x = Symbol('x')
simplify(Eq(f(x)+1,1))

When SymPy rewrites x + x as 2*x that is automatic rewriting. Not everything is automatic, however, as you have seen. If you want to know what value of f(x) makes that Equality true, you can solve for it:
>>> solve(Eq(f(x) + 1, 1), f(x))
[0]

Related

Sympy IndexedBase substitution

I am a bit confused how to use Indexed objects in Sympy. Suppose I have the following setup:
from sympy import *
x = IndexedBase('x')
i = Idx('i')
s = Sum(x[i], (i, 0, 5))
s
Output:
5
___
╲
╲
╱ x[i]
╱
‾‾‾
i = 0
Which ofcourse is equal to
x[0] + x[1] + x[2] + x[3] + x[4] + x[5]
By doing s.doit(). Now, how do I substitute x with some range? I expected the following to work:
s.subs(x, list(range(6)))
But it does not do anything it would seem. However s.doit().subs(x[0], 0) works, but it will only substitute 1 element. Is it not intended to substitute IndexedBase with some list?
When using SymPy, there is one thing to always keep in mind: the only objects SymPy operates on is SymPy's object. Consider this example:
expr = x + 3
r = expr.subs(x, 2)
print(r, type(r))
5 <class 'sympy.core.numbers.Integer'>
Here, we passed a int number to subs, but SymPy internally converted it to an Integer number. Then, it performed the addition, producing the Integer number 5.
There are occasions in which the input parameter cannot be converted to something SymPy can understand. Your example is one such occasion. Let's use sympify (or its alias S) to verify how your list is going to be converted to a SymPy object:
l = list(range(6))
c = sympify(l)
type(c)
# out: list
As we can see, SymPy is unable to convert an object of type list, hence it is unable to use it. In short, this is the reason your code doesn't produce the correct output.
However, let's try the same trick with a tuple:
c = sympify(tuple(l))
type(c)
# out: Tuple
Here, SymPy converted a Python object of type tuple to a SymPy object of type Tuple. Now, the substitution should produce the correct result:
s.doit().subs(x, tuple(l))
# out: 15
Here are the most common SymPy objects the support iteration: Tuple, Matrix, Array.

How to solve an equation that contains Sum in SymPy?

I want to solve the following equation for x with SymPy:
(Note that the equation can be simplified as mentioned in the comments, I copied it verbatim from an example in a legal document.)
According to my understanding, this translates to the following SymPy expression:
from sympy import Sum, solve
from sympy.abc import k, x
solve(350 - 18500 + Sum(182.94 * (1/(1+x)**(k/12)), (k, 1, 120)), x)
However, when I run this, the result is empty:
[]
What am I doing wrong?
solve probably shouldn't give [] but you will get better results from nsolve for this expression using a guess for x near 0:
>>> from sympy.abc import k, x
>>> from sympy import nsolve
eq = 350 - 18500 + Sum(182.94 * (1/(1+x)**(k/12)), (k, 1, 120))
>>> nsolve(eq, 0)
0.0397546543274819
>>> eq.subs(x,_).round(2)
0

how to use SymPy or other library to have a numerical solution

I was trying to solve two equations for two unknown symbols 'Diff' and 'OHs'. the equations are shown below
x = (8.67839580228369e-26*Diff + 7.245e-10*OHs**3 +
1.24402291559836e-10*OHs**2 + OHs*(-2.38073807380738e-19*Diff -
2.8607855978291e-18) - 1.01141409254177e-29)
J= (-0.00435840284294195*Diff**0.666666666666667*(1 +
3.64525434266056e-7/OHs) - 1)
solution = sym.nsolve ((x, J), (OHs, Diff), (0.000001, 0.000001))
print (solution)
is this the correct way to solve for the two unknowns?
Thanks for your help :)
Note: I edited your equation per Vialfont's comments.
I would say it is a possible way but you could do better by noticing that the J equation can be solved easily for OHs and substituted into the x equation. This will then be much easier for nsolve to solve:
>>> osol = solve(J, OHs)[0] # there is only one solution
>>> eq = x.subs(OHs,osol)
>>> dsol = nsolve(eq, 1e-5)
>>> eq.subs(Diff,dsol) # verify
4.20389539297445e-45
>>> osol.subs(Diff,dsol), dsol
(-2.08893263437131e-12, 4.76768525775849e-5)
But this is still pretty ill behaved in terms of scaling...proceed with caution. And I would suggest writing Diff**Rational(2,3) instead of Diff**0.666666666666667. Or better, then let Diff be y**3 so you are working with a polynomial in y.
>>> y = var('y', postive=True)
>>> yx=x.subs(Diff,y**3)
>>> yJ=J.subs(Diff,y**3)
>>> yosol=solve(yJ,OHs)[0]
>>> yeq = yx.subs(OHs, yosol)
Now, the solutions of eq will be where its numerator is zero so find the real roots of that:
>>> ysol = real_roots(yeq.as_numer_denom()[0])
>>> len(ysol)
1
>>> ysol[0].n()
0.0362606728976173
>>> yosol.subs(y,_)
-2.08893263437131e-12
That is consistent with our previous solution, and this time the solutions in ysol were exact (given the limitations of the coefficients). So if your OHs solution should be positive, check your numbers and equations.
Your expressions do not meet Sympy requirements, including the exponential expressions. May be it is easier to start with a simpler system to solve with two unknowns and only a square such as:
from sympy.abc import a,b,x, y
from sympy import solve,exp
eq1= a*x**2 + b*y+ exp(0)
eq2= x + y + 2
sol=solve((eq1, eq2),(x,y),dict=True)
sol includes your answers and you have access to solutions with sol[0][x] and sol[0][y]. Giving values to the parameters is done with the .sub() method:
sol[0][x].subs({a:1, b:2}) #gives -1
sol[0][y].subs({a:1, b:2}) #gives -1

How in sympy Disable unnecessary parenthesis?

Tell me please, How to forbid to open brackets? For example,
8 * (x + 1) It should be that way, not 8 * x + 8
Using evaluate = False doesn't help
The global evaluate flag will allow you to do this in the most natural manner:
>>> with evaluate(False):
... 8*(x+1)
...
8*(x + 1)
Otherwise, Mul(8, x + 1, evaluate=False) is a lower level way to do this. And conversion from a string (already in that form) is possible as
>>> S('8*(x+1)',evaluate=False)
8*(x + 1)
In general, SymPy will convert the expression to its internal format, which includes some minimal simplifications. For example, sqrt is represented internally as Pow(x,1/2). Also, some reordering of terms may happen.
In your specific case, you could try:
from sympy import factor
from sympy.abc import x, y
y = x + 1
g = 8 * y
g = factor(g)
print(g) # "8 * (x + 1)"
But, if for example you have g = y * y, SymPy will either represent it as a second power ((x + 1)**2), or expand it to x**2 + 2*x + 1.
PS: See also this answer by SymPy's maintainer for some possible workarounds. (It might complicate things later when you would like to evaluate or simplify this expression in other calculations.)
How about sympy.collect_const(sympy.S("8 * (x + 1)"), 8)?
In general you might be interested in some of these expression manipulations: https://docs.sympy.org/0.7.1/modules/simplify/simplify.html

symbolic derivation of a larger function

I want to take the derivative of the following function
y=(np.log(x))/(1+x),
if I am using sympy, it gives me the following error
from sympy import *
y1=Derivative((np.log(x))/(1+x), x)
print y1
sequence too large; cannot be greater than 32
Do it like this:
>>> from sympy import *
>>> var('x')
x
>>> y1 = diff(log(x)/(1+x))
>>> y1
-log(x)/(x + 1)**2 + 1/(x*(x + 1))
As Sanjeev mentioned in a comment you need to define variables in one way or another.
np.log in your code would be a function that accepts a numerical value and returns a numerical value; sympy needs to see a function names that it knows in formal terms, such as log
In this context, you need to use sympy's diff function, rather than Derivative.