How can I get the constant from an ODE in python? - python

My task is to calculate the constant from an ODE. So, I don't want to plot the function, I just want to get the result of the differential equation, and after that I need to calculate the c based on this assumption: v0=120 when t0=0.
I have started to implement with help of sympy module, and I get successfully the following result:[120.000000000000 -2.23606797749979/tanh(C1)]
But, after that I have no idea how I could get c1. Is it possible?
import inline as inline
import sympy as sp
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
from sympy import *
from sympy import lambdify
t=Symbol('t')
v = map(Function, 'v')
v=Function('v')
k=2
g=10
i=dsolve(Eq( Derivative(v(t), t)+k*v(t)**2, g), v(t))
j=i.subs(v(t),120).subs(t,0).evalf()
print(i)
print(j)
h=j.args
k=np.array(h)

If you want the value of C1 corresponding to the values of a given t and v(t) you could first solve for it and then substitute in the known values:
>>> C1 = [_ for _ in i.free_symbols if _.name == 'C1'][0]
>>> vals = solve(i, C1)
>>> [_.subs(v(t),120).subs(t,0).n(2) for _ in vals]
[-0.019 + 3.1*I, -0.019]

Related

How write the symbolic variable in the sympy EDO dsolve

Good afternoon,
I'm coming here as I noticed something unusual in the results of dsolve() in sympy.
from sympy import *
from sympy.abc import x,y
import sympy as s
import numpy as np
n = symbols('n', complex=True)
s.init_printing()
f=Function('x')
eq=Derivative(f(x),x,x)+n**2*f(x)
a=dsolve(eq, f(x))
eq2=Derivative(f(x),x,x)+2**2*f(x)
a2=dsolve(eq2, f(x))
display(a.subs(n,2)==a2)
The generated result is False.
Looking only at the result of 'a' it is already possible to see that there are differences in the results using the symbolic variable 'n'.
Could anyone guide if I'm doing it the right way?
The solution sets are equivalent:
In [2]: a
Out[2]:
-ⅈ⋅n⋅x ⅈ⋅n⋅x
x(x) = C₁⋅ℯ + C₂⋅ℯ
In [3]: a2
Out[3]: x(x) = C₁⋅sin(2⋅x) + C₂⋅cos(2⋅x)
These are just different ways of writing the general solution. If you had declared n to be real then the sin/cos form would be used.
The two forms are related by Euler's formula:
https://en.wikipedia.org/wiki/Linear_differential_equation#Second-order_case

Unexpected result in Trace function sympy: Trace(A*B) not equal to Trace(B*A)

I am puzzled about why the following code produces False in sympy, Python
import sympy
from sympy import MatrixSymbol, Trace
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)
Trace(A*B)==Trace(B*A)
while it is well-known that Tr(AB)=Tr(BA) https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Trace_of_a_product
Any help is appreciated!
Alright I see you're not happy with letting it go. Here is how you actually get sympy to calculate that for you
from sympy import shape, Matrix, symbols, trace
import numpy as np
from itertools import product
A = Matrix(np.array(symbols([f"a_{i}{j}" for i,j in product(range(1,4),range(1,4))])).reshape(3,3))
B = Matrix(np.array(symbols([f"b_{i}{j}" for i,j in product(range(1,4),range(1,4))])).reshape(3,3))
trace(A*B)-trace(B*A) == 0
Which finally gives you True.

System of First Order ODEs in Python

I have seen how to solve systems of ODEs in Python, but all of the examples I have seen were "standard" equations. What I mean by standard is that the equations do not say "derivative of one function = expression that contains derivative of another function".
Here is a sample system I am trying to solve numerically. Initial conditions are x(0) = 5, y(0) = 3, z(0) = 2, and all initial derivatives are 0:
x'(t) + 4y(t) = -3y'(t)
y'(t) + ty(t) = -2z'(t)
z'(t) = -2y(t) + x'(t)
I am not 100% sure how to code this. Here is what I have tried:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
def ODESystem(f,t):
x = f[0]
y = f[1]
z = f[2]
Now, what do I define first: dydt, dxdt or dzdt. Is there a way for me to define one expression that "hangs around" before I use it to define another expression?
You do not need to solve anything manually, you can just as well do
def ODESystem(f,t):
x,y,z = f
return np.linalg.solve([[1,3,0],[0,1,2],[-1,0,1]], [-4, -t, -2])*y
Nevermind; I am stupid. I can keep on substituting into the third equation until I get an equation for z'(t) that does not include any other derivatives.

Runtime Return array size Error Python

I am trying to solve a simple differential equation using odeint function. It is giving an error with matching size of array. I think my initial_condi is not matching with the equation function. I can't figure it out where actually the error is. Blow is the error and code. Any help would be greatly appreciated.
RuntimeError: The size of the array returned by func (1) does not match the size of y0 (3)
from scipy import *
from scipy.integrate import odeint
from operator import itemgetter
import matplotlib as plt
from matplotlib.ticker import FormatStrFormatter
from pylab import *
from itertools import product
import itertools
from numpy import zeros_like
import operator
initial_condi = [1, 1, 1]
t_range = arange(0.0,60.0,1.0)
def equation(w, t):
T,I,V = w
dT= V*I*10.24-T*1.64
return dT
result_init = odeint(equation, initial_condi, t_range)
plt.plot(t, result_init[:, 0])
plt.show()
As your state vector has 3 components, the return value of the ODE function also needs to have 3 components, the derivatives of T,I,V. You only provided dT, but should return [dT, dI, dV ].

dsolve error: 'numpy.ndarray' object is not callable

import sympy as sp
sp.init_printing()
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
Can somebody help me please?
The variable y is a numpy.ndarray, not a callable, which means it cannot be used like a function (or other callable) would: y(); only indexed, like y[]. You probably meant to write sp.Derivative(y[x],x).
I suspect that you want to solve a differential equation involving only scalar variables.
>>> import sympy as sp
>>> sp.var('x')
x
>>> f = sp.Function('f')
>>> sp.dsolve(sp.Derivative(f(x),x)-(1/(1+x**2)-2*f(x)**2))
Eq(f(x), x**3*(2*C1*(C1 - 1) - 1)/3 + x**5*(C1*(16*C1*(-9*C1 + 1) - 13*C1 + 2) - 20*C1 + 12)/30 + C1 + C1*x + C1*x**4*(13*C1 + 2)/6 - C1**2*x**2 + O(x**6))
If you have an initial condition and need to solve for the arbitary constant then Represent a first order differential equation in numpy might help. (I don't know for sure.)

Categories

Resources