PYTHON PROBLEM: Given in the problem: Note this code is using PYTHON def osc_der
ID: 3803148 • Letter: P
Question
PYTHON PROBLEM:
Given in the problem: Note this code is using PYTHON
def osc_derivatives(state,time): # state is a vector of current values and time is the time array
x, v = state # unpack the incoming array
deriv1 = v
deriv2 = -omega_squared*x # notice that omega_squared is a global variable so we didn't have to send it in through the arguments, although we could have
return deriv1, deriv2
time = np.linspace(0,10,60) # these are the time points we want a solution at
init_conditions = np.array([1,0]) # initial conditions for the two ODEs
omega_squared = 2.0 # this is the (only) parameter for this model
solution = odeint(osc_derivatives, init_conditions, time) # this returns a multidimensional array/list with the solutions in it
plt.plot(time,solution)
plt.xlabel('time')
plt.ylabel('both solutions')
plt.grid()
The Question: The code above gives us a graph of the oscillating derivatives but now how do I use what you know about NumPy arrays, take the solution you just got, break the solution array (using slicing operations) into two separate arrays for each solution, make a new plot using two plot statements with labels, and add a legend. (Note that above we got two solutions into one variable, solution, and used it without breaking it up.) Put your code and plot here
An explaination with the code would be greatly appreciated!!
Explanation / Answer
# making 2 row array for each solution
x = np.solution.reshape(2, len(solution))
sol_1 = x[0, None, :]
sol_2 = x[1, None, :]
plt.plot(time,sol_1)
plt.plot(time,sol_2)
plt.xlabel('time')
plt.ylabel('sol_1 & sol_2')
plt.grid()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.