How to deal with algebra in Python? - python

Apologies if this has been asked before, I’m a little stuck.
If I had two variables
a = 3x+4y
b = 2x+2y
How could I make it so that a+b = 5x+4y? The way I’ve been currently doing it is with numpy and the imaginary variable. However that doesn’t extend to more than one.
My current one variable code looks like this:
from numpy import *
a = 1+3j
b = 2+7j
Then I can just you the real and imag functions to get the appropriate coefficients.
Thanks

You can use Sympy.
from sympy import symbols
x = symbols('x')
y = symbols('y')
a = symbols('a')
b = symbols('b')
And define your equation using the python variables defined above
expr1 = 5*x + 4*y
expr2 = a + b

Related

evalf and subs in sympy on single variable expression returns expression instead of expected float value

I'm new to sympy and I'm trying to use it to get the values of higher order Greeks of options (basically higher order derivatives). My goal is to do a Taylor series expansion. The function in question is the first derivative.
f(x) = N(d1)
N(d1) is the P(X <= d1) of a standard normal distribution. d1 in turn is another function of x (x in this case is the price of the stock to anybody who's interested).
d1 = (np.log(x/100) + (0.01 + 0.5*0.11**2)*0.5)/(0.11*np.sqrt(0.5))
As you can see, d1 is a function of only x. This is what I have tried so far.
import sympy as sp
from math import pi
from sympy.stats import Normal,P
x = sp.symbols('x')
u = (sp.log(x/100) + (0.01 + 0.5*0.11**2)*0.5)/(0.11*np.sqrt(0.5))
N = Normal('N',0,1)
f = sp.simplify(P(N <= u))
print(f.evalf(subs={x:100})) # This should be 0.5155
f1 = sp.simplify(sp.diff(f,x))
f1.evalf(subs={x:100}) # This should also return a float value
The last line of code however returns an expression, not a float value as I expected like in the case with f. I feel like I'm making a very simple mistake but I can't find out why. I'd appreciate any help.
Thanks.
If you define x with positive=True (which is implied by the log in the definition of u assuming u is real which is implied by the definition of f) it looks like you get almost the expected result (also using f1.subs({x:100}) in the version without the positive x assumption shows the trouble is with unevaluated polar_lift(0) terms):
import sympy as sp
from sympy.stats import Normal, P
x = sp.symbols('x', positive=True)
u = (sp.log(x/100) + (0.01 + 0.5*0.11**2)*0.5)/(0.11*sp.sqrt(0.5)) # changed np to sp
N = Normal('N',0,1)
f = sp.simplify(P(N <= u))
print(f.evalf(subs={x:100})) # 0.541087287864516
f1 = sp.simplify(sp.diff(f,x))
print(f1.evalf(subs={x:100})) # 0.0510177033783834

Solving an equation system in terms of an unknown like z, could use some help in matlab or other programming languages

For example I have been given some equations and the solution is asked in terms of y/x = only numbers and z.
w1=-x+w2+w3,
w2=(z^-1)*x+2*w3,
w3=(z^-1)*w2+(z^-1)*y,
y=2*w1
I would like to see the solution to be done like this: (y/x = some equation only in terms of z and numbers)
y/x=(-2+6*(z^-1)+2*(z^-2))/(1-8*(z^-1))
Is there a way to do this? Could be code or some function in certain programming languages like matlab.
Thanks in advance.
MATLAB:
The isolate(eqn,expr) function will do this. The given example is, where x is isolated from a*x^2 + b*x + c == 0:
syms x a b c
eqn = a*x^2 + b*x + c == 0;
xSol = isolate(eqn, x)
Output:
xSol =
x == -(b + (b^2 - 4*a*c)^(1/2))/(2*a)
WolframAlpha:
solve(eqn,exp)
e.g. solve(a*x^2 + b*x + c = 0,x) will also re-write the same equation in terms of x.
Alteratively, a WolframAlpha widget exists to do this manually: https://www.wolframalpha.com/widgets/view.jsp?id=3d613c498715c870be91ed38004abc81

Solving a simple symbolic equation in python

I am using sympy to solve a very simple equation symbolically, but the solution I get for the variable is an empty matrix! Here is the code:
from sympy import *
x = Symbol('x')
l_x = Symbol('l_x')
x_min = -6
x_max = 6
precision_x = 10**8
solve(((x_max-x_min)/((2**l_x)-1))/precision_x, l_x)
print(l_x)
I tried some other simple equations such as:
solve(x**2 = 4, x)
And the later works perfectly; I just do not understand why the former one does not work!
The expression given to solve has an assumed rhs of 0 which no value of l_x can satisfy. Try something like this instead:
from sympy import *
q, r, s, t = symbols("q r s t")
eq = (q-r)/(2**s-1)/t
solve(eq-1,s)
The output is:
[log((q - r + t)/t)/log(2)]
to explicitly create an equation object with a non-zero rhs you can do something like:
solve(Eq(eq,1),s)
It is simple: your equation has no result.
The equation is 12/((2**l_x)-1))/1e8 = 0 and that has no solution.
See what y = 12/((2**x)-1))/1e8 looks like (copied from wolframalpha):
To compare, try solving e.g. 12/((2**l_x)-1))/1e8 = 1 instead:
>>> solve(((x_max-x_min)/((2**l_x)-1))/precision_x - 1, l_x)
[(-log(25000000) + log(25000003))/log(2)]
Works like a charm!

How to solve an exponential equation in Python

Now I have an equation to solve:
exp(x * a)-exp(x * b) = c, where a,b and c are known constants.
I tried sympy and scipy.optimize.fsolve, even brenth and newton. Nothing good. I 'm new to python, like 2 weeks. So pls help me out of this. Thanks!
It's still unclear what you really want. Symbolic- vs. Numerical-optimization and exact solution vs. least-squares solution.
Ignoring this and just presenting the least-squares approach:
from scipy.optimize import minimize_scalar
import math
a = 3
b = 2
c = 1
def func(x):
return (math.exp(x * a) - math.exp(x * b) - c)**2
res = minimize_scalar(func)
print(res.x)
print(res.fun)
Output:
0.382245085908
1.2143546318937163e-19
Alternative example:
a = 5
b = 2
c = -1
Output:
-0.305430244172
0.4546398791780655
That's just a demo in regards to scipy.optimize. This might not be what you want after all.

How to do function composition in Sympy?

I want to do something like h = f(g(x)) and be able to differentiate h, like h.diff(x). For just one function like h = cos(x) this is in fact possible and the documentation makes it clear.
But for function compositions it is not so clear. If you have done this, kindly show me an example or link me to the relevant document.
(If Sympy can't do this, do you know of any other packages that does this, even if it is non-python)
thank you.
It seems that function composition works as you would expect in sympy:
import sympy
h = sympy.cos('x')
g = sympy.sin(h)
g
Out[245]: sin(cos(x))
Or if you prefer
from sympy.abc import x,y
g = sympy.sin('y')
f = g.subs({'y':h})
Then you can just call diff to get your derivative.
g.diff()
Out[246]: -sin(x)*cos(cos(x))
It's named compose; although, I can't find it in the docs.
from sympy import Symbol, compose
x = Symbol('x')
f = x**2 + 2
g = x**2 + 1
compose(f,g)
Out: x**4 + 2*x**2 + 4

Categories

Resources