SIGNUMDATA
  • Home
  • DisPol
  • SevesoTool
  • Courses
  • Numerics
  • MDsquad
  • Team
  • Contact

Introduction to
​Numerical Programming
A Practical Guide for Scientists and Engineers
​Using Python and C/C+

Picture
  • Book
  • Author
  • Contents
  • Libraries
  • Graphics
  • Programs
<
>
Picture
The book is devoted to the general field of numerical programming, with emphasis on methods specific to computational physics and engineering.

The book is addressed to advanced undergraduate and graduate students in natural sciences and engineering, with the aim of being suited as curriculum material for a one- or two-semester course in numerical programming based on Python or C/C++. The book may also be used for independent study or as a reference material beyond academic studies. It may be useful, for instance, as an introductory text for researchers preparing to engage in scientific computing, or engineers needing effective numerical tools for applicative calculations.

All the materials on this web site are released as 'open source', with the only request that the authorship and the book are mentioned.

Please also visit the book's web site at CRC Press / Taylor & Francis Group.
​
Feedback to the author is highly appreciated!
Picture
Titus A. Beu, Professor Emeritus, Dr.
University Babeş-Bolyai
Faculty of Physics
Department of Biomolecular Physics
1, M. Kogălniceanu Street, Cluj-Napoca
Romania, 400084
Mobile: +40-752-441608
Email: [email protected]
​
Email: [email protected]
I am Titus Adrian Beu, professor emeritus at the Faculty of Physics of the "Babeș-Bolyai" University from Cluj-Napoca, Romania.

I have been active in the broader field of computational physics for more than 40 years, both in research and academia. My research has been theoretical and computational in nature, covering a multitude of topics. These have evolved from Tokamak plasma and nuclear reactors in the 1980s, collision theory and molecular cluster spectroscopy in the 1990s, fullerenes and nanofluidics in the 2000s, to complex biomolecular systems of interest in drug delivery, in recent years.

The development of complex computer codes has always been at the heart of all the research projects I have conducted. In parallel, I gave university lectures on general programming techniques and advanced numerical methods, computer simulation methods, and advanced molecular dynamics.
​
The material covered in the book comes together from my research experience and the computational physics courses taught at the university. The core material has undergone a continuous process of distillation and reformulation over the years, following the evolution of modern programming concepts and technologies.

I am happy to receive opinions, questions, requests,...

​Have fun reading the book and practicing numerical programming!
1 Approximate Numbers
1.1 Sources of errors in numerical calculations
1.2 Absolute and relative errors
1.3 Representation of numbers
1.4 Significant digits
1.5 Errors of elementary operations
1.5.1 Error of a sum
1.5.2 Error of a difference
1.5.3 Error of a product
1.5.4 Error of a quotient
References

2 Basic Programming Techniques
2.1 Programming concepts
2.2 Functions and parameters
2.3 Passing arguments to Python functions
2.4 Passing arguments to C/C++ functions
2.5 Arrays in Python
2.6 Dynamic array allocation in C/C++
2.7 Basic matrix operations
References

3 Elements of Scientific Graphics
3.1 The Tkinter package
3.2 The Canvas widget
3.2.1 Commonly used Canvas items
3.2.2 Methods for updating Canvas widgets
3.3 Simple Tkinter applications
3.4 Plotting functions of one variable
3.5 The graphics library graphlib.py
3.5.1 Auxiliary functions
3.5.2 Routines for plotting functions
3.5.3 Simple 3D rendering routines
3.5.4 Histograms
3.6 Creating plots in C++ using the library graphlib.py
References

4 Sorting and Indexing
4.1 Introduction
4.2 Bubble sort
4.3 Insertion sort
4.4 Quicksort
4.5 Indexing and ranking
4.6 Implementations in C/C++
4.7 Problems
References

5 Evaluation of Functions
5.1 Evaluation of polynomials by Horner's scheme
5.2 Evaluation of analytic functions
5.3 Continued fractions
5.4 Orthogonal polynomials
5.5 Spherical harmonics. Associated Legendre functions
5.6 Spherical Bessel functions
5.7 Implementations in C/C++
5.8 Problems
References

6 Algebraic and Transcendental Equations
6.1 Root separation
6.2 Bisection method
6.3 Method of false position
6.4 Method of successive approximations
6.5 Newton's method
6.6 Secant method
6.7 Birge-Vieta method
6.8 Newton's method for systems of nonlinear equations
6.9 Implementations in C/C++
6.10 Problems
References

7 Systems of Linear Equations
7.1 Introduction
7.2 Gaussian elimination with backward substitution
7.3 Gauss-Jordan elimination
7.4 LU factorization
7.5 Inversion of triangular matrices
7.6 Cholesky factorization
7.7 Tridiagonal systems of linear equations
7.8 Block tridiagonal systems of linear equations
7.9 Complex matrix equations
7.10 Jacobi and Gauss-Seidel iterative methods
7.11 Implementations in C/C++
7.12 Problems
References

8 Eigenvalue problems
8.1 Introduction
8.2 Diagonalization of matrices by similarity transformations
8.3 Jacobi method
8.4 Generalized eigenvalue problems for symmetric matrices
8.5 Implementations in C/C++
8.6 Problems
References
9 Modeling of Tabulated Functions
9.1 Interpolation and regression
9.2 Lagrange interpolation polynomial
9.3 Neville's interpolation method
9.4 Cubic spline interpolation
9.5 Linear regression
9.6 Multilinear regression models
9.7 Nonlinear regression. The Levenberg-Marquardt method
9.8 Implementations in C/C++
9.9 Problems
References

10 Integration of Functions
10.1 Introduction
10.2 Trapezoidal Rule; A Heuristic Approach
10.3 The Newton-Cotes Quadrature Formulas
10.4 Trapezoidal Rule
10.5 Simpson's Rule
10.6 Adaptive Quadrature Methods
10.7 Romberg's Method
10.8 Improper Integrals: Open Formulas
10.9 Midpoint Rule
10.10 Gaussian Quadratures
10.11 Multidimensional integration
10.12 Adaptive multidimensional integration
10.13 Implementations in C/C++
10.14 Problems
References

11 Monte Carlo Method
11.1 Introduction
11.2 Integration of functions
11.3 Importance sampling
11.4 Multidimensional integrals
11.5 Generation of random numbers
11.6 Implementations in C/C++
11.7 Problems
References

12 Ordinary Differential Equations
12.1 Introduction
12.2 Taylor series method
12.3 Euler's method
12.4 Runge-Kutta methods
12.5 Adaptive step size control
12.6 Methods for second-order ODEs
12.7 Numerov's method
12.8 Shooting methods for two-point problems
12.9 Finite-difference methods for linear two-point problems
12.10 Implementations in C/C++
12.11 Problems
References

13 Partial Differential Equations
13.1 Introduction
13.2 Boundary-value problems for elliptic differential equations
13.3 Initial-value problems for parabolic differential equations
13.3.1 Explicit finite-difference method
13.3.2 von Neumann stability analysis
13.3.3 Implicit finite-difference method
13.3.4 Crank-Nicolson method
13.3.5 Spatially variable diffusion coefficient
13.4 Time-dependent Schrödinger equation
13.5 Initial-value problems for hyperbolic differential equations
13.6 Implementations in C/C++
13.7 Problems
References

A Dynamic array allocation in C/C++

B Basic operations with vectors and matrices

C Embedding Python in C/C++
References

D The numerical libraries numxlib.py and numxlib.h

E The graphics library graphlib.py based on Tkinter

F The C++ interface to the graphics library graphlib.py

G List of programs by chapter

Index

​The numerical libraries numxlib.py and numxlib.h

The partial numerical libraries developed along the chapters compose the general libraries numxlib.py and numxlib.h. The corresponding Python and C/C++ routines have identical names and functionalities. The only naming exception concerns the modules random1.py and random.h, and this is due to the existence of a standard Python module named random.py.

numxlib.h also includes memalloc.h, containing dynamic memory allocation routines for vectors and matrices in C/C+.
numxlib.py.zip
File Size: 40 kb
File Type: zip
Download File

numxlib.h.zip
File Size: 40 kb
File Type: zip
Download File

​numxlib.py          Library of numerical methods for Python.

    
​numxlib.h             Library of numerical methods for C.

    

​Component modules

sort.py​ / sort.h          Routines for sorting, indexing, and ranking numeric sequences:
BubbleSort - Sorts a numeric sequence using bubble sort.
InsertSort - Sorts a numeric sequence by direct insertion.
QuickSort - Sorts a numeric sequence using Quicksort.
Index - Indexes a numeric sequence by direct insertion.
Rank - Ranks a numeric sequence based on the array of indexes.
Index2 - Performs the indexing of two correlated arrays by direct insertion.
specfunc.py​ / specfunc.h          ​Routines for evaluating special functions:
Chebyshev - Evaluates Chebyshev polynomials of the first kind and their derivatives using the recurrence relation.
Legendre - Evaluates Legendre polynomials and their derivatives using the recurrence relation.
aLegendre - Evaluates associated Legendre functions.
Laguerre - Evaluates Laguerre polynomials and their derivatives using the recurrence relation.
aLaguerre - Evaluates associated Laguerre polynomials.
Hermite - Evaluates Hermite polynomials and their derivatives using the recurrence relation.
SpherY - Evaluates the real and imaginary parts of spherical harmonics.
SBessy - Evaluates spherical Neumann functions.
SBessj - ​Evaluates spherical Bessel functions.
roots.py​ / roots.h          Routines for determining real roots of real functions:
Bisect - Determines a real root of a function by the bisection method.
FalsPos - Determines a real root of a function by the false position method.
Iter - Determines a real root of a function by the method of successive approximations.
Newton - Determines a real root of a function by the Newton-Raphson method using the analytical derivative.
NewtonNumDrv - Determines a real root of a function by the Newton-Raphson method using the numerical derivative.
Secant - Determines a real root of a function by the secant method.
BirgeVieta - Determines real roots of polynomials by the Birge-Vieta method.
Jacobian - Calculates the Jacobian of a system of multidimensional functions using central finite differences.
NewtonSys - ​Solves a system of nonlinear equations by Newton's method.
linsys.py​ / linsys.py          Routines for solving systems of linear equations:
Gauss - Solves a matrix equation by Gaussian elimination with partial pivoting.
GaussJordan0 - Solves a matrix equation by Gauss-Jordan elimination with partial pivoting.
GaussJordan1 - Solves a matrix equation by Gauss-Jordan elimination with partial pivoting and matrix inversion.
GaussJordan - Solves a matrix equation by Gauss-Jordan elimination with complete pivoting and matrix inversion.
LUFactor - Performs LU factorization of a matrix by Doolittle's method.
LUSystem - Solves a linear system using the LU decomposition of its matrix.
MatInv - Performs matrix inversion using LU factorization.
MatTriInv - Inverts a triangular matrix.
Cholesky - Performs the Cholesky factorization of a symmetric positive-definite matrix.
CholeskySys - Solves a positive-definite linear system using the Cholesky decomposition of its matrix.
MatSymInv - Inverts a positive-definite matrix using the Cholesky factorization.
TriDiagSys - Solves a linear system with tridiagonal matrix.
GaussSeidel - Solves a system of linear equations by the Gauss-Seidel method.
eigsys.p y​ / eigsys.h          Routines for solving eigenvalue problems:
Jacobi Solves an eigenvalue problem for a real symmetric matrix using the Jacobi method.
EigSym - Solves a generalized eigenvalue problem for real symmetric (positive-definite) matrices.
EigSort - Sorts a set of eigenvalues and eigenvectors according to the eigenvalues.
​modfunc.py​ / modfunc.h          Routines for modeling tabular dependences by interpolation or regression:
Lagrange - Evaluates the Lagrange interpolating polynomial for a set of data points.
Neville - Evaluates the Lagrange interpolating polynomial by Neville's method.
Spline - Performs cubic spline interpolation.
LinFit - Performs linear regression on a set of data points.
MultiFit - Performs multilinear regression on a set of data points.
PolFit - Performs polynomial regression on a set of data points.
MarqFit - ​Performs nonlinear regression based on the Levenberg-Marquardt method.
integral.py​ / integral.h          1D and 3D integrators for real functions with real variables:
qTrapz - Function integrator based on the trapezoidal rule.
qSimpson - Function integrator based on Simpson's rule.
qTrapzCtrl - Adaptive integrator based on the trapezoidal rule.
qSimpsonCtrl - Adaptive integrator based on Simpson's rule.
qRomberg - Adaptive integrator based on Romberg's method.
qImprop1 - Adaptive integrator for improper integrals of the first kind (with infinite limits).
qImprop2 - Adaptive integrator for improper integrals of the second kind (with singular integrable limits).
qMidPoint - Adaptive integrator based on the midpoint rule.
xGaussLeg - Generates abscissas and weights for Gauss-Legendre quadratures.
qGaussLeg - Gauss-Legendre integrator.
xGaussLag - Generates abscissas and weights for Gauss-Laguerre quadratures.
qGaussLag - Gauss-Laguerre integrator.
qTrapz3D - 3D integrator based on the trapezoidal rule.
xSimpson - Generates integration points and weights for Simpson's rule.
qSimpson3D - 3D integrator based on Simpson's rule.
qGaussLeg3D - 3D integrator based on Gaussian quadratures.
qSimpsonAng - Integrator in spherical angular coordinates based on Simpson's rule.
qSimpsonSph - Integrator in spherical coordinates based on Simpson's rule.
qGaussSph - Integrator in spherical coordinates based on Gaussian quadratures.
qSimpsonCyl - ​Integrator in cylindrical coordinates based on Simpson's rule.
random1.py​ / random.h          Routines for generating pseudorandom numbers:
randLCG1 - Linear congruential random number generator based on specifications from Press et al. 2002.
randLCG2 - Linear congruential random number generator based on specifications from Rapaport 2004.
randMCG - Multiply-with-Carry random number generator based on specifications of George Marsaglia.
randNrm - Generates random numbers with normal distribution based on the central limit theorem.
randNrm2 - Returns two random numbers with normal distribution.
randMet - ​Random number generator based on the Metropolis method.
ode.py / ode.h          Routines for solving systems of ordinary differential equations:
Euler - Euler propagator for systems of first-order ODEs.
EulerPC - Euler predictor-corrector propagator for systems of first-order ODEs.
RungeKutta - Fourth-order Runge-Kutta solver for Cauchy problems for systems of first-order ODEs.
RKadapt - Adaptive ODE solver using step-halving and the Runge-Kutta method.
RKFehlberg - Adaptive ODE solver based on the Runge-Kutta-Fehlberg method.
Euler1 - Euler propagator for a second-order ODE.
EulerCromer1 - Euler-Cromer propagator for a second-order ODE.
Verlet1 - Verlet propagator for a second-order ODE.
Euler2 - Euler propagator for a system of second-order ODEs.
EulerCromer - Euler-Cromer propagator for a system of second-order ODEs.
Verlet2 - 2D velocity Verlet propagator for a single particle.
Verlet - Velocity Verlet propagator for a system of particles in interaction.
EulerCromerQM - Euler-Cromer integrator for the 1D Schrödinger equation.
Numerov - Numerov integrator for the 1D Schrödinger equation.
Propag - Propagates the solution of a second-order ODE on a regular mesh using the Euler-Cromer method.
Shoot - Solves a two-point boundary-value problem for a second-order ODE using the shooting method.
ShootQM - Solves the 1D Schrödinger equation using the shooting method.
Bilocal - Linear bilocal problem solver based on the finite-difference method.
pde.py / pde.h          Routines for solving partial differential equations:
Poisson0 - Solver for the 2D Poisson equation in Cartesian coordinates with Dirichlet boundary conditions.
PoissonXY - Solver for the 2D Poisson equation in Cartesian coordinates with arbitrary boundary conditions.
Poisson2D - Solver for the 2D Poisson equation in Cartesian coordinates on an irregular domain.
PropagFTCS - Explicit forward-time central-space propagator for the diffusion equation.
PropagBTCS - Implicit backward-time central-space propagator for the diffusion equation.
PropagCN - Crank-Nicolson propagator for the diffusion equation.
PropagDiff - Crank-Nicolson propagator for the diffusion equation with variable diffusion coefficient.
PropagQTD - Crank-Nicolson propagator for the Schrödinger equation based on tridiagonal solver.
PropagQGS - Crank-Nicolson propagator for the Schrödinger equation using the Gauss-Seidel method.
PropagWave - ​Explicit forward-time central-space propagator for the classical wave equation.
utils.py / utils.h          Utility routines:
Nint - Returns the nearest integer to its real-type argument.
Sign - Transfers the sign of its second argument onto the absolute value of the first argument.
Magn - Returns the order of magnitude of its argument as a power of 10.
Index - ​Indexes a numeric sequence by direct insertion

​Auxiliary libraries

memalloc.h          Functions for dynamic memory allocation of vectors and matrices in C:
Vector, FreeVector - Allocate/deallocate a double vector with indices in the range [imin,imax].
Matrix, FreeMatrix - Allocate/deallocate a double matrix, with row and column indices in the range [imin,imax] x  [jmin,jmax].
IVector, FreeIVector - Allocate/deallocate an int vector with indices in the range [imin,imax].
IMatrix, FreeIMatrix - Allocate/deallocate an int matrix, with row and column indices in the range [imin,imax] x  [jmin,jmax].
CVector, FreeCVector - Allocate/deallocate a complex vector with indices in the range [imin,imax].
CMatrix, FreeCMatrix - Allocate/deallocate a complex matrix, with row and column indices in the range [imin,imax] x  [jmin,jmax].
coords.py / coords.h          Routines for transforming the coordinates of systems of particles:
MovetoCM - Moves a system of n particles to the CM system.
PrincipalAxes - Rotates a set of n particles to the system of principal axes.
elemfunc.py / elemfunc.h          Routines for evaluating elementary functions:
Poly - Evaluates a real polynomial using Horner's scheme.
PolyDerive - Returns the coefficients of the derivative of a real polynomial.
PolyDivide - Returns the coefficients of the division of a real polynomial by a binomial (x-x0).
matutil.py / matutil.h          Utility routines for basic operations with vectors and matrices:
MatRead - Reads from the keyboard the elements of matrix.
MatPrint - Prints the elements of a matrix on the display.
MatPrintTrans - Prints the elements of a transposed matrix on the display.
MatZero - Zeros the elements of a matrix.
MatCopy - Copies a matrix into another matrix.
MatTrans - Replaces a square matrix by its transpose.
MatDiff - Returns the difference of two matrices.
MatProd - Returns the product of two matrices.
MatPow - Returns a power of a square matrix.
MatNorm - Returns the max norm of a matrix.
VecPrint - Prints the elements of a vector on the display.
VecZero - Zeros the elements of a vector.
VecCopy - Copies a vector into another vector.
VecDiff - Returns the difference of two vectors.
VecNorm - Returns the 2-norm of a vector.
MatVecProd - ​Returns the product of matrix and a vector.

​The graphics library grafxlib.py

​The graphics library graphlib.py, accompanying the book was renamed grafxlib.py to avoid confusions with a recent standard module of Python. grafxlib.py is used throughout to produce runtime graphics both from Python and C/C++. The C/C++ applications can access grafxlib.py via the interface grafxlib.h.
grafxlib.py
Graphics library for Python based on Tkinter.
​grafxlib.h
C/C++ interface to the library grafxlib.py.
grafxlib.py.zip
File Size: 8 kb
File Type: zip
Download File

grafxlib.h.zip
File Size: 3 kb
File Type: zip
Download File


​Sample plots

Picture
Picture
Picture
Picture
Picture
Picture
Picture
Picture
Picture
Picture

​Simple example - plotting a function of one variable:

Python code:

    
C code:

    
To see all graphics applications, go to section Programs.

​Structure of grafxlib.py


    

​Auxiliary functions

​Limits extends an arbitrary real interval so as to include an integer number of equal subintervals of length expressible as d x 10p, with d = 2, 5, or 10 and p integer. Output: xmin and xmax--adjusted values of, scale--scale factor (10p), nsigd--number of significant digits required to optimally represent the limits, nintv--resulting integer number of subintervals. Limits is typically called by Plot and MultiPlot to adjust the x and y user intervals for optimal labeling of the axes, by Contour to resize contour plots, and by ColorLegend to resize color legends.

FormStr determines the optimal labeling format for a given value x on the basis of previous output from Limits (scale factor scale and number of significant digits nsigd), and separates the mantissa in mant[] and the exponent of 10 in expn[].

ColorLegend and RGBcolors are used to display a color legend alongside a contour plot.

​Routines for plotting functions

Plot plots a real function of one variable. The arrays x[] and y[] should contain the coordinates pairs of the representative points. The plot color is specified by the parameter col, and the corresponding arguments can be RGB colors or standard color names. The plot-style parameter sty can take one of the integer values: 0--scatter plot, 1--line plot, 2--polar plot, 3--drop lines, 4--histogram. fxmin, fxmax, fymin, fymax are the fractional limits of the plotting domain on the canvas. xtext, ytext, and title are the titles of the axes and of the whole graph. "None" as axis title inhibits the labeling of the axis altogether. The independent coordinate x[] is not supposed to vary monotonically, and this also enables the representation of cyclic functions.

MultiPlot plots several functions of one variable on a single graph. The representative points of the nplot plots are contiguously packed in sequenced sets in the same vectors x[] and y[], with an additional array, n[], specifying the ending index for each set. sig[] is only used when error bars (sty[i]=4) are employed for at least one of the plots. col[] contains the colors of the individual plots and sty[] specifies the corresponding style parameters: 0--scatter plot, 1--line plot, -1--line plot with dashed line, 2--polar plot, -2--polar plot with dashed line, 3--drop lines, 4--error bars, -4--error bars and continuous line. For ioptx set to 0, the x-axis is resized automatically, while for nonzero ioptx, the axis is resized based on the provided user interval [xminp,xmaxp]. The y-axis is resized analogously, in accordance with the option iopty.

Contour creates the contour plot of a real function of two variables, defined in the domain [xmin,xmax] x [ymin,ymax] and specified by its values z[i][j] at the nx x ny nodes of a regular grid. The representation is confined to z-values between zmin and zmax.

​Simple 3D rendering routines

PlotParticles depicts systems of particles as spheres, optionally connected by cylindrical bonds. The input consists of the coordinate vectors x[], y[], and z[] of the centers of the n particles, their radii r[], and colors col[]. dmax is a cutoff distance beyond which the particles are no longer linked by bonds (with dmax set to 0, no bonds at all are depicted). The ioptx and iopty parameters control whether the x and y-axis, respectively, are to be sized automatically in order to reveal the entire structure (ioptx=0 and iopty=0), or, instead, the input user coordinates (xminp,xmaxp) and (yminp,ymaxp) are to be considered to crop the image.

PlotStruct is a simple 3D rendering routine for structures specified by nodes and triangular surfaces defined between them. The input to PlotStruct consists of the coordinate vectors x[], y[], and z[] of the n nodes and the indexes ind1[], ind2[], and ind3[] of the nodes defining each of the n3 triangles.

​Histograms

​Histograms can be plotted using Plot with the style parameter sty=4. Before plotting a histogram, the data need to be binned. HistoBin is normally called in three successive modes:
  1. Initializing the histogram--defining the boundaries of the bins and zeroing the corresponding frequencies.
  2. Binning new observations--assigning them to the appropriate bins and incrementing the corresponding occurrence frequencies.
  3. Normalizing the histogram--dividing the frequencies by the total number of observations.
The input parameters are xnew--new value to be binned, a and b--limits of the total binning interval (data falling outside are ignored), n--number of bin boundaries (n-1 is the number of bins), and iopt--option specifying the mode in which the routine is to be used: 0--to initialize the histogram, 1--to bin the new value xnew, and 2--to normalize the histogram. The output consists of the vectors x[], containing the bin boundaries, and y[], representing the (normalized or unnormalized) frequencies. Specifically, y[i] is the frequency of observations occurring in the interval [x[i],x[i+1]).

​Creating plots in C/C++ using the library grafxlib.py

The C/C++ programs including the interface file grafxlib.h can seamlessly call with similar syntax the Python graphics functions defined in the module grafxlib.py. The proper functioning of grafxlib.h requires access to grafxlib.py (and to the therein imported module utils.py)) either by search path settings or by simply placing the three files in the same folder.

​List of programs by chapter

​The file names of the application programs contain the complete information on their location within the folder structure descending from the root folder /INP/. The general format of the file names is Pnn-name.py or Pnn-name.cpp, whereby nn indicates the chapter folder /INP/Chnn/ and the extension indicates the respective subfolder, that is, /INP/Chnn/Python/ or /INP/Chnn/C/.

A trailing "~" in their names, indicates updated versions of the files.

​2 Basic Programming Techniques

p02.zip
File Size: 4 kb
File Type: zip
Download File

Listing File Output
2.1
2.2
P02-Fact_global.py
P02-Fact_global.cpp
Factorial with global variables.
2.3
2.4
P02-Fact_comb.py
P02-Fact_comb.cpp
Combinations using a factorial function.
P02-Fact_recur.py
P02-Fact_recur.cpp
Factorial based on recursivity.
2.7
2.9
2.10
P02-Swap~.py
P02-Swap.c
P02-Swap.cpp
Returning swapped arguments from a function.
2.8 P02-Swap_list~.py Returning swapped list elements from a function.
2.18
2.19
P02-MatOp.py
P02-MatOp.cpp
Check of identity (A B)T = BT AT for random arrays A and B.

​3 Elements of Scientific Graphics

p03.zip
File Size: 12 kb
File Type: zip
Download File

Listing File Output
3.1 P03-Tk.py Creating a Tk root widget.
3.2 P03-Tk_Label.py Creating a tkinter Label widget.
3.3 P03-Tk_Canvas0.py Creating a Tkinter Canvas widget.
3.4 P03-Tk_Canvas.py Tkinter Canvas widget with simple graphic elements.
3.5 P03-Tk_Clock0.py Python clock application built with Tkinter.
3.6 P03-Tk_Clock.py Python clock using callback function.
3.7 grafxlib0.py Minimal Python library based on Tkinter for plotting functions.
3.8 P03-Plot0~.py Plotting a function of one variable.
P03-Plots~.py
P03-Plots~.cpp
Plotting a function of one variable with different styles.
3.10
3.17
P03-MultiPlot~.py
P03-MultiPlot~.cpp
Plotting two functions on the same graph.
3.11
3.18
P03-Contour~.py
P03-Contour~.cpp
Contour plot of a function of two variables.
3.12 P03-PlotParticles~.py 3D rendering of a molecule.
3.13 P03-Plotstruct~.py 3D rendering of an airplane.
3.15 P03-Histogram~.py Histogram of a sequence of random numbers.

3.16
P03-Plot~.py
P03-Plot~.cpp
Plotting a function of one variable.

4 Sorting and Indexing

p04.zip
File Size: 10 kb
File Type: zip
Download File

Listing File Output
4.2 P04-Sort0.py
P04-Sort0.cpp
Generic use of sorting routines.
4.7 P04-Sort1.py
P04-Sort1.cpp
Ascending sorting and indexing of an array.
4.9 P04-Sort2.py
P04-Sort2.cpp
Ascending indexing of two correlated arrays.
4.12
4.13
P04-SortQuart.py
P04-SortQuart.cpp
Sorting the elements of an array into quartiles.
4.15
4.16
P04-Sort3.py
P04-Sort3.cpp
Sorting and indexing of a random sequence using direct insertion.
P04-SortComp0.py
P04-SortComp0.cpp
Comparison of operation counts for sorting methods.
P04-SortComp1.py
P04-SortComp1.cpp
Comparison of operation counts for sorting methods (graphic).

​5 Evaluation of Functions

p05.zip
File Size: 10 kb
File Type: zip
Download File

Listing File Output
5.2 P05-Poly.py
P05-Poly.cpp
Elementary operations with polynomials.
P05-Exp.py
P05-Exp.cpp
Evaluates the exponential from its power-series and continued fraction representations.
P05-TanPlot.py
P05-TanPlot.cpp
Plots the tangent function using the continued fraction representation.
5.12
5.13
P05-PolyPlot.py
P05-PolyPlot.cpp
Plots a polynomial and its derivative
5.16
5.17
P05-SpherYPlot~.py
P05-SpherYPlot~.cpp
Plots squared spherical harmonics.
5.18
5.19
P05-SpherY.py
P05-SpherY.cpp
Checks the addition theorem for spherical harmonics.
P05-CBessPlot.py
P05-CBessPlot.cpp
Cylindrical Bessel and Neumann functions, based on the corresponding spherical functions.
P05-RadProbH.py
P05-RadProbH.cpp
Radial probability densities for the hydrogen atom.

​6 Algebraic and Transcendental Equations

p06.zip
File Size: 14 kb
File Type: zip
Download File

Listing File Output
6.2
6.16
P06-Bisect.py
P06-Bisect.cpp
Real roots of a real function by the bisection method.
6.5 P06-Iter.pybr
P06-Iter.cpp
Real root of a real function by the method of successive approximations.
P06-Newton.py
P06-Newton.cpp
Real roots of a real function by the Newton-Raphson method.
6.11 P06-BirgeVieta.py
P06-BirgeVieta.cpp
Real roots of a polynomial by the Birge-Vieta method.
6.14 P06-NewtonSys.py
P06-NewtonSys.cpp
Real roots of systems of nonlinear equations by the Newton-Raphson method.
P06-CompareZeros.py
P06-CompareZeros.cpp
Compare solvers for algebraic and transcendental equations.
6.17 P06-Kepler.py
P06-Kepler.cpp
Solution of Kepler’s equation.
6.18 P06-Fraunhofer.py
P06-Fraunhofer.cpp
Intensity distribution for Fraunhofer diffraction.
6.19 P06-Planck.py
P06-Planck.cpp
Planck’s law of black body radiation.
6.20 P06-NewtonSys1.py
P06-NewtonSys1.cpp
Intersection points of a circle and a parabola.
6.21 P06-NewtonSys2.py
P06-NewtonSys2.cpp
System of three nonlinear equations.

​7 Systems of Linear Equations

p07.zip
File Size: 14 kb
File Type: zip
Download File

Listing File Output
7.2 P07-Gauss.py
P07-Gauss.cpp
Solution of a linear system by Gaussian elimination.
7.6 P07-GaussJordan.py
P07-GaussJordan.cpp
Solution of a matrix equation by Gauss-Jordan elimination.
7.11 P07-MatInv.py
P07-MatInv.cpp
Check of matrix inversion based on LU factorization.
7.18 P07-TriDiagSys.py
P07-TriDiagSys.cpp
Solution of linear system with tridiagonal matrix by LU factorization.
P07-GaussSeidel.py
P07-GaussSeidel.cpp
Solution of linear system by the Gauss-Seidel method.
7.21
7.22
P07-GaussJordan1.py
P07-GaussJordan1.cpp
Solution of a matrix equation by Gauss-Jordan elimination.
7.23
7.24
P07-LUFactor.py
P07-LUFactor.cpp
Solution of multiple linear systems by LU factorization.
7.25 P07-TriDiagSys1.py
P07-TriDiagSys1.cpp
Solution of system with tridiagonal matrix by LU factorization.
7.26 P07-MatDetIdent.py
P07-MatDetIdent.cpp
Check of identity for determinant of matrix product.
7.27 P07-MatInvIdent.py
P07-MatInvIdent.cpp
Check of identity for inverse of matrix product.
7.28 P07-MatSymInv.py
P07-MatSymInv.cpp
Inversion of symmetric positive-definite matrix by Cholesky factorization.
7.29 P07-Wavelet.py
P07-Wavelet.cpp
Solution of linear system for Daubechies D4 wavelet.

​8 Eigenvalue problems

p08.zip
File Size: 11 kb
File Type: zip
Download File

Listing File Output
8.3 P08-Jacobi.py
P08-Jacobi.cpp
Eigenvalues and eigenvectors of symmetric matrices by the Jacobi method.
8.6
8.7
P08-EigInvMat.py
P08-EigInvMat.cpp
Eigenvalues and eigenvectors of the inverse of a symmetric matrix.
8.8
8.9
P08-String.py
P08-String.cpp
Normal modes of a loaded string with fixed ends.
8.11 P08-MomInert.py
P08-MomInert.cpp
Rotation of a molecule to the system of principal axes.
8.12 P08-Airplane.py
P08-Airplane.cpp
Rotation of an airplane.
8.13 P08-Hueckel.py
P08-Hueckel.cpp
Application of the Hueckel method for the benzene molecule.
8.15 P08-Roothaan.py
P08-Roothaan.cpp
H2O.dat
Solution of the Roothaan equation for the H2O molecule.

​9 Modeling of Tabulated Functions

p09.zip
File Size: 40 kb
File Type: zip
Download File

Listing File Output
9.3 P09-Lagrange0.py
P09-Lagrange0.cpp
Interpolation using the Lagrange polynomial.
P09-Lagrange.py
P09-Lagrange.cpp
Lagrange interpolation for a sequence of arguments.
P09-Lagrange1.py
P09-Lagrange1.cpp
Lagrange interpolation for a list of arguments.
9.5 P09-Neville0.py
P09-Neville0.cpp
Interpolation using Neville’s method.
9.7 P09-Spline0.py
P09-Spline0.cpp
Interpolation using cubic splines.
9.7 P09-SplineLJ.py
P09-SplineLJ.cpp
Cubic spline interpolation of Lennard-Jones potential.
P09-LinFit0.py
P09-LinFit0.cpp
Linear fit of a model to observed data points.
9.10 P09-MultiFit0.py
P09-MultiFit0.cpp
Application of multilinear regression.
9.14 P09-MarqFit0.py
P09-MarqFit0.cpp
fit.dat
Nonlinear regression using the Levenberg-Marquardt method.
9.18
9.19
P09-Neville.py
P09-Neville.cpp
Lagrange interpolation and Neville’s method for uniformly distributed data points and equally spaced abscissas of the data points.
9.20 P09-Spline.py
P09-Spline.cpp
Interpolation using cubic splines.
9.21 P09-LinFit.py
P09-LinFit.cpp
Linear fit by the least-squares method.
9.23 P09-Halides.py
P09-Halides.cpp
halides.dat
Absorption maximum of halides by linear and nonlinear regression.
P09-PolFit.py
P09-PolFit.cpp
Polynomial fit by the least-squares method.
9.24 P09-MultiFit.py
P09-MultiFit.cpp
Multilinear fit by the least-squares method.
P09-MultiFit_pol.py
P09-MultiFit_pol.cpp
Polynomial fit using multilinear algorithm.
9.26 P09-MarqFit.py
P09-MarqFit.cpp
fit2.dat
Nonlinear fit by the Levenberg-Marquardt method.
9.28 P09-Tides.py
P09-Tides.cpp
tides.dat
Tidal analysis based on Levenberg-Marquardt and multilinear fits.
9.29 P09-Fourier.py
P09-Fourier.cpp
Fourier analysis of simple signals based on multilinear fit.

​10 Integration of Functions

p10.zip
File Size: 17 kb
File Type: zip
Download File

Listing File Output
10.1 P10-qTrapz.py
P10-qTrapz.cpp
Function integration using the trapezoidal rule.
10.6 P10-qAdapt.py
P10-qAdapt.cpp
Application of adaptive quadratures based on the trapezoidal rule, Simpson's rule, and Romberg's method.
10.9 P10-qImprop.py
P10-qImprop.cpp
Improper integrals of the first and second kind.
10.15 P10-qGauss.py
P10-qGauss.cpp
Gauss-Legendre and Gauss-Laguerre quadratures.
10.19 P10-Integ3D.py
P10-Integ3D.cpp
3D integral over toroidal domain using Cartesian coordinates.
10.22 P10-IntegSph.py
P10-IntegSph.cpp
3D integral in spherical coordinates.
10.24 P10-qAdapt3D.py
P10-qAdapt3D.cpp
Adaptive 3D integration on spherical domain.
10.26 P10-qTrapSimpConv.py
P10-qTrapSimpConv.cpp
Convergence study of the trapezoidal and Simpson rules applied to the sine function.
P10-qTrapSimpConv1.py
P10-qTrapSimpConv1.cpp
Convergence study of the trapezoidal and Simpson rules applied to the norm of Legendre functions.
P10-qSpherY.py
P10-qSpherY.cpp
Check of norm of associated Legendre functions (Romberg's method) and spherical harmonics (angular Simpson quadrature).
10.28
10.29
P10-Fresnel.py
P10-Fresnel.cpp
Fresnel integrals and Cornu spiral.
10.30 P10-ElecProbRad.py
P10-ElecProbRad.cpp
Radial localization probability of the electron in the H atom.
10.31 P10-ElecProb.py
P10-ElecProb.cpp
Total localization probability of the electron in the H atom.
10.32 P10-IntegCyl.py
P10-IntegCyl.cpp
3D integral in cylindrical coordinates.
10.34 P10-Integ3D1.py
P10-Integ3D1.cpp
3D integral over toroidal domain using Cartesian coordinates.
10.35
10.36
P10-qAdapt3DTor.py
P10-qAdapt3DTor.cpp
Adaptive 3D integration on toroidal domain.

​11 Monte Carlo Method

p11.zip
File Size: 18 kb
File Type: zip
Download File

Listing File Output
11.1 P11-MC-1D.py
P11-MC-1D.cpp
1D Monte Carlo integration of a function.
11.2 P11-MC-1Ds.py
P11-MC-1Ds.cpp
1D Monte Carlo integration of a function with importance sampling.
P11-MC-1Dg.py
P11-MC-1Dg.cpp
Convergence study of the 1D Monte Carlo integration of a function with/without importance sampling.
11.3 P11-MC-2D.py
P11-MC-2D.cpp
2D Monte Carlo evaluation of the unit circle area.
P11-MC-2Dg.py
P11-MC-2Dg.cpp
Convergence study of the 2D Monte Carlo evaluation of the unit circle area.
11.4 P11-MC-2Ds.py
P11-MC-2Ds.cpp
2D Monte Carlo integration with uniform and Gaussian sampling.
11.5 P11-MC-3D.py
P11-MC-3D.cpp
3D Monte Carlo evaluation of the mass center of a torus.
11.11 P11-MC-1Dx.py
P11-MC-1Dx.cpp
Convergence study of the 1D Monte Carlo integration of a Gaussian function with/without importance sampling.
11.12 P11-MC-2Dx.py
P11-MC-2Dx.cpp
Convergence study of the 2D Monte Carlo integration with uniform, Gaussian, and exponential sampling.
11.13 P11-RandUni.py
P11-RandUni.cpp
Generation of random numbers with uniform distribution.
11.14 P11-RandNrm.py
P11-RandNrm.cpp
Generation of random numbers with normal distribution.

​12 Ordinary Differential Equations

p12.zip
File Size: 52 kb
File Type: zip
Download File

Listing File Output
12.2 P12-ODE.py
P12-ODE.cpp
Solution of Cauchy problem for a system of two first-order ODEs by Euler’s method.
12.4 P12-PendulumRK.py
P12-PendulumRK.cpp
Angular motion of a nonlinear pendulum by the Runge-Kutta method.
12.7 P12-RKFehlberg.py
P12-RKFehlberg.cpp
Adaptive step size control for a system of two first-order ODEs.
P12-RKFehlberg_g.py
P12-RKFehlberg_g.cpp
Adaptive step size control for a system of two first-order ODEs with graphic output.
12.11 P12-PendulumEC.py
P12-PendulumEC.cpp
Angular motion of a nonlinear pendulum by the Euler-Cromer method.
P12-ThrowPC.py
P12-ThrowPC.cpp
Oblique throw of an object with drag using Euler's predictor-corrector method.
P12-ThrowEC.py
P12-ThrowEC.cpp
Oblique throw of an object with drag using the Euler-Cromer method.
12.12 P12-ThrowV.py
P12-ThrowV.cpp
Oblique throw of an object with drag using the velocity Verlet method.
12.15 P12-LegendreSH.py
P12-LegendreSH.cpp
Solution of the differential equation of the Legendre polynomials by the shooting method.
12.17 P12-OscillatorSH.py
P12-OscillatorSH.cpp
Eigenstates of the quantum oscillator by the shooting algorithm based on the Numerov method.
12.19 P12-LegendreBL.py
P12-LegendreBL.cpp
Solution of the differential equation of the Legendre polynomials by the finite-difference method.
12.21 P12-ODEg.py
P12-ODEg.cpp
Cauchy problem for a second-order ODE solved by the Euler and Euler predictor-corrector methods.
P12-ThrowECg.py
P12-ThrowECg.cpp
Hammer throw using the Euler-Cromer method.
12.22 P12-ThrowPCg.py
P12-ThrowPCg.cpp
Hammer throw using Euler’s predictor-corrector method.
12.22 P12-ThrowVg.py
P12-ThrowVg.cpp
Hammer throw using the velocity Verlet method.
12.23 P12-ChargePC.py
P12-ChargePC.cpp
Charged particle orbiting about a fixed charge using Euler’s predictor-corrector method.
12.24 P12-ChargeEC.py
P12-ChargeEC.cpp
Charged particle orbiting about a fixed charge using the Euler-Cromer method.
12.25 P12-ChargeV.py
P12-ChargeV.cpp
Charged particle orbiting about a fixed charge using the velocity Verlet method.
12.26 P12-PendulumRKg.py
P12-PendulumRKg.cpp
Angular motion of a nonlinear pendulum by the Runge-Kutta method.
12.27 P12-PendulumRKT.py
P12-PendulumRKT.cpp
Angular motion of a nonlinear pendulum by the Runge-Kutta method.
P12-PendulumECg.py
P12-PendulumECg.cpp
Angular motion of a nonlinear pendulum by the Euler and Euler-Cromer methods.
12.28 P12-PlanetsV.py
P12-PlanetsV.cpp
Orbital motions of the Earth and Moon by the velocity Verlet method.
12.30 P12-SqWellSHg.py
P12-SqWellSHg.cpp
Quantum eigenstates of a finite square quantum well by the shooting algorithm based on the Numerov method.
P12-OscillatorSHg.py
P12-OscillatorSHg.cpp
Eigenstates of the quantum harmonic oscillator by the shooting algorithm based on the Numerov method.
12.31 P12-LegChebSH.py
P12-LegChebSH.cpp
Legendre and Chebyshev polynomials by the shooting method.
12.32 P12-LegChebBL.py
P12-LegChebBL.cpp
Legendre and Chebyshev polynomials by the finite-difference method.

​13 Partial Differential Equations

p13.zip
File Size: 42 kb
File Type: zip
Download File

Listing File Output
13.3 P13-PoissonXY.py
P13-PoissonXY.cpp
Solution of the 2D Poisson equation in a rectangular domain.
13.5 P13-HeatDisk0.py
P13-HeatDisk0.cpp
Solution of the static heat problem of a conducting disk in Cartesian coordinates.
13.7 P13-Diffusion0.py
P13-Diffusion0.cpp
Finite-difference solution of the 1D diffusion equation.
13.11 P13-Diffusion1.py
P13-Diffusion1.cpp
Finite-difference solution of the 1D diffusion equation with spatially variable diffusion coefficient.
13.14 P13-ScatterQTD0.py
P13-ScatterQTD0.cpp
Scattering of a quantum wave packet using a tridiagonal solver for the 1D Schrödinger equation.
13.15 P13-ScatterQGS0.py
P13-ScatterQGS0.cpp
Scattering of a quantum wave packet using a Gauss-Seidel solver for the 1D Schrödinger equation.
13.17 P13-Wave0.py
P13-Wave0.cpp
Solution of the 1D classical wave equation by the explicit finite-difference method.
13.19 P13-Poisson0.py
P13-Poisson0.cpp
Solution of the 2D Poisson equation in a square domain (Poisson0).
13.20 P13-Poisson1.py
P13-Poisson1.cpp
Solution of the 2D Poisson equation in a rectangular domain (PoissonXY).
P13-Poisson2.py
P13-Poisson2.cpp
Solution of the 2D Poisson equation in a square domain (PoissonXY).
P13-HeatSquare0.py
P13-HeatSquare0.cpp
Steady-state temperature distribution in a thin square conducting plate.
P13-HeatSquare.py
P13-HeatSquare.cpp
Steady-state temperature distribution in a thin square conducting plate.
13.21 P13-HeatDisk.py
P13-HeatDisk.cpp
Steady-state temperature distribution in a thin conducting disk.
13.22 P13-HeatTriangle.py
P13-HeatTriangle.cpp
Steady-state temperature distribution in a thin triangular conducting plate.
13.23 P13-Diffusion2.py
P13-Diffusion2.cpp
Solution of the diffusion equation for spatially variable diffusion coefficient.
13.24 P13-ScatterQTD1.py
P13-ScatterQTD1.cpp
Scattering of a quantum wave packet by a potential barrier using a tridiagonal solver (real-time graphics).
P13-ScatterQGS1.py
P13-ScatterQGS1.cpp
Scattering of a quantum wave packet by a potential barrier using a Gauss-Seidel solver (real-time graphics).
13.25 P13-Wave.py
P13-Wave.cpp
Solution of the 1D classical wave equation by the explicit finite-difference method for two wave number interval widths (∆k = 0.5 and ∆k = 5).

​Appendix C: Embedding Python in C/C++

pyembed.zip
File Size: 2 kb
File Type: zip
Download File

Listing File Output
C.1 operations.py Module operations.py containing functions called from the C/C++ programs C.2, C.3, and C.4.
C.2 PyEmbed1.cpp Calling Python functions with scalar arguments from C++ code.
C.3 PyEmbed2.cpp Calling Python functions with vector arguments from C++ code.
C.4 PyEmbed3.cpp Calling Python functions via C++ wrapper classes.

Contact

Str. Theodor Capidan, Nr. 13-15, Apt. 7
​Cluj-Napoca, RO-400479
www.signumdata.net

[email protected]
+40 752 441 608     ​+40 745 657 751
Proudly powered by Weebly
  • Home
  • DisPol
  • SevesoTool
  • Courses
  • Numerics
  • MDsquad
  • Team
  • Contact