C++ PROGRAMMING FOR SCIENCE AND ENGINEERING
by Ronald S. Remmel
1811 Parkfair Ct., Katy, TX 77450
phone: 281-578-8117; e-mail: remmellabs@juno.com web site: www.remmellabs.com
Copyright 2014
TABLE OF CONTENTS
Each .c++ program has extensive comments. For some of the advanced programs,
explanatory write-ups are provided in .pdf files written in plain English
with mathematical equations; see the list of .pdf files at the end below.
The CD-ROM has the following files:
contents This file
intro Introduction
Linux Running C++ programs under Red Hat Linux
Windows Running under Windows & Borland Turbo C++
other Running under other systems
LIBRARY INCLUDE FILES (Put these in folder /usr/include/c++/4.4.0)
ansi.h Standard functions, compatible with ANSI C++
fft.h Fast Fourier transform
matrix.h Matrix functions
matrixz.h Complex matrix functions
spherharm.h Spherical harmonics library
plot.h Plotting functions for Hewlett Packard printers
schema.h Electronic circuit plotting functions
EASY PROGRAMS
hello.c++ Types a message
numbers.c++ Calculates with various numbers
loops.c++ Demonstrates various ways of looping
convert.c++ Converts English and metric units of volume
videogam.c++ Shows how grade-schoolers can write an adventure game
quest.c++ Computer game written by one of my computer camp kids
arrays.c++ Shows use of arrays
fib1.c++ Calculates Fibonacci numbers
fib2.c++ Graphs Fibonacci numbers
primes.c++ Finds 348,514 prime numbers
asmprimes.c++ Assembly language version finds primes up to 640,000,000.
ethan.c++ Finds prime factors of an integer
goldbach.c++ Tests Goldbach conjecture about prime numbers
sudoku.c++ Solves Sudoku puzzles of 9x9 arrays of integers
rubic.c++ Try but fail to solve rubic cube by rotating many angles.
rubic2.c++ Try but fail to solve rubic cube by rotating random angles.
MANIPULATING STRINGS AND READING/WRITING TO FILES
teacher.c++ Asks fill-in-the-blank questions about geology and math
sort.c++ Sorts strings of ASCII characters into order
parsdemo.c++ Parses a sentence into words using string functions in ansi.h
combine.c++ Combines two files
sorte.c++ Sorts a file containing e-mail addresses into order
dump.c++ Dumps a file to show numerical values of its bytes
runoff.c++ Prints a file with variable margins
PLOTTING ON HEWLETT PACKARD PRINTERS
plotintr.c++ Describes HP GL/2 plotting language and basic plotting functions
geometry.c++ First grade geometry quiz--names of shapes
3D.c++ Draws objects in 3-dimensional perspective
COMPUTER ART
spiral.c++ Draws logarithmic spirals for coloring
mandenbr.c++ Displays the Mandenbrot set
julian.c++ Displays the Julian set
EVALUATING FUNCTIONS
func.c++ Shows use of a function
power.c++ Computes integer powers
polydemo.c++ Demonstrates the polynomial function
complex.c++ Complex arithmetic
sqrt.c++ Iterative calculation of square root
sqrtMPFR.c++ Calculate sqrt(2) to 30,000,000 digits using MPFR functions
lissajou.c++ Plots Lissajous (sinusoidal) figures
euler.c++ Calculates Euler's number
sin.c++ Calcules sine by power series
pi4000.c++ Calculates pi to 4000 digits accuracy; read pi4000.pdf.
Uses high-precision arithmetic functions.
errf.c++ Calculates the error function
chisqfun.c++ Calculates the chi-square distribution function
bessel1.c++ Numerically calculates Bessel's functions; read file bessel1.pdf
bessel2.c++ Power series for Bessel functions; read file bessel2.pdf
bessel3.c++ Computes one of the roots of a Bessel function
legendre.c++ Plots Legendre functions for n = 0..7; read file legendre.pdf
spherh1.c++ Theory of spherical harmonic functions; read file spherh1.pdf
spherh2.c++ Spherical harmonics for large l and m; read file spherh2.pdf
mandenbr.c++ Displays the Mandenbrot set
julian.c++ Displays the Julian set
zeta.pdf Riemann zeta function write-up
zeta1.c++ Riemann zeta function for real s
zeta2.c++ Riemann zeta function zeroes--graph
zeta3.c++ Riemann zeta function--calculate first zero
zeta4.c++ Polar plot of zeta( 0.5 + y*i )
FINDING ROOTS OF FUNCTIONS
root.c++ Finds root of nonlinear functions
quadrat.c++ Solves quadratic formula
cubic.c++ Solves cubic equation
rootz1.c++ Graphically shows locations of complex roots
rootz2.c++ Numerically finds roots of a complex function
TESTING RANDOMNESS
Functions _rand() and _random() produce real pseudorandom numbers uniformly
distributed between 0 and 1. _random() is a SHUFFLED version of _rand() to
eliminate correlations; thus use _random(), not _rand().
Function _ranorm() is a Gaussian-distributed generator.
random1.c++ Uniformity test for random numbers: function _rand()
random2.c++ Mean, variance and moment tests of function _rand()
random3.c++ Correlation test of random number generator
random4.c++ Test of _rand() and _random(): simulates flipping coins and
tabulates lengths of series of heads
random5.c++ Coin flipping generator _ranbit(): means test
random6.c++ Coin flipping generator, second means test
random7.c++ Flips coins and tabulates lengths of series of heads
random8.c++ Tests _ranorm for runs above and below the mean
random9.c++ Tests _ranorm for up and down runs
random10.c++ Tests Kanada's 200,000,000,000 digits of pi for randomness
ranorm.c++ Generates Gaussian-distributed (normal) random numbers
pietc.pdf Article: Can the Bits of Pi, e, log(2), Phi, and sqrt(2) be
used to Generate Random Numbers?
pietc.c++ Computes files of 2^28 bits long for sqrt(2), golden ratio, pi,
e, log(2), and 1/239 for use in the programs pietc1.c++ through
pietc13.c++, which do the statistical tests described in the
article.
pietc4.c++ This is the most interesting program, which flips coins and
tabulates lengths of series of heads to test randomness.
GENERATING RANDOM NUMBERS AND COMPUTING MONTE-CARLO INTEGRALS
poisson.c++ Generates Poisson-distributed random numbers
code.c++ Produces secret codes using pseudorandom numbers
MonteHall.c++ Uses random numbers to evaluate stragety for "Let's Make a Deal"
pi.c++ Calculates pi using random numbers
montedem.c++ Calculates volume of sphere by Monte Carlo integration
inverssq.c++ Gravitation from sphere acts like mass is concentrated at center
illumin.c++ Calculates nonuniformity of illumination from light bulbs
PROBABILITY AND STATISTICS PROGRAMS
avdev.c++ Calculates average and standard deviation
maxlik1.c++ Tests fairness of a coin by likelihood method; read maxlik1.pdf
maxlik2.c++ Maximum likelihood method to estimate star temp.; maxlik2.pdf
chisqfit.c++ Does chi-square fit to data; read file chisqfit.pdf
correl.c++ Correlation coefficients. Read file correl.pdf.
SOLVING MATRIXES
mulmdemo.c++ Shows matrix multiplication
eqsm.c++ Solves linear equations by Gaussian elimination
eqsmp.c++ Same, but uses pivoting to avoid divide-by-zero error
invm.c++ Inverts matrix by Gaussian elimination
invmp.c++ Same, but uses pivoting
det.c++ Calculates determinate
matrixz.c++ Demonstrates complex matrix functions in library
network.c++ Linear networks in frequency domain using matrixes; network.pdf
wheatstone.c++ Calculates Wheatstone bridge using matrixes; read network.pdf.
asmaddm.c++ Adds matrixes with inline assembly language for speed.
asmmulm.c++ Multiplies matrixes with inline assembly language.
asmeqsm.c++ Solves linear equations with inline assembly language.
NUMERICAL DIFFERENTIATION: Read file differentiation.pdf.
deriv1.c++ Formulas for calculating derivatives numerically
deriv2.c++ Matrix method for calculating derivatives of order n
NUMERICAL INTEGRATION: Read file integration.pdf.
integ1.c++ Rectangle rule (definition) for integration
integ2.c++ Numerical integration by Simpson's rule
integ3.c++ Calculation of coefficients for higher-order integration
integ4.c++ Higher-order integration formulas of arbitary accuracy
integ5.c++ Gauss-Legendre integration formulas
integ6.c++ Gauss-Legendre quadrature for n=7 points
integfig.c++ Draws figure for rectangle rule
SOLVING ORDINARY DIFFERENTIAL EQUATIONS
expde.c++ Solves differential equation for y = exp(t)
expde2.c++ More accurate method for solving differential equations
sincos.c++ Solves differential equation for sine and cosine
expimag.c++ Exponential of an imaginary number
newton1.c++ Numerically solves Newton's laws of motion (read newton1.pdf)
newton2.c++ Artillery shell (read newton2.pdf)
newton3.c++ Escape velocity (read newton3.pdf)
newton4.c++ Circular, elliptical, and hyperbolic orbits (read newton4.pdf)
newton5.c++ The three-body problem (notes are in program)
newton6.c++ The orbit function and theory (read newton6.pdf)
newton7.c++ Improved orbit function (read newton7.pdf)
catenary.c++ Solves diff. eqs. of hanging chain (read catenary.pdf)
rc.c++ Solves RC circuit numerically
lcr.c++ Solves LCR circuit
twintee.c++ Solves twin-tee filter in time domain
neuron.c++ Reproduces the Hodgkin-Huxley model of a neuron
WAVES
harmonic.c++ Solves simple harmonic oscillator numerically (harmonic.pdf)
wave1.c++ Numerically solves waves on a wire (wave1.pdf)
wave2.c++ Same as wave1, but a ramp input
coax.c++ Generates wave on coaxial cable numerically (coax.pdf)
SOLVING SAMPLED-TIME PROBLEMS AND FOURIER TRANSFORMS. Read file fourier.pdf.
fourier.c++ The Fourier series of a square wave.
ft.c++ Demonstrates discrete Fourier transform on N=6 points
fft.c++ Demonstrates fast Fourier transform of a square wave
fft.h Library file for FFT
DIGITAL FILTERS. Read file DigitalFilter.pdf.
dfilter1.c++ First-order low-pass digital filter
dfilter2.c++ Second-order low-pass filter
dfilter3.c++ Bandpass filter
dfilter4.c++ Fourth-order Butterworth filter
dfilter5.c++ Integrator
dfilter6.c++ Differentiator
SOLVING PARTIAL DIFFERENTIAL EQUATIONS
laplace.c++ Solves Laplace's equation numerically; read file laplace.pdf
magnet.c++ Draws magnetic field throughout a dual square coil
magnet2.c++ Calculates magnetic field using Monte Carlo integration
magnet3.c++ Same as magnet.c++, but computes field at nine points
QUANTUM MECHANICS: Read file hydrogen.pdf
wavepack.c++ Graphs wave function of a free electron
hydrogen.c++ Graphs radial wave functions of hydrogen atoms
hydrog2.c++ Plot of measurements of random electron locations in hydroden
asm.pdf ARTICLE: EMBEDDING ASSEMBLY LANGUAGE INTO C++
asmintro.c++ 8 simple programs showing embedding
asmadd.c++ Adds 256-bit integers with carry bit
asmshiftleft.c++ Shifts 256-bit integer left
asmmul.c++ Multiplies two 256-bit integers
asmaddm.c++ Adds two matrixes using symbols to compute addresses
asmmulm.c++ Multiplies two matrixes using symbols to compute addresses
asmeqsm.c++ Solves linear equations using symbols to compute addresses
asmranbit.c++ Assembly random number generator flips coins
asmprimes.c++ Computes prime numbers up to 640,000,000
GNU MPFR Multiprecision Floating Reliable Library: This library of functions
can do calculations to as many digits as can fit into RAM memory. Directions
for installing MPFR are given in the sample program piMPFR.c++. The MPFR
instruction manual can be downloaded from http://www.mpfr.org.
sqrtMPFR.c++
COMPUTING PI TO MANY DIGITS: Read piarticle.pdf.
piMPFR.c++ Remmel's half-angle algorithm; read pi.pdf.
piBorwein50.c++ Borwein's summation formula giving 50 digits per term
piSchonhage.c++ Schonhage's modification of Gauss AGM iterative algorithm
piquad.c++ Borwein's quadratic iterative algorithm
picubic.c++ Borwein's cubic iterative algorithm
piquartic.c++ Borwein's quartic iterative algorithm
piquintic.c++ Borwein's quintic iterative algorithm
pinonic.c++ Borwein's nonic iterative algorithm
SPECIAL PROGRAMS
stars.c++ Graphs luminosities, temperatures, masses and lifespans of stars
schema.c++ Draws electronic circuit diagrams
etch.c++ Draws printed circuit patterns
arm.c++ Measurement of arm movements with an eye movement monitor
armrand.c++ Simulates measuring many random arm movements with noise
--------------------------------------------------------------------------
The following .pdf files are write-ups in English and math:
arm2.pdf Use of an Electromagnetic Eye Movement Monitor for Easy
Measurement of Arm Movements
asm.pdf Embedding Assembly Language Into C++
bessel1.pdf Derivation of Bessel's functions
bessel2.pdf Second Bessel function program
catenary.pdf Derivation of the catenary function (hanging chain)
chisqfit.pdf Derivation of chi-square (least-squares) fitting method
coax.pdf Derivation of the wave equation for a coaxial cable
correl.pdf Cross correlation and auto-correlation
differentiation.pdf Methods of numerical differentiation
DigitalFilter.pdf Use of a computer to filter signals
fourier.pdf The Fourier and fast Fourier transforms
harmonic.pdf The simple harmonic oscillator with damping
hydrogen.pdf Schrodinger's equation derived for the hydrogen atom
integration.pdf Various methods of numerical integration
laplace.pdf Laplace's differential equation
legendre.pdf Legendre polynomials for n = 0...7
maxlik1.pdf Maximum likelihood method to test fairness of a coin
maxlik2.pdf Maximum likelihood method to estimate star temperature
network.pdf Linear networks in the frequency domain using matrixes
newton1.pdf Newton's equations: uniform velocity and acceleration
newton2.pdf Artillery shell
newton3.pdf Vertical escape velocity
newton4.pdf Circular, elliptical, and hyperbolic orbits
newton6.pdf The orbit function
newton7.pdf Improved orbit function
pi.pdf A More Efficient Algorithm to Compute Pi
piarticle.pdf Lots of Ways to Compute Pi
spherh1.pdf Spherical harmonics derived from the wave equation
spherh2.pdf Spherical harmonics of any order
wave1.pdf Derivation of the wave equation for a string
zeta.pdf The Riemann zeta function