Solving ordinary differential equations and systems
with DSolve and NDsolve functions and visualization of the result with Plot[Evaluate[ ]]
Example 1. We solve the linear differential equation of the first kind y' = - x y with respect to y[x]. We get a formula for the general solution which depends on one arbitrary constant C[1]. In the second line we store the solution in the variable ' u ' by extracting from a list with the operation [[ ]].
DSolve[y'[x]== -x*y[x], y[x],x]
u=y[x] /.%[[1]]
Example 2. We find a particular solution by replacing the constant C[1] with a selected value and visialize the result with the Plot function since it is in analythical form (formula).
w=u /.C[1]->1
g1=Plot[w,{x,-5,5}]
Example 3. The equation from Example 1 becomes a Cauchy problem (initial value problem) if we set a condition for the value of the required function y[x] at a given initial point, for example at x=0, y= -2. We plot the solution in a suitable interval.
DSolve[ {y'[x]== -x*y[x],y[0]==-2}, y[x],x] (* Compare the syntax of DSolve with Example 1*)
w1=y[x] /.%[[1]] (* Store the solution in w1 *)
Plot[w1,{x,0,5}]
Example 4. The same basic problem from example 3 can be solved numerically by using the NDSolve function. In actuality this function is used primarily when it is not possible to obtain the solution analythically in the form of a formula, or if the formula is too complicated. Almost all basic problems can be solved with it, but the result is in the form of a group of numbers which Mathematica interpolates when needed.
In the first line we approximately solve the problem in a defined interval, in the second line we pull out a value of the required function y in the point x=1.2 and in the third we print the exact value which is calculated by the formula found in advance and stored in w1. There is a difference in the seventh decimal symbol.
NDSolve[ {y'[x]==-x* y[x],y[0]==-2}, y,{x,0,2}]
y[1.5] /.%
w1 /. x->1.5
Example 5. Here we show how the graphics of the solution is visualized and calculate the value of y[x] in the point x=0.5.
NDSolve[ {y'[x]== y[x],y[0]==-2}, y,{x,0,2}]
Plot[ Evaluate[y[x]/.%],{x,0,2}]
y[0.5] /.%%
Example 6. Here we solve the basic problem for a system of two ordinary differential equations and show the graphics of the obtained results.
u1= y'[x]== z[x]
u2= z'[x] == -y[x]
u10= y[0]==0
u20= z[0]==1
NDSolve[{u1,u2,u10,u20}, {y ,z }, {x,0,Pi}]
g3=Plot[ Evaluate[y[x] /.%], {x,0,Pi}]
g4=Plot[ Evaluate[z[x] /.%%], {x,0,Pi}]
Example 7. Simultaneous visualization of the two graphics.
Show[g3,g4]
Created by Mathematica (December 21, 2007)