Question: This code is python progaming code about solve Kirchoff's law about diffrent way of time scheme. I think this code will be plot a grapgh

This code is python progaming code about solve "Kirchoff's law" about diffrent way of time scheme. I think this code will be plot a grapgh seems like cosine function. But those code ara not same as cosine function, and It's converging at zero. Can you fix the code and it seems like a cosine function?
import numpy as np
import matplotlib.pyplot as plt
# Constants
V =1 # Voltage (V)
LC =1 # Inductance-Capacitance product (F*H)
delta_t =0.1 # Time step (s)
num_steps =500 # Number of time steps
# Initialize arrays
time = np.zeros(num_steps)
voltage_values ={
'Crank-Nicolson': np.zeros(num_steps),
'Runge-Kutta': np.zeros(num_steps),
'Euler-Explicit': np.zeros(num_steps),
}
# Initial condition
voltage_values['Crank-Nicolson'][0]= V
voltage_values['Runge-Kutta'][0]= V
voltage_values['Euler-Explicit'][0]= V
# Numerical schemes
def crank_nicolson(prev_v, LC, delta_t):
return (2* prev_v +2* V * delta_t / LC)/(2+2* delta_t / LC)
def runge_kutta(prev_v, LC, delta_t):
k1=-(prev_v / LC)
k2=-((prev_v + k1* delta_t/2)/ LC)
k3=-((prev_v + k2* delta_t/2)/ LC)
k4=-((prev_v + k3* delta_t)/ LC)
return prev_v +(delta_t /6)*(k1+2*k2+2*k3+ k4)
# Euler-Explicit method is straightforward
for t in range(1, num_steps):
time[t]= t * delta_t
voltage_values['Crank-Nicolson'][t]= crank_nicolson(voltage_values['Crank-Nicolson'][t-1], LC, delta_t)
voltage_values['Runge-Kutta'][t]= runge_kutta(voltage_values['Runge-Kutta'][t-1], LC, delta_t)
voltage_values['Euler-Explicit'][t]= voltage_values['Euler-Explicit'][t-1]-(voltage_values['Euler-Explicit'][t-1]/ LC)* delta_t
# Plotting
plt.figure(figsize=(10,6))
for scheme, values in voltage_values.items():
plt.plot(time, values, label=scheme)
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.title('Voltage-Time for Different Numerical Schemes')
plt.legend()
plt.grid(True)
plt.show()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!