Basically I'm trying to run the following code.
import sympy as sp
alpha = sp.Symbol(r'\alpha')
x = sp.Symbol('x')
sp.Q.is_true(alpha != -1)
sp.integrate(x**alpha, x)
This results in the following Piecewise function.
Since I specify global assumptions that alpha != -1, I expected it will simply give me the first expression. So two questions I have:
how do you properly define the assumptions so that the sp.integrate does not ignore them;
is there a way to access (extract) the first (or second) expression from the Piecewise function?
Thanks in advance!
PS. Defining conds='separate' in the sp.integrate only returns the first expression for some reason. So if I needed the second part of the piecewise function, I wouldn't be able to get it.
PPS. In case this matters, I have python 3.8.0 and sympy 1.4.
There is no way to give a specific value as an assumption for a symbol so it can be used in the integration. The best you can do is specify positive, negative, etc... But as for extracting the desired expression from the Piecewise, you can either get it as the particular argument or else feed in a dummy value for x that would extract it. Like the following:
>> from sympy.abc import x
>> from sympy import Piecewise, Dummy
>> eq = Piecewise((x + 1, x < 0), (1/x, True))
>> eq.args[0]
(x + 1, x < 0)
>> _.args[0]
x + 1
>> d = Dummy(negative=True)
>> eq.subs(x, d)
d + 1
>> _.subs(d, x)
x + 1
Related
according to this graph: desmos
print(solve('x**2 + x - 1/x'))
# [-1/3 + (-1/2 - sqrt(3)*I/2)*(sqrt(69)/18 + 25/54)**(1/3) + 1/(9*(-1/2 - sqrt(3)*I/2)*(sqrt(69)/18 + 25/54)**(1/3)), -1/3 + 1/(9*(-1/2 + sqrt(3)*I/2)*(sqrt(69)/18 + 25/54)**(1/3)) + (-1/2 + sqrt(3)*I/2)*(sqrt(69)/18 + 25/54)**(1/3), -1/3 + 1/(9*(sqrt(69)/18 + 25/54)**(1/3)) + (sqrt(69)/18 + 25/54)**(1/3)]
I was expecting [0.755, 0.57], but, I got something I cannot use in my future program. I desire to get a list of floats as result, so refer to this post, I did following, but I got some even more weird:
def solver(solved, rit=3):
res = []
for val in solved:
if isinstance(val, core.numbers.Add):
flt = val.as_two_terms()[0]
flt = round(flt, rit)
else:
flt = round(val, rit)
if not isinstance(flt, core.numbers.Add):
res.append(flt)
return res
print(solver(solve('x**2 + x - 1/x')))
# [-0.333, -0.333, -0.333]
Now I am really disappointed with sympy, I wonder if there is an accurate way to get a list of floats as result, or I will code my own gradient descent algorithm to find the roots and intersection.
sym.solve solves an equation for the independent variable. If you provide an expression, it'll assume the equation sym.Eq(expr, 0). But this only gives you the x values. You have to substitute said solutions to find the y value.
Your equation has 3 solutions. A conjugate pair of complex solutions and a real one. The latter is where your two graphs meet.
import sympy as sym
x = sym.Symbol('x')
# better to represent it like the equation it is
eq = sym.Eq(x**2, 1/x - x)
sol = sym.solve(eq)
for s in sol:
if s.is_real:
s = s.evalf()
print(s, eq.lhs.subs({x: s})) # eq.rhs works too
There are a variety of things you can do to get the solution. If you know the approximate root location and you want a numerical answer, nsolve is simplest since it has no requirements on the type of expression:
>>> from sympy import nsolve, symbols
>>> x = symbols('x')
>>> eq = x**2 + x - 1/x
>>> nsolve(eq, 1)
0.754877666246693
You can try a guess near 0.57 but it will go to the same solution. So is there really a second real roots? You can't use real_roots on this expression because it isn't in polynomial form. But if you split it into numerator and denominator you can check for the roots of the numerator:
>>> n, d = eq.as_numer_denom()
>>> from sympy import real_roots
>>> real_roots(n)
[CRootOf(x**3 + x**2 - 1, 0)]
So there is only one real root for that expression, the one that nroots gave you.
Note: the answer that solve gives is an exact solution to the cubic equation and it can't figure out definitively which ones are a solution to the equation so it returns all three. If you evaluate them you will find that only one of them is real. But since you don't need the symbolic solution, just stick to nroots.
I'm trying to solve the following equation.
(x * x) - 1 = 0
The result should be +1 or -1. But when I try to solve it via sympy, the result is an empty output.
import sympy as sy
x = sy.Symbol('x')
sy.solve((x**2)-1, 0)
# sy.solve((x * x)-1, 0) and sy.solve((x * x), 1) returns the same result
>>> []
What am I doing wrong here?
You should use,
sy.solve((x**2)-1,x)
Instead of,
sy.solve((x**2)-1,0)
The second argument x suggests that the equation should be solved for x. You are solving the equation for 0 which makes no sense.
Carefully read the documentation in the future :)
It is supposed to be
>>> from sympy.solvers import solve
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> solve(x**2 - 1, x)
Read the documentation for the function here
Either do
sp.solve((x**2)-1, x)
or
sp.solve((x**2) - 1)
For further information, you can check out https://docs.sympy.org/latest/modules/solvers/solvers.html
In nsolve the second argument is an initial guess for the value of the variable that will make the univariate expression equal to zero:
>>> nsolve(x**2-1, 0)
1.00000000000000
>>> nsolve(x**2-1, -3)
-1.00000000000000
In solve, however, an initial guess is not needed since the equation will be solved symbolically:
>>> nsolve(x**2-1)
[-1, 1]
But solve can also handle multivariate expressions and in that case the second argument is used to indicate which variable you want to solve for.
>>> solve(x**2-c)
[{c: x**2}]
>>> solve(x**2-c, x)
[-sqrt(c), sqrt(c)]
But you can solve for anything that appears in the expression, even numbers. That's why an error is not raised in your case (though perhaps zero should raise an error). Here are examples of solving for a number:
>>> solve(3*x**2-c, 3)
[c/x**2]
>>> solve(3*x**4-c, 4)
[log(c/3)/log(x)]
>>> solve(2*x**2-c, 2)
[LambertW(c*log(x))/log(x)]
Not sure why I can't find something on this but here's my question:
How do I initiate an integer without giving it a value so I can use it to solve equations.
E.g., if I specified that I had some integer x then I could write something that allows me to solve functions with respect to x.
E.g., an output might be: 2x+5
EX:
# Eisenstein Prime?
# 1J is complex number i
def eisenstein(a,b):
w = e**((2*math.pi*1J)/3)
z=a+b*w
a = a+b*(w**2)
print("Eisenstein Integer as z:")
print(z)
print("Omega as w:")
print(w)
This outputs:
Eisenstein Integer as z:
(-0.9999999999999987+5.196152422706632j)
Omega as w:
(-0.4999999999999998+0.8660254037844387j)
I'd like to have the variable similar to how j appears above.
You can't do that with plain ints. You'll need to install a package for symbolic mathematics.
python -m pip install sympy
Then to use it,
import sympy as sp
x = sp.var('x')
equation = 2*x + 5
print(sp.solve([equation], [x]))
Output:
{x: -5/2}
The solver takes lists because it can do systems of equations. You can also just
sp.solve(equation, x)
And get
[-5/2]
Another example.
import sympy as sp
x, y = sp.var('x y')
equation = 2*x + 5*y # Equations made this way are implicitly "= 0".
print(sp.solveset(equation, y, sp.S.Complexes))
Solved for y, note the output is in terms of x:
{-2*x/5}
I'm trying to perform the following integration using sympy;
x = Symbol('x')
expr = (x+3)**5
integrate(expr)
The answer that I'm expecting is:
But what's being returned is:
The following code works in MATLAB:
syms x
y = (x+3)^5;
int(y)
I'm unsure what I'm doing wrong in order to perform this using sympy.
This is actually a common problem seen in Calculus where for these kinds of polynomial expressions, you do get two answers. The coefficients for each of the powers of x exist but the constant factor is missing between them.
As such, there are two methods you can use to find the indefinite integral of this expression.
The first method is to perform a substitution where u = x+3, then integrate with respect to u. Then, the indefinite integral would be (1/6)*(x + 3)^6 + C as you expect.
The second method is to fully expand out the polynomial and integrate each term individually.
MATLAB elects to find the integral the first way:
>> syms x;
>> out = int((x+3)^5)
out =
(x + 3)^6/6
Something to note for later is that if we expand out this polynomial expression, we get:
>> expand(out)
ans =
x^6/6 + 3*x^5 + (45*x^4)/2 + 90*x^3 + (405*x^2)/2 + 243*x + 243/2
sympy elects to find the integral the second way:
In [20]: from sympy import *
In [21]: x = sym.Symbol('x')
In [22]: expr = (x+3)**5
In [23]: integrate(expr)
Out[23]: x**6/6 + 3*x**5 + 45*x**4/2 + 90*x**3 + 405*x**2/2 + 243*x
You'll notice that the answer is the same between both environments, but the constant factor is missing. Because the constant factor is missing, there is no neat way to factor this into the neat polynomial that you are expecting from your output seen in MATLAB.
As a final note, if you would like to reproduce what sympy generates, expand out the polynomial, then integrate. We get what sympy generates:
>> syms x;
>> out = expand((x+3)^5)
out =
x^5 + 15*x^4 + 90*x^3 + 270*x^2 + 405*x + 243
>> int(out)
ans =
x^6/6 + 3*x^5 + (45*x^4)/2 + 90*x^3 + (405*x^2)/2 + 243*x
The constant factor though shouldn't worry you. In the end, what you are mostly concerned with is a definite integral, and so the subtraction of these constant factors will happen, which won't affect the final result.
Side Note
Thanks to DSM, if you specify the manual=True flag for integrate, this will attempt to mimic performing integration by hand, which will give you the answer you're expecting:
In [26]: from sympy import *
In [27]: x = sym.Symbol('x')
In [28]: expr = (x+3)**5
In [29]: integrate(expr, manual=True)
Out[29]: (x + 3)**6/6
Just started learning python, and was asked to define a python function that integrate a math function.
We were instructed that the python function must be in the following form: (for example, to calculate the area of y = 2x + 3 between x=1 and x=2 )
integrate( 2 * x + 3, 1, 2 )
(it should return the area below)
and we are not allowed to use/import any libraries other than math (and the built in integration tool is not allowed either).
Any idea how I should go about it? When I wrote the program, I always get x is undefined, but if I define x as a value ( lets say 0 ) then the 2*x+3 part in the parameters is always taken as a value instead of a math equation, so I can't really use it inside?
It would be very helpful, not just to this assignment, but many in the future if I know how a python function can take a math equation as parameter, so thanks alot.
Let's say your integration function looks like this:
def integrate(func, lo_x, hi_x):
#... Stuff to perform the integral, which will need to evaluate
# the passed function for various values of x, like this
y = func(x)
#... more stuff
return value
Then you can call it like this:
value = integrate(lambda x: 2 * x + 3, 1, 2)
edit
However, if the call to the integration function has to look exactly like
integrate( 2 * x + 3, 1, 2 )
then things are a bit trickier. If you know that the function is only going to be called with a polynomial function you could do it by making x an instance of a polynomial class, as suggested by M. Arthur Vaïsse in his answer.
Or, if the integrate( 2 * x + 3, 1, 2 ) comes from a string, eg from a command line argument or a raw_input() call, then you could extract the 2 * x + 3 (or whatever) from the string using standard Python string methods and then build a lambda function from that using exec.
Here come an implementation that fill the needs I think. It allow you to define mathematical function such as 2x+3 and propose an implementation of integral calculation by step as described here [http://en.wikipedia.org/wiki/Darboux_integral]
import math
class PolynomialEquation():
""" Allow to create function that are polynomial """
def __init__(self,coef):
"""
coef : coeficients of the polynome.
An equation initialized with [1,2,3] as parameters is equivalent to:
y = 1 + 2X + 3X²
"""
self.coef = coef
def __call__(self, x):
"""
Make the object callable like a function.
Return the value of the equation for x
"""
return sum( [self.coef[i]*(x**i) for i in range(len(self.coef)) ])
def step_integration(function, start, end, steps=100):
"""
Proceed to a step integration of the function.
The more steps there are, the more the approximation is good.
"""
step_size = (end-start)/steps
values = [start + i*step_size for i in range(1,steps+1)]
return sum([math.fabs(function(value)*step_size) for value in values])
if __name__ == "__main__":
#check that PolynomialEquation.value works properly. Assert make the program crash if the test is False.
#y = 2x+3 -> y = 3+2x -> PolynomialEquation([3,2])
eq = PolynomialEquation([3,2])
assert eq(0) == 3
assert eq(1) == 5
assert eq(2) == 7
#y = 1 + 2X + 3X² -> PolynomialEquation([1,2,3])
eq2 = PolynomialEquation([1,2,3])
assert eq2(0) == 1
assert eq2(1) == 6
assert eq2(2) == 17
print(step_integration(eq, 0, 10))
print(step_integration(math.sin, 0, 10))
EDIT : in truth the implementation is only the upper Darboux integral. The true Darboux integral could be computed if really needed by computing the lower Darboux integral ( replace range(1, steps+1) by range(steps) in step_integration function give you the lower Darboux function. And then increase the step parameter while the difference between the two Darboux function is greater than a small value depending on your precision need (could be 0.001 for example). Thus a 100 step integration is suppose to give you a decent approximation of the integral value.