Instant Download Numerical Methods Using Kotlin: For Data Science, Analysis, and Engineering 1st Edition Haksun Li PDF All Chapters
Instant Download Numerical Methods Using Kotlin: For Data Science, Analysis, and Engineering 1st Edition Haksun Li PDF All Chapters
com
https://ebookmass.com/product/numerical-methods-using-
kotlin-for-data-science-analysis-and-engineering-1st-
edition-haksun-li-2/
OR CLICK HERE
DOWLOAD NOW
https://ebookmass.com/product/numerical-methods-using-kotlin-for-data-
science-analysis-and-engineering-1st-edition-haksun-li/
ebookmass.com
https://ebookmass.com/product/numerical-methods-in-environmental-data-
analysis-moses-eterigho-emetere/
ebookmass.com
https://ebookmass.com/product/spatial-analysis-using-big-data-methods-
and-urban-applications-yamagata/
ebookmass.com
https://ebookmass.com/product/the-crimson-queen-dark-halos-
book-3-amanda-aggie/
ebookmass.com
Genetic and Metabolic Engineering for Improved Biofuel
Production from Lignocellulosic Biomass Arindam Kuila
https://ebookmass.com/product/genetic-and-metabolic-engineering-for-
improved-biofuel-production-from-lignocellulosic-biomass-arindam-
kuila/
ebookmass.com
https://ebookmass.com/product/the-wiley-blackwell-companion-to-
hinduism-2nd-edition-gavin-flood/
ebookmass.com
https://ebookmass.com/product/her-ruthless-duke-a-guardian-ward-
regency-romance-rogues-guild-book-1-scarlett-scott/
ebookmass.com
https://ebookmass.com/product/ruthless-kings-a-dark-why-choose-mafia-
romance-black-hollow-isle-book-2-dani-rene/
ebookmass.com
Nutrition, Sustainable Agriculture and Climate Change in
Africa: Issues and Innovative Strategies 1st ed. Edition
Gbadebo Odularu
https://ebookmass.com/product/nutrition-sustainable-agriculture-and-
climate-change-in-africa-issues-and-innovative-strategies-1st-ed-
edition-gbadebo-odularu/
ebookmass.com
Haksun Li, PhD
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
Source Code
All source code used in this book can be downloaded from
github.com/apress/numerical-methods-kotlin.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(github.com/apress). For more detailed information, please visit
www.apress.com/source-code.
Acknowledgments
I never knew that writing a book would be such a tremendous effort,
especially for this book with such wide coverage. It started out as a one-
year project and then was extended to become an almost two-year
project. For eight months in 2021, I basically did nothing other than
write this book, pretty much every day. What would be a better thing to
do during the indefinite COVID-19 lockdown?
This book covers a lot of topics in basic college applied
mathematics, supplemented with a lot of sample code and more than
300 images for illustration. It was a tremendous effort to put the
materials together. I want to thank my team for their incredible support
throughout the writing of this manuscript. They are amazing and this
book would not have happened without them: Kehao Feng, Jingqi Guo,
Shihao Liu, Yang Lu, Hengyu Luo, and Dr. Xueying Ni.
Although we have never met in person, I thank Steve Anglin for
inviting me to write this book, something that I have wanted to do for a
long time but never found sufficient motivation to do. I thank you Mark
Wickham for carefully reviewing my book and making a lot of good
comments and suggestions. Last but not least, I must thank Mark
Powers for pushing me to submit the manuscript. He provided a huge
push for me to sit down at my computer and start typing and meet the
always-missed-and-always-late deadlines. I thank you all for your
patience!
Table of Contents
Chapter 1:Introduction to Numerical Methods in Kotlin/S2
1.1.Library Design
1.1.1.Class Parsimony
1.1.2.Java vs C++ Performance
1.2.Java Scripting
1.2.1.Kotlin Programming Language
1.3.S2
1.3.1.R Replacement
1.3.2.Python Replacement
1.3.3.S2 Online IDE
1.4.About This Book
1.4.1.Sample Code
Chapter 2:Linear Algebra
2.1.Vector
2.1.1.Element-Wise Operations
2.1.2.Norm
2.1.3.Inner Product and Angle
2.2.Matrix
2.2.1.Matrix Operations
2.2.2.Element-Wise Operations
2.2.3.Transpose
2.2.4.Matrix Multiplication
2.2.5.Rank
2.2.6.Determinant
2.2.7.Inverse and Pseudo-Inverse
2.2.8.Kronecker Product
2.3.Matrix Decomposition
2.3.1.LU Decomposition
2.3.2.Cholesky Decomposition
2.3.3.Hessenberg Decomposition and Tridiagonalization
2.3.4.QR Decomposition
2.3.5.Eigen Decomposition
2.3.6.Singular Value Decomposition
2.4.System of Linear Equations
2.4.1.Row Echelon Form and Reduced Row Echelon Form
2.4.2.Back Substitution
2.4.3.Forward Substitution
2.4.4.Elementary Operations
2.4.5.Gauss Elimination and Gauss-Jordan Elimination
2.4.6.Homogeneous and Nonhomogeneous Systems
2.4.7.Overdetermined Linear System
2.5.Sparse Matrix
2.5.1.Dictionary of Keys
2.5.2.List of Lists
2.5.3.Compressed Sparse Row
2.5.4.Sparse Matrix/Vector Operations
2.5.5.Solving Sparse Matrix Equations
Chapter 3:Finding Roots of Equations
3.1.An Equation of One Variable
3.2.Jenkins-Traub Algorithm
3.3.The Bisection Method
3.4.Brent’s Method
3.4.1.Linear Interpolation Method, False Position Method,
Secant Method
3.4.2.Inverse Quadratic Interpolation
3.4.3.Brent’s Method Implementation
3.5.The Newton-Raphson Method
3.5.1.Halley’s Method
Chapter 4:Finding Roots of System of Equations
4.1.System of Equations
4.2.Finding Roots of Systems of Two Nonlinear Equations
4.3.Finding Roots of Systems of Three or More Equations
Chapter 5:Curve Fitting and Interpolation
5.1.Least Squares Curve Fitting
5.2.Interpolation
5.2.1.Linear Interpolation
5.2.2.Cubic Hermite Spline Interpolation
5.2.3.Cubic Spline Interpolation
5.2.4.Newton Polynomial Interpolation
5.3.Multivariate Interpolation
5.3.1.Bivariate Interpolation
5.3.2.Multivariate Interpolation
Chapter 6:Numerical Differentiation and Integration
6.1.Numerical Differentiation
6.2.Finite Difference
6.2.1.Forward Difference
6.2.2.Backward Difference
6.2.3.Central Difference
6.2.4.Higher-Order Derivatives
6.3.Multivariate Finite Difference
6.3.1.Gradient
6.3.2.Jacobian
6.3.3.Hessian
6.4.Ridders’ Method
6.5.Derivative Functions of Special Functions
6.5.1.Gaussian Derivative Function
6.5.2.Error Derivative Function
6.5.3.Beta Derivative Function
6.5.4.Regularized Incomplete Beta Derivative Function
6.5.5.Gamma Derivative Function
6.5.6.Polynomial Derivative Function
6.6.Numerical Integration
6.7.The Newton-Cotes Family
6.7.1.The Trapezoidal Quadrature Formula
6.7.2.The Simpson Quadrature Formula
6.7.3.The Newton-Cotes Quadrature Formulas
6.8.Romberg Integration
6.9.Gauss Quadrature
6.9.1.Gauss-Legendre Quadrature Formula
6.9.2.Gauss-Laguerre Quadrature Formula
6.9.3.Gauss-Hermite Quadrature Formula
6.9.4.Gauss-Chebyshev Quadrature Formula
6.10.Integration by Substitution
6.10.1.Standard Interval
6.10.2.Inverting Variable
6.10.3.Exponential
6.10.4.Mixed Rule
6.10.5.Double Exponential
6.10.6.Double Exponential for Real Line
6.10.7.Double Exponential for Half Real Line
6.10.8.Power Law Singularity
Chapter 7:Ordinary Differential Equations
7.1.Single-Step Method
7.1.1.Euler’s Method (Polygon Method)
7.1.2.Runge-Kutta Family
7.1.3.Convergence
7.1.4.Stability
7.2.Linear Multistep Method
7.2.1.Adams-Bashforth Method
7.3.Comparison of Different Methods
7.4.System of ODEs and Higher-Order ODEs
Chapter 8:Partial Differential Equations
8.1.Second-Order Linear PDE
8.1.1.Parabolic Equation
8.1.2.Hyperbolic Equation
8.1.3.Elliptic Equation
8.2.Finite Difference Method
8.2.1.Numerical Solution for Hyperbolic Equation
8.2.2.Numerical Solution for Elliptic Equation
8.2.3.Numerical Solution for Parabolic Equation
Chapter 9:Unconstrained Optimization
9.1.Brute-Force Search
9.2. C2OptimProblem
9.3.Bracketing Methods
9.3.1.Fibonacci Search Method
9.3.2.Golden-Section Search
9.3.3.Brent’s Search
9.4.Steepest Descent Methods
9.4.1.Newton-Raphson Method
9.4.2.Gauss-Newton Method
9.5.Conjugate Direction Methods
9.5.1.Conjugate Directions
9.5.2.Conjugate Gradient Method
9.5.3.Fletcher-Reeves Method
9.5.4.Powell Method
9.5.5.Zangwill Method
9.6.Quasi-Newton Methods
9.6.1.Rank-One Method
9.6.2.Davidon-Fletcher-Powell Method
9.6.3.Broyden-Fletcher-Goldfarb-Shanno Method
9.6.4.Huang Family (Rank One, DFP, BFGS, Pearson,
McCormick)
Chapter 10:Constrained Optimization
10.1.The Optimization Problem
10.1.1.General Optimization Algorithm
10.1.2.Constraints
10.2.Linear Programming
10.2.1.Linear Programming Problems
10.2.2.First-Order Necessary Conditions
10.2.3.Simplex Method
10.2.4.The Algebra of the Simplex Method
10.3.Quadratic Programming
10.3.1.Convex QP Problems with Only Equality Constraints
10.3.2.Active-Set Methods for Strictly Convex QP Problems
10.4.Semidefinite Programming
10.4.1.Primal and Dual SDP Problems
10.4.2.Central Path
10.4.3.Primal-Dual Path-Following Method
10.5.Second-Order Cone Programming
10.5.1.SOCP Problems
10.5.2.Primal-Dual Method for SOCP Problems
10.6.General Nonlinear Optimization Problems
10.6.1.SQP Problems with Only Equality Constraints
10.6.2.SQP Problems with Inequality Constraints
Chapter 11:Heuristics
11.1.Penalty Function Method
11.2.Genetic Algorithm
11.2.1.Encoding
11.2.2.Fitness Function
11.2.3.Initial Population
11.2.4.The Operation Process
11.2.5.Selection
11.2.6.Crossover
11.2.7.Mutation
11.2.8.Differential Evolution
11.3.Simulated Annealing
Chapter 12:Basic Statistics
12.1.Random Variables
12.2.Sample Statistics
12.2.1.Mean
12.2.2.Weighted Mean
12.2.3.Variance
12.2.4.Weighted Variance
12.2.5.Skewness
12.2.6.Kurtosis
12.2.7.Moments
12.2.8.Rank
12.2.9.Covariance
12.3.Probability Distribution
12.3.1.Moments
12.3.2.Normal Distribution
12.3.3.Log-Normal Distribution
12.3.4.Exponential Distribution
12.3.5.Poisson Distribution
12.3.6.Binomial Distribution
12.3.7.T-Distribution
12.3.8.Chi-Square Distribution
12.3.9.F-Distribution
12.3.10.Rayleigh Distribution
12.3.11.Gamma Distribution
12.3.12.Beta Distribution
12.3.13.Weibull Distribution
12.3.14.Empirical Distribution
12.4.Multivariate Probability Distributions
12.4.1.Multivariate Normal Distribution
12.4.2.Multivariate T-Distribution
12.4.3.Multivariate Beta Distribution
12.4.4.Multinomial Distribution
12.5.Hypothesis Testing
12.5.1.Distribution Tests
12.5.2.Rank Test
12.6.Markov Models
12.6.1.Discrete-Time Markov Chain
12.6.2.Hidden Markov Model
12.7.Principal Component Analysis
12.8.Factor Analysis
12.9.Covariance Selection
Chapter 13:Random Numbers and Simulation
13.1.Uniform Random Number Generators
13.1.1.Linear Congruential Methods
13.1.2.Mersenne Twister
13.2.Sampling from Probability Distributions
13.2.1.Inverse Transform Sampling
13.2.2.Acceptance-Rejection Sampling
13.2.3.Sampling from Univariate Distributions
13.2.4.Sampling from Multivariate Distributions
13.2.5.Resampling Method
13.3.Variance Reduction
13.3.1.Common Random Numbers
13.3.2.Antithetic Variates
13.3.3.Control Variates
13.3.4.Importance Sampling
Chapter 14:Linear Regression
14.1.Ordinary Least Squares
14.1.1.Assumptions
14.1.2.Model Properties
14.1.3.Residual Analysis
14.1.4.Influential Point
14.1.5.Information Criteria
14.1.6.NM Dev Linear Regression Package
14.2.Weighted Least Squares
14.3.Logistic Regression
14.4.Generalized Linear Model
14.4.1.Quasi-family
14.5.Stepwise Regression
14.6.LASSO
Chapter 15:Time-Series Analysis
15.1.Univariate Time Series
15.1.1.Stationarity
15.1.2.Autocovariance
15.1.3.Autocorrelation
15.1.4.Partial Autocorrelation
15.1.5.White Noise Process and Random Walk
15.1.6.Ljung-Box Test for White Noise
15.1.7.Model Decomposition
15.2.Time-Series Models
15.2.1.AR Models
15.2.2.MA Model
15.2.3.ARMA Model
15.2.4.ARIMA Model
15.2.5.GARCH Model
15.3.Multivariate Time Series
15.3.1.VAR Model
15.3.2.VMA Model
15.3.3.VARMA Model
15.3.4.VARIMA Model
15.4.Cointegration
15.4.1.VEC Model
15.4.2.Johansen Cointegration Test
Index
About the Author
Haksun Li
, PhD, is the founder and CEO of NM DEV
PTE. LTD, NM Education LTD, NM Optim
LTD, and NM FinTech LTD. The NM group
of companies has the single mission of
“Making the World Better Using
Mathematics.” Under his leadership, the
company group serves security houses,
hedge funds, high-net-worth individuals,
multinational corporations, factories,
and plants all over the world. See
https://nm.sg.
NM DEV PTE. LTD is dedicated to the
research and development of innovative
computing technologies for business
operations as well as quantitative wealth
management. Haksun and the team have
developed a suite of programming libraries for mathematics. They
created the S2 platform, a next-generation data science toolbox that
offers high performance and easy deployment. See https://nm.dev.
NM Education LTD is an online tutoring service to teach pre-
university kids mathematics using an innovative learn-by-coding
approach. Traditional math teaching often asks students to repeatedly
do exercises mechanically. Traditional programming classes mainly
teach language constructs and syntax and ask students to code toy
problems. Haksun and his team have designed a new teaching
methodology to teach math using programming. Kids are asked to code
the math concepts to solve real engineering problems. Consequently,
not only do students gain hands-on experience applying new skills, but
they also gain deeper understanding of how math actually works. See
https://nm.education.
NM Optim LTD helps factories and plants streamline operations,
improve productivity, and increase revenue by applying operations,
research, and optimization theories. It is the bridge between industries
and academia. Haksun leads a team that is revolutionizing the
workflow of factories by making more efficient use of resources and
offering better scheduling, better management, better pricing, and so
on, all based on mathematical models, hence upgrading companies to
Industry 4.0. See https://nmoptim.com.
NM FinTech LTD develops financial analytic systems for quantitative
portfolio managers worldwide. For the U.S. equity market, Haksun
created a risk-management system, together with a factor library and
tools for portfolio construction. For the China bond market, Haksun
created SuperCurve, which is to date the only accurate yield curve
publicly available for pricing Chinese bonds, together with a suite of
fixed-income analytics. See https://nmfin.tech.
Haksun is the associate dean and a professor of the Big Data Finance
and Investment Institute of Fudan University in Shanghai, China. He
was an adjunct professor with multiple universities. He has taught at
the National University of Singapore (mathematics), the Nanyang
Technological University (business), the Fudan University (economics),
and the Hong Kong University of Science and Technology
(mathematics). Prior to that, Haksun was a quantitative analyst and a
quantitative trader at UBS and BNP Paribas New York, Tokyo, London,
and Singapore.
Haksun holds a bachelor’s degree in mathematics and a master’s
degree in financial mathematics from the University of Chicago, as well
as a master’s and a doctoral degree in computer science and
engineering (with specialization in artificial intelligence) from the
University of Michigan – Ann Arbor.
About the Technical Reviewer
Mark Wickham
is a software developer based in Dallas. Prior to returning to Texas in
2020, Mark lived in Beijing for nearly 20 years, where he worked for
Motorola, Inc., as a software engineering manager, and in various
program management and product management roles for the Asia-
Pacific region. Mark got his start in Java and Android when Motorola
produced the first Java-based mobile phone and he wanted to write his
own apps.
Mark was a regular speaker at some of the well-known Android
developer conferences and has written two books for Apress, Practical
Java Machine Learning and Practical Android.
Before embarking on his professional career, Mark obtained a
degree in physics from Creighton University in Omaha, with a major in
computer science and a minor in mathematics. Mark later obtained an
MBA from the University of Washington and also studied at the Hong
Kong University of Science and Technology.
An Iowa native, in his free time, Mark enjoys gravel bike riding,
sports photography, and his latest new passion, disc golf. For more
information about Mark, connect with him at
linkedin.com/in/mark-j-wickham.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2023
H. Li, PhD, Numerical Methods Using Kotlin
https://doi.org/10.1007/978-1-4842-8826-9_1
val A = DenseMatrix(arrayOf(
doubleArrayOf(1.0, 2.0, 3.0),
doubleArrayOf(6.0, 5.0, 4.0),
doubleArrayOf(8.0, 7.0, 9.0)))
val Ainv = Inverse(A)
Ainv
3x3
[,1] [,2] [,3]
[1,] -0.809524, -0.142857, 0.333333,
[2,] 1.047619, 0.714286, -0.666667,
[3,] -0.095238, -0.428571, 0.333333,
Figure 1-2 Print out the first six rows in a data set in R
By contrast, when using Java, you always have to write, compile, and
then run the whole program. There are many problems with this
approach. First, it is very annoying to always have to repeatedly
compile, deploy, and execute the code. Second, Java is verbose. It has too
much boilerplate code. There are sections of unnecessary code that
have to be included in many places with little or no alteration. You need
to write a lot of code even for simple things like printing out a number.
Third, it is very time consuming to run the whole program from the
beginning each time. Fourth, you often do not know what program you
want to write without examining, understanding, and experimenting
with the data. Java does not allow programmers to try different things
with the data, such as look the first six rows versus the first hundred
rows. Fifth, you cannot pause a Java program in the middle of a run to
examine the intermediate results. In a nutshell, Java is not the right tool
for prototyping and developing data science code. You need a Java-
based scripting language that lets you interact with data.
There are a few Java-based scripting languages that fully
interoperate with existing Java code and libraries, most notably Clojure,
Scala, Groovy, and Kotlin. (I do not count JRuby and Jython because they
are simply Java implementation of Ruby and Python, respectively. Their
goals are to make Ruby and Python code run on JVM.) I do not like
Clojure, a dynamic and functional dialect of the LISP programming
language on the Java platform, because there are too many parentheses
to read and they hurt my eyes and brain.2 I can read English-like
sentences much faster than LISPs. Scala is a strong, statically typed
general-purpose programming language that supports both object-
oriented programming and functional programming. Designed to be
concise, many of Scala’s design decisions are aimed to address the
criticisms of Java. My problem with Scala is its learning curve. I cannot
figure out what the lines mean at the first glance, especially with all the
symbols like :, ::, :::. I want a language that I can pick up and use right
away without spending time learning it.
Groovy is easy to learn and read. I did not spend any time learning
it. I simply copied, pasted, and modified the code and was able to get
things working. Groovy is a Java-syntax-compatible object-oriented
programming language for the Java platform. It is both a static and
dynamic language with features similar to Python. It can be used as a
programming language and as a scripting language, is compiled to Java
Virtual Machine (JVM) bytecode, and interoperates seamlessly with
other Java code and libraries. Groovy uses a curly-bracket syntax
similar to Java’s. SuanShu used to support Groovy. For example, the
following two-line Groovy script evaluates a definite integral. See
Figure 1-3. More examples can be found in Figure 1-4.
I = new Riemann();//create an integrator
v = I.integrate(
['evaluate' : {x -> return x * x}] as
nivariateRealFunction,//integrate the function y =
x^2
0, 1);//limit: [0, 1]
1 + 1
2 * 2
val A = 1.0
To print out a variable, you simply type its name. For example:
1.0
X = x + 1
x
2.0
for (i in 1..3) {
println(i)
}
1
2
3
The following snippet defines an array and prints it out.
1.0
2.0
3.0
4.0
5.0
add1(2.0)
3.0
There are many good books and tutorials on the Internet to learn
how to code Kotlin. The official Kotlin Foundation website has a lot of
information about Kotlin, its development, news, and community.
https://kotlinlang.org
They also have an online course to get beginners started on coding
Kotlin.
https://kotlinlang.org/docs/getting-
started.xhtml
1.3 S2
S2 is an online integrated development environment of data and
analytics for data science and numerical computing. It is developed by
the company NM DEV PTE LTD. The official S2 website is:
http://nm.dev/s2
S2 contains all numerical algorithms in the NM Dev library and
some mathematics, science, machine learning, graphing, plotting,
financial, and other commercial libraries. S2 lets users create their
math algorithms by calling all these built-in libraries in a simple
manner using Kotlin.
1.3.1 R Replacement
S2 is designed to be a modern-day replacement for R. You can do a lot
of things in S2 that you can do in R and S2 does them faster. Moreover, R
code runs inside only the R environment. It is very difficult to deploy
the code anywhere else such as in embedded devices like microwaves,
automobiles, or space rockets. S2 code runs in any JVM environment.
There are now 15 billion devices that run JVM!
S2 is an online IDE for numerical computing and coding numerical
algorithms. It is like an online calculator. Let’s start with 1+1, as shown
in Figure 1-5.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookmass.com