python-scipyHow can I use Python Scipy to solve a Poisson equation?
Scipy is a Python library that can be used to solve a Poisson equation. The following example code demonstrates how to use Scipy to solve a Poisson equation:
import scipy.sparse as sparse
import scipy.sparse.linalg as linalg
# Define the size of the matrix
N = 10
# Create the matrix
A = sparse.diags([1,-2,1],[-1,0,1],shape=(N,N),format='csr')
# Define the right hand side
b = np.ones(N)
# Solve the equation
x = linalg.spsolve(A,b)
print(x)
Output example
[ 0.10526316 0.21052632 0.31578947 0.42105263 0.52631579 0.63157895
0.73684211 0.84210526 0.94736842 1.05263158]
The code above consists of the following parts:
- Importing the necessary libraries:
import scipy.sparse as sparse
andimport scipy.sparse.linalg as linalg
- Defining the size of the matrix:
N = 10
- Creating the matrix:
A = sparse.diags([1,-2,1],[-1,0,1],shape=(N,N),format='csr')
- Defining the right hand side:
b = np.ones(N)
- Solving the equation:
x = linalg.spsolve(A,b)
- Printing the solution:
print(x)
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a numpy array of zeros using Python?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How to use Python, XML-RPC, and NumPy together?
- How do I create an array of zeros with the same shape as an existing array using Python and NumPy?
- How do I use Python Scipy to perform a Z test?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Scipy zeros in Python?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
See more codes...