import numpy as npOnce the code is finished, the last u will have the final values. More detailed code along with the sparse matrix version is here.

import scipy.linalg

# Number of internal points

N = 200

# Calculate Spatial Step-Size

h = 1/(N+1.0)

k = h/2

x = np.linspace(0,1,N+2)

x = x[1:-1] # get rid of the '0' and '1' at each end

# Initial Conditions

u = np.transpose(np.mat(10*np.sin(np.pi*x)))

# second derivative matrix

I2 = -2*np.eye(N)

E = np.diag(np.ones((N-1)), k=1)

D2 = (I2 + E + E.T)/(h**2)

I = np.eye(N)

TFinal = 1

NumOfTimeSteps = int(TFinal/k)

for i in range(NumOfTimeSteps):

# Solve the System: (I - k/2*D2) u_new = (I + k/2*D2)*u_old

A = (I - k/2*D2)

b = np.dot((I + k/2*D2), u)

u = scipy.linalg.solve(A, b)

## Sunday, January 30, 2011

### Heat Equation solution using Finite Difference and Crank-Nicholson

I rewrote parts of this code so that it used dense (non-sparse) matrices instead of sparse matrices, for demonstration purposes. The code is below:

Subscribe to:
Post Comments (Atom)

## No comments:

## Post a Comment