I want to remove any coefficient that is equal to 1 in sympy symbolic expression , for example:
I want 1.0x**2 to be x**2 , Is there anyway to do it ?
Also if possible to round integers , for example 2.0x**2 to be 2*x**2
You can use nsimplify:
In [4]: nsimplify(2.0*x**2)
Out[4]:
2
2⋅x
in a Python shell
>>> import sympy
>>> sympy.nsimplify("1.0*x**2")
x**2
>>> sympy.nsimplify("2.0*x**2")
2*x**2
Related
I am using sympy to derive some equations and I experience some unexpected behaviour with substituting. Let's say I have a function f(x) that I differentiate by x like this:
fx = f(x).diff()
This results in the following:
Now if I substitute x with a value such as pi, like this:
fx.subs(x, pi)
I get:
However, if I substitute x with another variable, let say phi, like this:
fx.subs(x, phi)
I get something unexpected:
What is happening is that sympy is replacing x in the equation before differentiating, I would like that it does after it. I have seen some suggestions that I should use .doit(), but that does not result in a wanted solution:
fx.doit().subs(x, phi)
What am I doing wrong and how can I replace the variable after the differentiation?
Use srepr to see the structure of an expression more directly:
In [48]: f(x).diff(x).subs(x, pi)
Out[48]:
⎛d ⎞│
⎜──(f(x))⎟│
⎝dx ⎠│x=π
In [49]: srepr(f(x).diff(x).subs(x, pi))
Out[49]: "Subs(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))), Tuple(Symbol('x')), Tuple(pi))"
So you can see that Subs is what is used to represent an unevaluated substitution:
In [50]: Subs(f(x).diff(x), x, phi)
Out[50]:
⎛d ⎞│
⎜──(f(x))⎟│
⎝dx ⎠│x=φ
Then doit is used to make the Subs evaluate (by performing the substitution):
In [51]: Subs(f(x).diff(x), x, phi).doit()
Out[51]:
d
──(f(φ))
dφ
https://docs.sympy.org/latest/modules/core.html#subs
My equation is ax = ln(ec-b/y)
How can I find what x*y equals in python? I've tried using SymPy.solve, but it doesn't allow me to solve for a term. Thanks in advance.
If you solve for y = f(x) then y*x = x*f(x). So these two steps in SymPy are:
>>> from sympy.abc import a,b,c,x,y
>>> from sympy import solve, Eq
>>> solve(Eq(a*x , ln(exp(c-b)/y)),y)
[exp(-a*x - b + c)]
>>> _[0]*x # == y*x
x*exp(-a*x - b + c)
You can solve for any subexpression, but when it is not a symbol, it will be interpreted literally as if you solved for u after replacing the sub-expression with u:
>>> solve(x*y - 1/x, x*y)
[1/x]
In your expression there is no x*y so that's why an attempt to naively solve for it fails.
I tried this in python shell
>>> from sympy import sqrt
>>> sqrt((-9/10 + 6*sqrt(3)/5)**2 + (6/5 + 9*sqrt(3)/10)**2)
sqrt((-0.9 + 6*sqrt(3)/5)**2 + (1.2 + 9*sqrt(3)/10)**2)
and when type it in google:
So how do I get numpy to give me a more simpilified result (it won't always be an int so I cant use evalf or N)
There are 2 things missing here:
You need to explicitly tell sympy to simplify the expression if it's something complex.
You should use Rational whenever possible, to avoid numerical inaccuraties of floating point arithmetic
All in all:
>>> from sympy import Rational, simplify, sqrt
>>> simplify(sqrt((-Rational(9, 10) + Rational(6,5)*sqrt(3))**2 + (Rational(6,5) + Rational(9,10)*sqrt(3))**2))
3
When I am writing the probability density function for a normal distribution in Sympy (v. 1.5.1) like this:
pdf_normal = (1 / (sigma*sqrt(2*pi))) * exp(-(1/2) * ((x - mu)/sigma)**2)
based on an expression of the equation like this (Wikipedia):
sympy 'simplifies' the expression but makes it much harder to read:
Is there any way to prevent this?
(This discussion is not helping, because the proposed answer is not touching the expression at all)
Thanks in advance!
You can use evaluate=False to control this but it will likely end up being evaluated in subsequent operations:
In [11]: Pow(Mul(sigma, sqrt(2*pi, evaluate=False), evaluate=False), -1, evaluate=False)
Out[11]:
1
─────────
_____
σ⋅╲╱ 2⋅π
Does symbol-trickery work for you?
>>> r2pi = Symbol('\\sqrt{2 \\pi}')
>>> (1 / (sigma*r2pi)) * exp(-(1/2) * ((x - mu)/sigma)**2)
The UnevaluatedExpr class will keep an expression from being re-evaluated during subsequent operations. With the changes suggested here I think it would solve your problem:
>>> from sympy import S
>>> from sympy.abc import *
>>> from sympy import S
>>> usqrt = lambda x: UnevaluatedExpr(sqrt(x, evaluate=False))
>>> (1 / (sigma*usqrt(2*pi))) * exp(((x - mu)/sigma)**2/-2)
exp(-(-mu + x)**2/(2*sigma**2))/(sigma*sqrt(2*pi))
Given an expression in sympy, is there a way to find all discontinuities in a given interval? For instance, given 1/(x^2-1) from -2 to 2, it would return -1 and 1. It doesn't have to be symbolic. A numerical solution may actually work better for my purposes.
You can use the singularities module for this.
In [ ]: from sympy import *
In [ ]: init_printing()
In [ ]: x = symbols('x')
In [ ]: singularities(1/(x**2 - 1), x)
Out[ ]: (-1, 1) # A tuple of SymPy objects
Reference: http://docs.sympy.org/latest/modules/calculus/index.html#sympy.calculus.singularities.singularities
I don't think that there's any specific method in SymPy to do this; it might be very difficult to do in full generality (i.e. for any possible function, in any number of variables, including those with infinite discontinuities).
If you're working with relatively simple expressions in one real variable, such as the example in your question, then one approach could be to compute the expression as a ratio of two expressions and then solve the denominator expression.
>>> expr
1/(x**2 - 1)
>>> n, d = expr.as_numer_denom()
>>> sympy.solve(d)
[-1, 1]
Another small example:
>>> expr2 = 1/(sympy.sin(x)) + 4/(x**2 - 3)
>>> expr2
1/sin(x) + 4/(x - 3)
>>> n, d = expr2.as_numer_denom()
>>> sympy.solve(d)
[0, -sqrt(3), sqrt(3), pi]
Obviously in this case SymPy does not list every multiple of pi as a solution; you'll have to process the list to generate solutions that lie in your desired domain.