#!/usr/bin/env python """ an example of using the multigrid class to solve Laplace's equation. Here, we solve u_xx = cos(x) with u(0) = 0.0 and u(1) = 1.0 """ from numarray import * import multigrid # the analytic solution def true(x): return -cos(x) + x*cos(1.0) + 1.0 # the L2 error norm def error(imin, imax, dx, r): # L2 norm of elements in r, multiplied by dx to # normalize return sqrt(dx*sum(r[imin:imax+1]**2)) # test the multigrid solver nx = 128 # left and right boundary conditions lbc = 0.0 rbc = 1.0 a = multigrid.MGfv(nx, lBC = lbc, rBC = rbc, verbose=1) a.initSolution(zeros(nx, Float64)) a.initRHS(cos(a.x[a.imin:a.imax+1])) # solve to a relative tolerance of 1.e-10 a.solve(rtol=1.e-10) v = a.getSolution() # compute the error compared to the true solution e = v - true(a.grids[a.nlevels-1].x) print "L2 error = %g, rel. error from previous cycle = %g, num. cycles = %d" % \ (error(a.imin,a.imax, a.dx, e), a.error, a.numCycles)