Expected square matrix? - python

Kindly help in finding out the error.
import sympy as sp
from scipy.linalg import solve
x, y, z,w = sp.symbols('x,y,z,w')
alpha,beta, gamma, delta = sp.symbols('alpha,beta,gamma,delta')
f1 = alpha*y*z - beta*w
f2= gamma*z - delta*x
f3=-alpha*y*z + beta*w + x
f4= -alpha*y*z + beta*w - gamma*z + delta*x
K=solve(f1,f2,f3,f4)
print K
The error showing is
Expected square matrix

scipy.linalg.solve does not solve SymPy equations. Use a SymPy solver. See, for example, http://docs.sympy.org/dev/modules/solvers/solvers.html

Related

How to solve this equation with sympy?

Recently I got a long equation to solve that looks like that.
I've tried to solve this using sympy.solveset(), but it returned ConditionSet which means it couldn't handle this equation. How can I solve this equation using simpy library and if not at least in python? The code that I used:
import sympy as sp
t = sp.symbols('t')
a = 1.46
b = 1.2042 * 10**-4 * ((1.2275 * 10**-5 + t) * sp.ln(1.2275 * 10**-5 + t) - t)
result = sp.solveset(sp.Eq(a, b), t)
print(result)
This is a transcendental equation. It possibly has an analytic solution in terms of the Lambert W function but I'm not sure. I'll assume that you just want a numerical solution which you can get using nsolve:
In [42]: nsolve(a - b, t, 1)
Out[42]: 1857.54700584719

Why Can't Sympy Integrate 1/\sqrt{x^2+x}

I tried this:
import sympy as sy
from sympy.abc import x
sy.integrate(1/sy.sqrt(x**2+x),x)
But sympy simply returned a repeat of the integration instead of giving the result of it which SageMath would do.
This should be easy to integrate.
I'm not sure what's happening. If you knew x to be real and positive, you could try:
import sympy as sy
x = sy.symbols('x', real=True, positive=True)
sol = sy.integrate(1/sy.sqrt(x**2+x), x)
print(sol)
print(sol.doit())
For some reason, this only gives a solution if you add doit().
Output:
Integral(1/(sqrt(x)*sqrt(x + 1)), x)
2*acosh(sqrt(x + 1))

Multiple errors attempting to solve a function with fsolve and sym solve in python

I am trying to solve the function below. I've attempted to use a symbolic solver and fsolve. Both are causing me trouble. First time posting, I apologize in advance if I'm missing something in my question.
Does anyone have a suggestion on how to solve this? I am solving for y, everything else is a known variable.
cos(y) + ((xi - tdd) / y) * sin(y)) - exp(xi - tii)
I attempted this in python using two ways, both did not work. The first is:
import numpy as np
from scipy.optimize import fsolve
import sympy as sym
from sympy import *
def fi(y):
return ((cos(y) + ((xi - tdd) / y) * sin(y)) - exp(xi - tii))
y = fsolve(fi,0.01)
With this code I get this error:
AttributeError: 'ImmutableDenseNDimArray' object has no attribute 'could_extract_minus_sign'
I also tried this:
y = symbols('y')
init_printing(use_unicode=True)
yi = solve(cos(y) + ((xi - tdd) / y) * sin(y)) - exp(xi - tii))
And got this error:
NotImplementedError: multiple generators [y, tan(y/2)] No algorithms are implemented to solve equation y*(10000000000000000*(-tan(y/2)**2 + 1)/(tan(y/2)**2 + 1) - 9849605264665270) - 300789470669454*tan(y/2)/(tan(y/2)**2 + 1)
This is how I solved it in Matlab (i and j because I have x values in a matrix that need to be solve):
fi = #(y,x) (cos(y) + (((x-tdd)/y)*sin (y))) - exp((x - tii));
yi(i) = fzero(#(y) fi(y,xi(i,j)),.01);
As I already addressed in a comment, the solve function isn't geared to solve such equations. More information can be found here.
Regarding fsolve, it appears that the problem is caused because you are using the sin, cos and exp functions from sympy. If you replace them with the functions from the math module the code should work.
Specifically, your code should look like this:
import math
from scipy.optimize import fsolve
def fi(y):
return ((math.cos(y) + ((xi - tdd) / y) * math.sin(y)) - math.exp(xi - tii))
y = fsolve(fi, 0.01)

Differentiation of a multivariate function via SymPy and evaluation at a point

I want to take the derivative of a multivariable function using SymPy and then for a) the symbolic result to be printed and then b) the result of the derivative at a point to be printed. I'm using the following code
import math as m
import numpy
import scipy
#define constants
lambdasq = 0.09
Ca = 3
qOsq = 2
def f1(a,b,NN,ktsq,x):
return NN*x**(-a)*ktsq**b*m.exp(m.sqrt(16*Ca/9*m.log(1/x)*m.log((m.log(ktsq/lambdasq))/m.log(qOsq/lambdasq))))
from sympy import *
x = symbols('x')
def f2(NN,a,b,x,ktsq):
return -x*diff(m.log(f1),x)
This runs but I can't find a way to get the symbolic result to be printed and when I try to evaluate at a point, say e.g adding in print(f2(0.3,0.1,-0.2,0.1,3)) I get an error
TypeError: must be real number, not function
When I replace f1 with its symbolic representation, I get instead the error
ValueError:
Can't calculate 1st derivative wrt 0.100000000000000.
So I can summarise my question as follows
a) How to print out a symbolic derivative and its value at a point when I call diff(m.log(f1),x) (i.e without having to replace f1 by its actual representation)
b) If I have to use the symbolic representation in the differentiation (i.e use diff(m.log(NN*x**(-a)*ktsq**b*m.exp(m.sqrt(16*Ca/9*m.log(1/x)*m.log((m.log(ktsq\
/lambdasq))/m.log(qOsq/lambdasq))))),x) then how to print out the symbolic derivative and its value at a point?
New to Python so hopefully there is a relatively simple fix.
Thanks!
I'm posting this answer since this thread is #1 on my search engine when searching for 'simpy multivariate differentiation' and might help someone.
example 1
import sympy as sp
def f(u):
return (u[0]**2 + u[1]**10 + u[2] - 4)**2
u = sp.IndexedBase('u')
print(sp.diff(f(u), u[0]))
outputs
4*(u[0]**2 + u[1]**10 + u[2] - 4)*u[0]
This is the derivative of f(u) wrt u[0]
example 2
if we want the whole jacobian, we can do:
for i in range(3):
print(sp.diff(f(u), u[i]))
which outputs
4*(u[0]**2 + u[1]**10 + u[2] - 4)*u[0]
20*(u[0]**2 + u[1]**10 + u[2] - 4)*u[1]**9
2*u[0]**2 + 2*u[1]**10 + 2*u[2] - 8
we can define a temp function and copy paste these lines
def temp(u):
return np.array([
4*(u[0]**2 + u[1]**10 + u[2] - 4)*u[0],
20*(u[0]**2 + u[1]**10 + u[2] - 4)*u[1]**9,
2*u[0]**2 + 2*u[1]**10 + 2*u[2] - 8,
])
temp([1., 1., 1.])
this outputs array([ -4., -20., -2.])
and to verify
from autograd import grad
gradient = grad(f)
gradient([1., 1., 1.])
this outputs: [array(-4.), array(-20.), array(-2.)]
Note:This is just a simple showcase how you can do multivariate derivatives in sympy. I hope I can help someone with this
First, math functions are numeric, they cannot work with SymPy's symbols. Use the corresponding functions from SymPy (exp, log, sqrt) which you already imported with from sympy import *:
def f1(a, b, NN, ktsq, x):
return NN*x**(-a)*ktsq**b*exp(sqrt(16*Ca/9*log(1/x)*log((log(ktsq/lambdasq))/log(qOsq/lambdasq))))
Second, within f2 you are trying to differentiate f1. But f1 is a callable Python function, not a SymPy expression. You need to pass in some arguments to get a SymPy expression, which can then be differentiated.
def f2(NN, a, b, x0, ktsq):
return (-x*diff(log(f1(a, b, NN, ktsq, x)), x)).subs(x, x0)
Here the numeric arguments, except the value x0, are passed to f1, resulting in a SymPy expression containing x. That is a thing to be differentiated. After that, the numeric value x0 is substituted for x.
print(f2(0.3,0.1,-0.2,0.1,3)) # 0.366748952743614
A take-away point is that SymPy differentiates expressions, not functions. There is no concept of f' in SymPy, only f'(x).

Rewrite equation as polynomial

from sympy import *
K, T, s = symbols('K T s')
G = K/(1+s*T)
Eq1 =Eq(G+1,0)
I want to rewrite equation Eq1 with sympy as polynomial: 1+K+T*s==0
How would I do this?
I spent some hours of searching and trying simplifications methods but could not find a elegant, short solution.
The actual problem in SymPy:
from IPython.display import display
import sympy as sp
sp.init_printing(use_unicode=True,use_latex=True,euler=True)
Kf,Td0s,Ke,Te,Tv,Kv,s= sp.symbols("K_f,T_d0^',K_e,T_e,T_v,K_v,s")
Ga= Kf/(1+s*Tv)
Gb= Ke/(1+s*Te)
Gc= Kf/(1+s*Td0s)
G0=Ga*Gb*Gc
G1=sp.Eq(G0+1,0)
display(G1)
How to tell Sympy to rewrite equation G1 as polynomial in shape s^3*(...)+s^2*(...)+s*(...)+(...)=... ?
The actual problem from textbook: http://i.imgur.com/J1MYo9H.png
How it should look like: http://i.imgur.com/RqEDo7H.png
The two equations are equivalent.
Here's what you can do.
import sympy as sp
Kf,Td0s,Ke,Te,Tv,Kv,s= sp.symbols("K_f,T_d0^',K_e,T_e,T_v,K_v,s")
Ga= Kf/(1+s*Tv)
Gb= Ke/(1+s*Te)
Gc= Kf/(1+s*Td0s)
G0=Ga*Gb*Gc
Throw away the denominator
eq = (G0 + 1).as_numer_denom()[0]
Expand the equation and collect terms with powers of s.
eq = eq.expand().collect(s)
Final Equation
Eq(eq, 0)
Eq(K_e*K_f**2 + T_d0^'*T_e*T_v*s**3 + s**2*(T_d0^'*T_e + T_d0^'*T_v + T_e*T_v) + s*(T_d0^' + T_e + T_v) + 1, 0)

Categories