Xnumbers Tutorial1
Xnumbers Tutorial1
Volume
FOXES TEAM
Numeric Calculus
in Excel
Numeric Calculus
in EXCEL
Oct 2007
Xnumbers Tutorial
Index
About this Tutorial ..................................................................................................................... 8
Array functions........................................................................................................................... 9
What is an array-function? ....................................................................................................... 9
How to insert an array function ................................................................................................ 9
How to get the help on line...................................................................................................... 12
Xnumbers installation.............................................................................................................. 13
How to install .......................................................................................................................... 13
How to uninstall ...................................................................................................................... 14
Installation troubles ................................................................................................................ 14
Multiprecision Floating Point Arithmetic ............................................................................... 15
Why using extended precision numbers? .............................................................................. 15
Multiprecision methods........................................................................................................... 17
How to store long number ...................................................................................................... 17
Functions .................................................................................................................................. 19
General Description................................................................................................................ 19
Using Xnumbers functions ..................................................................................................... 19
Using extended numbers in Excel.......................................................................................... 20
Functions Handbook .............................................................................................................. 21
Precision................................................................................................................................. 22
Formatting Result ................................................................................................................... 22
Arithmetic Functions............................................................................................................... 23
Addition............................................................................................................................................. 23
Subtraction........................................................................................................................................ 23
Multiplication ..................................................................................................................................... 24
Division ............................................................................................................................................. 24
Inverse .............................................................................................................................................. 24
Integer Division ................................................................................................................................. 24
Integer Remainder ............................................................................................................................ 25
Sum .................................................................................................................................................. 27
Product ............................................................................................................................................. 27
Raise to power.................................................................................................................................. 27
Square Root...................................................................................................................................... 28
Nth- Root ........................................................................................................................................... 28
Absolute............................................................................................................................................ 28
Change sign...................................................................................................................................... 28
Integer part ....................................................................................................................................... 29
Decimal part...................................................................................................................................... 29
Truncating......................................................................................................................................... 29
Rounding .......................................................................................................................................... 29
Relative Rounding ............................................................................................................................ 30
Xnumbers Tutorial
Combinations.................................................................................................................................... 39
Permutations..................................................................................................................................... 40
Arithmetic Mean................................................................................................................................ 40
Geometric Mean ............................................................................................................................... 40
Quadratic Mean ................................................................................................................................ 40
Standard Deviation ........................................................................................................................... 40
Variance............................................................................................................................................ 41
Probability distributions ..................................................................................................................... 41
Univariate Statistic ............................................................................................................................ 46
Linear Regression Coefficients ......................................................................................................... 47
Linear Regression - Standard Deviation of Estimates ...................................................................... 49
Linear Regression Formulas............................................................................................................. 50
Linear Regression Covariance Matrix............................................................................................... 51
Linear Regression Statistics ............................................................................................................. 52
Linear Regression Evaluation ........................................................................................................... 53
Polynomial Regression - Coefficient ................................................................................................. 54
Polynomial Regression - Standard Deviation of Estimates ............................................................... 54
Polynomial Regression Statistics...................................................................................................... 54
Macro - Regression .......................................................................................................................... 55
Linear Regression with Robust Method ............................................................................................ 59
Linear Regression Min-Max .............................................................................................................. 60
NIST Certification Test...................................................................................................................... 61
Trigonometric Functions......................................................................................................... 65
Sin .................................................................................................................................................... 65
Cos ................................................................................................................................................... 65
Tan ................................................................................................................................................... 66
Arcsine.............................................................................................................................................. 66
Arccosine .......................................................................................................................................... 66
Arctan ............................................................................................................................................... 66
Constant ........................................................................................................................................ 66
Complement of right angle................................................................................................................ 67
Xnumbers Tutorial
Polynomial System of 2nd degree...................................................................................................... 91
Bivariate Polynomial ......................................................................................................................... 92
Orthogonal Polynomials evaluation .................................................................................................. 97
Weight of Orhogonal Polynomials..................................................................................................... 99
Zeros of Orthogonal Polynomials...................................................................................................... 99
Coefficients of Orthogonal Polynomials .......................................................................................... 100
Xnumbers Tutorial
Matrix Subtraction........................................................................................................................... 133
Matrix Multiplication ........................................................................................................................ 133
Matrix Inverse ................................................................................................................................. 133
Matrix Determinant ......................................................................................................................... 133
Matrix Modulus ............................................................................................................................... 134
Scalar Product ................................................................................................................................ 134
Similarity Transform ........................................................................................................................ 134
Matrix Power................................................................................................................................... 134
Matrix LU decomposition ................................................................................................................ 135
Matrix LLT decomposition ............................................................................................................... 135
Vector Product ................................................................................................................................ 136
Solve Linear Equation System........................................................................................................ 136
Square Delta Extrapolation ............................................................................................................. 137
Macro for Multiprecision Matrix Operations..................................................................................... 139
Interpolation.......................................................................................................................... 195
Polynomial interpolation.................................................................................................................. 195
Interpolation schemas..................................................................................................................... 197
Interpolation with continued fraction ............................................................................................... 199
Interpolation with Cubic Spline........................................................................................................ 201
Cubic Spline 2nd derivatives........................................................................................................... 201
Cubic Spline Coefficients ................................................................................................................ 203
2D Mesh Interpolation..................................................................................................................... 204
Macro Mesh Fill .............................................................................................................................. 205
Xnumbers Tutorial
Macro ODE Solver .......................................................................................................................... 232
Macro ODE - Slope Grid ................................................................................................................. 233
Derivatives............................................................................................................................ 239
First Derivative................................................................................................................................ 239
Second Derivative........................................................................................................................... 240
Gradient .......................................................................................................................................... 240
Jacobian matrix............................................................................................................................... 241
Hessian matrix ................................................................................................................................ 241
Non-linear equation solving with derivatives ................................................................................... 243
Xnumbers Tutorial
WHITE PAGE
Xnumbers Tutorial
Chapter
1
About this tutorial
About this Tutorial
This document is the reference guide for all functions
and macros contained in the Xnumbers addin. It is a
printable version of the help-on-line, with a larger
collection of examples.
Leonardo Volpi
Xnumbers Tutorial
Array functions
What is an array-function?
A function that returns multiple values is called "array-function". Xnumbers contains many of
these functions. Each function returning a matrix or a vector is an array functions. Function
performing matrix operations such as inversion, multiplication, sum, etc. are examples of arrayfunctions. Also complex numbers are arrays of two cells. On the contrary, in the real domain,
the logarithm, the exponential, the trigonometric functions, etc. are scalar functions because
they return only one value.
In a worksheet, an array-function always returns a (n x m) rectangular range
of cells. To enter it, you must select this range, enter the function as usually
and and give the keys sequence CTRL+SHIFT+ENTER. Keep down both
keys CTRL and SHIFT (do not care the order) and then press ENTER.
4
b = 2
3
1 1 1
A = 1 2 2
1 3 4
Xnumbers Tutorial
Now - attention! - give the "magic" keys sequence CTRL+SHIFT+ENTER
That is:
All the values will fill the cells that you have selected.
Note that Excel shows the function around two braces { }. These symbols mean that the
function return an array (you cannot insert them by hand).
An array function has several constrains. Any cell of the array cannot be modified or deleted.
To modify or delete an array function you must selected before the entire array cells.
1 2 1 0
2 1 + 0 1
We can use directly the addition operator "+". We can do this following these steps.
1)
2)
3)
Write a formula that adds the two ranges. Either write =B4:C5+E4:F5 Do not press
<Enter>. At this point the spreadsheet should look something like the figure below. Note
that the entire range B8:C9 is selected.
10
Xnumbers Tutorial
4)
5)
Press <ENTER>.
If you have correctly followed the procedure, the spreadsheet should now look something like
this
This trick can also work for matrix subtraction and for the scalar-matrix multiplication, but not for
the matrix-matrix multiplication.
Let's see this example that shows how to calculate the linear combination of two vectors
11
Xnumbers Tutorial
There is also another way to get the help-on-line. It is from the Xnumbers Function Handbook
Select the function that you want and press the Help button
You can also recall the help guide from the function wizard window
Of course you can open the help on-line from the Xnumber menu
12
Xnumbers Tutorial
Xnumbers installation
How to install
This addin for Excel XP is composed by the following files:
Addin file
Help file
Handbook file
After the first installation, Xnumbers.xla will be add to the Addin Manager
By this tool, you can load or unload the addins that you want, simply switching on/off the checkboxes.
At the starting, the checked addins will be automatically loaded
If you want to stop the automatic loading of xnumbers.xla simply deselect the check box before
closing Excel
If all goes right you should see the welcome
popup of Xnumbers. This appears only when
you activate the check box of the Addin
Manager. When Excel automatically loads
Xnumbers, this popup is hidden
.
13
Xnumbers Tutorial
How to uninstall
If you want to uninstall this package, simply delete its folder. Once you have cancelled the
Xnumbers.xla file, to remove the corresponding entry in the Addin Manager, follow these steps:
1) Open Excel
2) Select <Addins...> from the <Tools> menu.
3) Once in the Addins Manager, click on the Xnumbers entry
4) Excel will inform you that the addin is missing and ask you if you want to remove it from
the list. Give "yes".
Installation troubles
If you do not see the Xnumbers icon or the welcome popup the installation has gone wrong and
probably it is due to same configuration parameter of your Windows / Excel environment
The default security setting of Excel XP 2002/2003 doesn't allowe to install Xnumbers as is. To
prevent errors it is necessary to open the Excel menu option:
Tools > Options > Security > Macro Security, and set: "Average Level security" and "Trust
Access to Visual Basic Project".
Do not worry about it. Xnumbers contains only safe macros; they do not alter your PC in any
way. If you want to remove Xnumbers simply delete all the files contained in the package.
In addition we have to point out that, nowadays, nobody use to hide virus, spy-software, trojan
and related things in a macro Excel: this things belong to the prehistory of informatics!
Nowadays, E-mail and Internet are by far the most important media.
14
Xnumbers Tutorial
Coefficients
P( x) = ai x i
a9
a8
a7
a6
a5
a4
a3
a2
a1
a0
i =0
xn
32
31,71962617
31,44427498
31,186622
31,02434159
30,99711858
31,00020851
30,99030069
31,01228318
31,00220065
1
-279
34606
-2504614
116565491
-3617705301
74873877954
-996476661206
7738306354988
-26715751812360
-P/P'
0,280373832
0,275351191
0,257652979
0,162280411
0,02722301
-0,003089933
0,009907825
-0,021982495
0,01008253
-0,00146544
|xn-x|
1
0,7196262
0,444275
0,186622
0,0243416
0,0028814
0,0002085
0,0096993
0,0122832
0,0022007
As we can see, the iteration approaches the solution x = 31 but the error |xn - x| remains too
high. Why? Multiple roots? No, because P'(x) >> 0. Algorithm failed? Of course not. This
method is very well tested. The only explanation is the finite precision of the computing. In fact,
repeating the calculus of P(x) and P'(x) with 25 significant digits, we find the excellent
convergence of this method.
The basic structure is the IEEE-754 which allows for a 64 bit standard floating point double precision number. The
later has a mantissa of 53 bits (one is the implied bit) which becomes equivalent to 15.4 digits. Excel reports a
maximum of 15 digits. For a good, accurate note see "Excel Computation and Display Issue" by David. A. Heiser,
http://www.daheiser.info/excel/frontpage.html
15
Xnumbers Tutorial
xn
-P/P'
|xn-x|
32
120
428
0,28037383
31,71962617
43,71020049043
158,979858019937
0,27494175
0,719626
31,44468442
15,71277333004
61,059647049872
0,25733482
0,444684
31,1873496
4,83334748037
29,483621556222
0,1639333
0,18735
31,02341629
0,56263326884
24,082301045236
0,02336294
0,023416
31,00005336
0,00128056327
24,000000427051
5,3357E-05
5,34E-05
31
0,00000000053
23,999999999984
2,2083E-11
1,54E-11
31
0,00000000004
23,999999999995
1,6667E-12
6,66E-12
The graph below resumes the effect of computation with 15 and 25 significant digits.
|Xn -X|
1
0,01
15 digits
0,0001
1E-06
1E-08
25 digits
1E-10
1E-12
1
Iteration
10
The application field of multi-precision computation is wide. Especially it is very useful for
numeric algorithms testing. In the above example, we had not doubt about the NewtonRaphson method, but what about the new algorithm that you are studying? This package helps
you in this work.
16
Xnumbers Tutorial
Multiprecision methods
Several methods exist for simulating variable multi-precision floating point arithmetic. The basic
concept consists of breaking down a long number into two or more sub-numbers, and repeating
cyclic operations with them. The ways in which long numbers are stored vary from one method
to another. The two most popular methods use the "string" conversion and the "packing"
As we can see, the sub-packet numbers are in decimal base and the original long number is
perfectly recognizable. This a great advantage for the future debugging operation.
An example of arithmetic operation - the multiplication A x B = C - between two packet numbers
is shown in the following:
A
456789
105112
601
B
654321
X
Xnumbers Tutorial
carry
+
298886 +
68777 +
393 +
0
x
105112 x
601 x
0 x
456789
C'
=
=
=
=
654321
654321
654321
654321
298886635269
68777287838
393315698
393
=>
=>
=>
=>
635269
287838
315697
393
The numbers in the accumulator C' are split into two numbers. The last 6 digits are stored in C,
the remaining left digits are copied into the carry register of the next row.
As we can see, the maximum number of digits is reached in accumulator C'. In the other
vectors, the numbers require only six digits at most. The maximum number of digits for a single
packet depends of the hardware accumulator. Normally, for a 32-system, is 6 digits.. This is
equivalent to conversion from a decimal to a 10^6 representation base. This value is not critical
at all. Values from 4 to 7 affect the computation speed of about 30 %. But it does not affect the
precision of the results in any case.
18
Xnumbers Tutorial
Functions
General Description
Xnumbers is an Excel addin (xla) that performs multi-precision floating point arithmetic.
Perhaps the first package providing functions for Excel with precision from 15 up to 200
significant digits. It is compatible with Excel XP and consists of a set of more than 270 functions
for arithmetic, complex, trigonometric, logarithmic, exponential and matrix calculus covering the
following main subjects.
The basic arithmetical functions: addition, multiplication, and division were developed at the
first. They form the basic kernel for all other functions.
All functions perform multiprecision floating point computations for up to 200 significant digits.
You can set a precision level separately for each function by an optional parameter. By default,
all functions use the precision of 30 digits, but the numerical precision can easily be regulated
continually from 1 to 200 significant digits. In advance some useful constants like , Log(2),
Log(10) are provided with up to 400 digits.
Upon "user's" category you will find the functions of this package.
From version 2.0 you can manage functions also by the Function Handbook. It starts by the
Xnumbers menu
All the functions for multi-precision computation begin with "x". The example below shows two
basic functions for the addition and subtraction.
As any other functions they can also be nested to build complex expressions. In the example
below we compute x^4 with 30 digits precision
As we can see, Xnumbers is powerful, but it does slow down the computation considerably
Therefore, use the multiprecision x-functions only when they are really necessary.
19
Xnumbers Tutorial
You can also insert extended numbers directly in the function. Only remember that, for
preserving Excel to convert them, you must insert extended numbers like string, within quote
"...".
2469135780246913578 =xmult( "1234567890123456789" , 2 )
20
Xnumbers Tutorial
Functions Handbook
Xnumbers includes an application for searching and pasting the Xnumbers functions,
cataloged by subject. This application can also submit the Xnumbers macros.
You can activate the Functions Handbook from the menu bar Help > Function manager.
Category: you can filter macros by category (Arithmetic, Statistical, Trigonometric, etc.)
Macro Type: filters by macro Functions, by macro Subroutines, or both
Paste Into: choose the cell you want to paste a function, default is the active cell
Search: searches macros by words or sub-words contained into the name or description. For
example, if you input "div" you list all macros that match words like (div, divisor, division,...)
You can associate more words in AND/OR. Separate words with comma "," for OR, with plus
"+", for AND. For example, if you type "+div +multi" you will get all the rows containing words
like (div, divisor, division,...) and words like (multi, multiprecision,...). On the contrary, if you
type "div, multi", you get all the rows that contain words like (div, divisor, division,...) or also the
words like (multi, multiprecision,...). Remember to choose also the Category and Macro Type.
Example, if you enter the word hyperbolic, setting the Category complex, you find the
hyperbolic functions restricted to the complex category.
Help: recalls the help-on-line for the selected function.
OK: insert the selected function into the worksheet ". This activates the standard Excel function
wizard panel. If the macro selected is a "sub", the OK button activates the macro.
21
Xnumbers Tutorial
Precision
Most functions of this package have an optional parameter - Digit_Max - setting the maximum
number of significant digits for floating point computation, from 1 to 200 (default is 30). The
default can be changed from the menu X-Edit\Defaut Digits
This parameter also determines how the output is automatically formatted. If the result has
fewer integer digits than Digit_Max, then the output is in the plain decimal format
( 123.45, -0.0002364, 4000, etc.), otherwise, if the number of integer digits exceeds the
maximum number of digits allowed (significant or not), the output is automatically converted in
exponential format (1.23456789E+94).
The exponent can reach the extreme values of +/- 2,147,483,.647.
The output format is independent of the input format.
In synthesis, the Digit_Max parameter limits:
The significant digits of internal floating point computation
The maximum number output digits, significant or not.
The default of Digit_Max can be changed from the X-Edit menu . It affects all multiprecision
functions and macros.
Formatting Result
The user can not format an extended number with standard Excel number format tools,
because, it is a string for Excel. You can only change the alignment. To change it you can use
the usual standard Excel format tools.
It is possible to separate the digits of a x-numbers in groups, by the user function xFormat()
and xUnformat() 1.
It work similar at the built-in function Format(x, "#,##0.00")
2,469,135,780,246,913,578 = xformat("2469135780246913578",3)
These functions were original developed by Ton Jeursen for the add-in XNUMBER95, the downgrade version of
XNUMBERS for Excel 5. Because they are very useful for examining long string of number, we have imported them in
this package
22
Xnumbers Tutorial
Arithmetic Functions
Addition
xadd(a, b, [Digit_Max])
Performs the addition of two extended numbers: xadd(a, b) = a + b.
Subtraction
xsub(a, b, [Digit_Max])
Performs the subtraction of two extended numbers: xsub(a, b) = a b.
NB. Do not use the operation xadd(a, -b) if b is an extended number. Excel converts b into
double, then changes its sign, and finally calls the xadd routine. By this time the original
precision of b is lost. If you want to change sign at an extended number and preserve its
precision use the function xneg()
800000.008209750361424423316366
800000
0.008209750361424423316366
(digits)
30
6
25
The subtraction is exact (no approximation has been entered). But the final result have 25 total
digits, of wich only 22 are significant. 8 significant digits are lost in this subtraction. We cannot
do anything about this phenomenon, except to increase the precision of the operands, when
possible.
23
Xnumbers Tutorial
Multiplication
xmult(a, b, [Digit_Max])
Performs the multiplication of two extended numbers: xmult(a, b) = a x b.
The product can often lead to long extended numbers. If the result has more integer digits than
the ones set by Digit_Max, then the function automatically converts the result into the
exponential format.
Division
xdiv(a, b, [Digit_Max])
Performs the division of two extended numbers: xdiv(a, b) = a / b.
If b = 0 the function returns ?. The division can return long extended numbers even when the
operands are small. In the example below we see the well-known periodic division 122 / 7 =
17,428571 . with 30 significant digits.
Inverse
xinv(x, [Digit_Max])
It returns the inverse of an extended number. If x = 0, the function returns ?.
xinv(x) = 1 / x
Integer Division
xdivint(a, b)
Returns the quotient of the integer division for a>0 , b>0.
If b = 0 the function returns ?.
xdivint(a, b)= q , where: a = b*q + r , with 0 r < b
24
Xnumbers Tutorial
Integer Remainder
xdivrem(a, b)
Returns the remainder of the integer division for a>0 , b>0. If b = 0 the function returns ?.
xdivrem(a, b)= r , where: a = b*q + r , with 0 r < b
This function is also called "a mod b "
How to test multiprecision functions ?
This test is the most important problem in developing multiprecision arithmetic. This activity,
absorbs almoust the 60% of the totally realization effort.
Apart the first immediate random tests, we can use many known formulas and algorithms. The
general selecting criterions are:
1.
2.
3.
4.
5.
6.
For example, a good arithmetic test is the Newton algoritm to compute the square root of a
number. The iterative formula:
xn +1 =
xn 1 xn xn + 2
+ =
2 xn
2 xn
For each iterate only the blu digits are exacts. We see the progressive convergence. By the
way, we note that this algorithm is also very efficent. The rate of convergence is quadratic. The
number of digits approximately doubles at each iteration (In fact this is just the algorithm used
by the xsqr multiprecision function)
But, as said, for testing, the efficiency has no influence. It is important only that the algorithm
involves the most multiprecision functions as possible.
25
Xnumbers Tutorial
Another algorithm quite suitable for testing multiprecision accuracy is the approximatation by
continuous fraction1.
Initialize
X = 31/2, Y = 1/2, T = 6
Iteration
X = (2 + X)1/2
Y = Y/X
T = 2T
P = Y*T*(5Y6/112 + 3Y4/40 + Y2/6 + 1)
Accuracy: approximately 12 decimal digits every 5 iterations)
Below, step by step, a possible Excel arrangement:
The Digit_Max parameter is in the A1 cell. By this parameter we can modulate the arithmetic
accuracy. We have set 30 digits only for the picture dimensions. But you can try with 60, 100 or
more.
Note that, in order to have a more compact form, we have used the xeval function for
calculating the X and P formulas that are inserted into the cells B3 and E3 rispectively.
Selecting the last row (range A6:F6) and dragging it down, we get the following iteration table
This version, studied by David Sloan (2003), full of many arithmetic operations, permitted us to detect a very hidden
bug in Xnumbers
26
Xnumbers Tutorial
Sum
xsum(v, [Digit_Max])
This is the extended version of the Excel built-in function SUM. It returns the sum of a vector of
numbers. The argument is a standard range of cells.
vi = v1 + v2 + ...vn
Note that you can not use the standard function SUM, because it recognizes extended
numbers as strings and it excludes them from the calculus.
Product
xprod(v, [Digit_Max])
Returns the product of a vector of numbers.
i vi = v1 v2 ...vn
Note that the result is an extended number
even if all the factors are in standard
precision
Raise to power
xpow(x, n, [Digit_Max])
Returns the integer power od an extended number. xpow(x, n) = x n
xpow("0.39155749636098981077147016011",90) = 1.9904508921478176508981155284E-7
xpow(5,81,60) = 5
81
= 413590306276513837435704346034981426782906055450439453125
Note the exponent +2088 of the third result. Such kind of numbers can be managed only with
extended precision functions because they are out side of the standard limits for 32bit double
precision.
For not integer power see the exponential functions xexp and xexpa
27
Xnumbers Tutorial
Square Root
xsqr(x, [Digit_Max])
Returnts the square root of an extended number
xsqr(x) =
1.41421356237309504880168872420969807
Nth- Root
xroot(x, n, [Digit_Max])
Returns the nth root of an extended number
The root's index must be a positive integer.
xroot(x, n)=
1.66810053720005875359979114908
xroot(100,9,60) = 1.66810053720005875359979114908865584747919268415239470704499
Absolute
xabs(x)
Returns the absolute value of an extended number xabs(x)= |x|
Do not use the built-in function "abs", as Excel converts x in double, then takes the absolute
value but, at that time, the original precision of x is lost.
Change sign
xneg(x)
Returns the opposite of an extended number: xneg(x) = x
Do not use the operator (minus) for extended numbers. Otherwise Excel converts the
extended numbers into double and changes its sign but, at that time, the original precision is
lost. In the following example the cell B8 contains an extended number with18 digits. If you use
the as in the cell B9, you lose the last 3 digits. The function xneg(), as we can see in the cell
B10, preserves the original precision.
28
Xnumbers Tutorial
Integer part
xint(x)
Returns the integer part of an extended number, that is the greatest integer less than or equal
to x.
Examples:
xint(2.99) =
2
xint(2.14) =
2
xint(-2.14) =
3
xint(-2.99) =
3
xint(12345675.00000001) =
xint(12345675.00000001) =
12345675
12345676
Decimal part
xdec(x)
Returns the decimal part of an extended number
Examples:
xdec(2.99) = 0.99
xdec(-2.14) = - 0.14
Truncating
xtrunc(x, [dec])
Returns the truncated number; the parameter "dec" sets the number of decimals to keep
(default 0). It works like Excel function TRUNC. dec can be negative; in that case x is cut to
the integer number, counting back from the decimal point. See the following examples.
Examples:
number
dec
number truncated
4074861.076055370173
4074861.076055370173
4074861.076055370173
4074861.076055370173
4074861.076055370173
4074861.076055370173
-2
-1
0
1
2
3
4074800
4074860
4074861
4074861
4074861.07
4074861.076
Rounding
=xround(x, [dec])
Rounds an extended number, the parameter "dec" sets the decimal number of is to keep
(default 0). It works like standard round function. dec can be negative, in that case x is
rounded to the integer number, starting to count back from decimal point. See the following
examples.
29
Xnumbers Tutorial
number to round
dec
number rounded
6.2831853071795864769
6.2831853071795864769
6.2831853071795864769
6.2831853071795864769
6.2831853071795864769
100352934.23345
100352934.23345
100352934.23345
0
1
2
3
4
0
-1
-2
6
6.3
6.28
6.283
6.2832
100352934
100352930
100352900
When the number is in exponential format, it is internally converted into decimal before the
rounding.
number to round
Decimal format
Dec
number rounded
1.238521E-17
1.238521E-17
1.238521E-17
1.238521E-17
0.00000000000000001238521
0.00000000000000001238521
0.00000000000000001238521
0.00000000000000001238521
16
17
18
19
0
1.E-17
1.2E-17
1.24E-17
Relative Rounding
=xroundr(x, [dgt])
Returns the relative round of a number. The optional parameter Dec sets the significant digits
to keep. (default = 15)
This function always rounds the decimal place no matter what the exponent is
number to round
dgt
number rounded
1.23423311238765E+44
1.23423311238765E+44
1.23423311238765E+44
1.23423311238765E+44
1.23423311238765E+44
1.23423311238765E+44
15
14
13
12
11
10
1.23423311238765E+44
1.2342331123876E+44
1.234233112388E+44
1.23423311239E+44
1.2342331124E+44
1.234233112E+44
30
Xnumbers Tutorial
Numbers comparison
xcomp(a [b])
Compares two extended numbers. It returns the value y defined by:
1 a > b
y = 0a =b
1 a < b
31
Xnumbers Tutorial
Check digits
DigitsAllDiff(number)
This function2 return TRUE if a number has all digits different.
DigitsAllDiff(12345) = TRUE
DigitsAllDiff(123452) = FALSE
Argument can be also a string. Example
DigitsAllDiff(12345ABCDEFGHIM) = TRUE
DigitsAllDiff(ABCDA) = FALSE
These functions were original developed by Ton Jeursen for his add-in XNUMBER95, the downgrade version of
XNUMBERS for Excel 5.
Because it works well and it is very useful for examining long string of number, I have imported it in this package.
2
32
Xnumbers Tutorial
SortRange
=SortRange (ArrayToSort, [IndexCol], [Order], [CaseSensitive])
This function returns an array sorted along a specified column
ArrayToSort: is the (N x M ) array to sort
IndexCol: is the index column for sorting (1 default)
Order: can be "A" ascending (default) or "D" descending
CaseSensitive: True (default) or False. It is useful for alphanumeric string sorting
Example: The left table contains same points of a function f(x,y). The right table is ordered from
low to high function values (the 3-th column)
Digits sum
sumDigits(number)
This useful1 function returns the digits sum of an integer number (extended or not)
sumDigits(1234569888674326778876543) = 137
Vector flip
Flip(v)
This function returns a vector in inverse order [a1, a2, a3, a4] [a4, a3, a2, a1]
33
Xnumbers Tutorial
Scientific format
xcvexp(mantissa, [exponent])
This function converts a number into scientific format. Useful for extended numbers that, being
string, Excel cannot format.
xcvexp(-6.364758987642234, 934) = -6.364758987642234E+934
xcvexp(1.2334567890122786, ) = 1.2334567890122786E-807
This function is useful also to convert any xnumbers into scientific notation, simply setting
exponent = 0 (default)
xcvexp(12342330100876523, 0) = 1.2342330100876523E+16
xcvexp(0.000023494756398348) = 2.3494756398348E-5
Note that, in the last case, you cannot convert directly into double (for example, using the
VALUE function), even if the number of digits is less than 15. The exponent is too large for the
standard double precision.
1
12
0
4
4
8
using the multiprecision xMatInv function, you will get a matrix like the following
0.3076923076923076923076923
-0.2307692307692307692307692
0.1538461538461538461538462
-0.02564102564102564102564103
0.1025641025641025641025641
-0.01282051282051282051282051
34
-0.1410256410256410256410256
0.06410256410256410256410256
0.05448717948717948717948718
Xnumbers Tutorial
If you use the functions xcdbl nested with the multiprecision function, the matrix will be
rounded in standard precision and the output will have a more compact format
Note that xcdbl affects only the output. The internal computing is always performed in
multiprecision.
Macros X-Edit
These simple macros are very useful for manipulating extended numbers in the Excel
worksheet. They perform the following operations:
Format
Unformat
Double Conversion
Round
Relative Round
Mop-Up
From this menu you can also change the default Digit_Max parameter
Using these macros is very simple. Select the range where you want to operate and then start
the relative macro. They work only over cells containing only numeric values, extended or
standard. Cells containing function are ignored
Tip. For stripping-out a formula from a cell and leaving its value, you can select the cell and
then click in sequence
(copy + paste values)
Here are same little examples:
Format - group 6
31415926.53589793238462643
19831415926.53589793238462
0.535897932384626433832734
31,415926.535897,932384,62643
19831,415926.535897,932384,62
0.535897,932384,626433,832734
Double Conversion
31415926.53589793238462643
19831415926.53589793238462
0.535897932384626433832734
31415926.5358979
19831415926.5358
0.535897932384626
31415926.536
19831415926.536
0.536
Rounding 3 decimals.
31415926.53589793238462643
19831415926.53589793238462
0.535897932384626433832734
35
Xnumbers Tutorial
Relative rounding - significant digits 15.
4.5399929762484851535591E-5
1.0015629762484851535591E-6
0.539929762484851535591E-12
4.53999297624849E-05
1.00156297624849E-06
5.39929762484852E-13
31415926.53589793238462643
0
0
0
Note that the function mopup is used overall for improving the readability. The cells having
values greater than the limit are not modified.
Macro X-Converter
This macro1 (*) converts a well formed Excel formula to the equivalent in terms of Xnumber
multiprecision functions (xadd, xmult, etc.).
The advantage over x-evaluate is that the code can be debugged in normal excel using small
values
and in a familiar form. When the spreadsheet works it is ' converted to using nested x-calls for
the precision work. The intention is to tag the conversion onto the copy worksheet function ' so
that you end up with a multi-precision copy of the original.
Its main features are:
converts a range of cells directly on site or in a new worksheet.
skips cells having functions not convertible.
skips array functions except MINVERSE and MMULT that are substituted with the
correspondent x-functions xMatInv and xMatMult.
Errors (if any ) are shown on the panel
The digits parameter can be set in 4 different ways:
1) an integer number i.e. 30
2) a fixed reference of a cell, i.e. $A$1
3) a name of a cell, i.e. "digits"
4) simply nothing. In that case all the x-functions use the internal default = 30
Of course not all the Excel Functions can be converted. The list of the Excel functions2
converted is:
* , / , + , - , ^ , ABS , ACOS , ACOSH , ASIN , ASINH , ATAN , ATANH , AVERAGE
, COMBIN , COS , COSH , EXP , FACT , INT , LN , LOG , MDETERM , MINVERSE ,
MMULT , MOD , PI , PRODUCT , ROUND , SIN , SINH , SQRT , STDEV , STDEVP , SUM
, TAN , TANH , TRUNC , VAR , VARP
The conversion engine of this macro was originally developed by John Jones in an smart m4 macro language which
makes the VB native j-code more simple (!) to write. It appears in this package thanks to his courtesy
The functions are indicated with their original English names, that usually are different from the local names.
36
Xnumbers Tutorial
Example. Assume to have an Excel formula in the cell B6 calculating the norm of a 3dim vector
like the following worksheet.
We would transform this formula into a multiprecision one using the x-functions of the
Xnumbers add-in
Select the cell B6 and start the macro X-Converter from the menu X-Edit
Range to convert: the range containing the one or more formulas to convert
Digit Parameter: specifies the global precision digits for all the functions under conversion.
You can leave "(Default)" or blank meaning that all the function will use the internal default
precision (usually 30 digits). But you can set a reference cell (example $A$1) where you have
set your own precision. Or you can insert a name of a cell (example "mydigits") that you have
defined. You can also insert directly a number (example 25)
Output Option: sets the output where the multiprecision function will be copied. Select "on
site" if we want to convert the formula directly in the selected cell. Select "new sheet" if we want
to perform the conversion in a new worksheet. The original formula will be preserved.
Let's select "on site" and click "run". The worksheet look will look like as the following
Xnumbers Tutorial
=xsqr(xadd(xadd(B2,B3),B4)).
working with the default precision digits (30)
Note that there are 3 nested functions in the converted formula.
The maximum number of nested functions in Excel is 8.
If an error raises during the cell conversion, the formula is left unchanged and the text is turned
in red. The macro always shows a short list of the errors encountered during the conversion.
The macro works also with a range selection
Example. In the following worksheet we have same functions in the range A3:A18
Note that the cell A18 contains the
function COUNTA that are not the
similar x-function
Note that the range A14:A15
contains an array function { ... },
thus the cells A14 and A15 are
inseparable.
The cells A7 contain a simple
constant
We want to convert them, where possible, in a new worksheet without affect the original
worksheet.
For that, select all the range A3:A18 and start the X-Converter
Select "new sheet" and click "run". The new worksheet look like as the following
Note that the cell A7, A14, A15, A18 are unchanged
Note that the original cells A9 = B7^12 and A13 =A11^2.6 having the same operator symbol
"^", are substituted with two different x-functions: xpow for integer power and xexpa for float
power.
38
Xnumbers Tutorial
Statistical Functions
Factorial
xfact(n, [Digit_Max])
Returns the factorial of an integer number xfact(n)= n!
This example shows all 99 digits of 69!
xfact(69, 100) = 71122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000
If the parameter Digit_Max is less than 99, the function returns the approximate result in
exponential format:
xfact(69) = 1.71122452428141311372468338881E+98
For large number (n>> 1000) you can use the faster function xGamma(x). The relation between
the factorial and the gama function is:
(n) = (n-1)!
xfact2(n) = 13579...n
Combinations
xComb(n, k, [Digit_Max])
Returns the binomial coefficients, a combination of n, class k. xcomb = C n,k
The example below shows all the 29 digits of the combination of 100 objects grouped in class
of 49 elements:
xComb(100,49) = 98913082887808032681188722800
Combinations of N = 100
objects in class of 10, 20,
90
Note the typical parabolic
outline of the binomial
coefficients
For large argument (n and k >>1000) use the faster function xcomb_big(n,k) .
39
Xnumbers Tutorial
Permutations
xPerm(n, [k], [Digit_Max])
Returns the permutation of n, class k. xperm(n,k)= Pn,k.
If k is omitted, the function assume k = n and in this case will be P(n) = n!
Examples:
xPerm(100, 20, 60) = 1303995018204712451095685346159820800000
xPerm(100) = 9.33262154439441526816992388562E+157
Arithmetic Mean
xmean(x, [Digit_Max])
Returns the arithmetic mean of n numbers, extended or not. The argument is a range of cells.
M=
Geometric Mean
xgmean(x, [Digit_Max])
Returns the geometric mean of n numbers, extended or not.
GM =
x1 x 2 x 2 ... x n
Quadratic Mean
xqmean(x, [Digit_Max])
Returns the quadratic mean of n numbers, extended or not.
QM =
Standard Deviation
xstdev(range, [Digit_Max])
xstdevp(range, [Digit_Max])
Return the deviation of n numbers, extended or not. Range is a range of cells. The optional
parameter Digit_Max, from 1 to 200, sets the number of significant digits (default 30)
(x x)
n 1
40
Xnumbers Tutorial
p =
(x x)
Variance
xvar(range, [Digit_Max])
xvarp(range, [Digit_Max])
Return the variance of n numbers, extended or not. Range is a range of cells. The optional
parameter Digit_Max, from 1 to 200, sets the number of significant digits (default 30)
v =
(x x)
n 1
vp
(x x)
=
Probability distributions
Xnumbers contains several type of probability distribution functions
DSBeta(x, a, b, [dtype])
DSBinomial(k, n, p, [dtype])
DSCauchy(x, m, s, n, [dtype])
DSChi(x, r, [dtype])
DSErlang(x, k, l, [dtype]))
DSGamma(x, k, l, [dtype]))
DSLevy(x, l, [dtype]))
DSLogNormal(x, m, s, [dtype]))
DSLogistic(x, m, s, [dtype]))
DSMaxwell(x, a, [dtype]))
DSMises(x, k, [dtype]))
DSNormal(x, m, s, [dtype]))
DSPoisson(k, z, [dtype]))
DSRayleigh(x, s, [dtype]))
DSRice(x, v, s, [dtype]))
DSStudent(t, v, [dtype]))
DSWeibull(x, k, l, [dtype]))
Beta distribution
Binomial distribution
n integer , s > 0
Chi distribution
r integer, x > 0
Erlang distribution
k integer, x > 0
Gamma distribution
Levy distribution
x > 0, l > 0
Log-normal distribution
x > 0, m 0, s > 0
Logistic distribution
x > 0, m 0, s > 0
Maxwell-Boltzman distribution
x > 0, a > 0
Normal distribution
s>0
Poisson distribution
k integer, z > 0
Rayleigh distribution
x > 0, s > 0
x > 0, v 0 , s > 0
The optional parameter dtype = 0 (default) returns the density distribution f(x); dtype = 1
returns the cumulative distribution F(x).
x
The lower limit "a" depends by the definition domain of the density function f(x).
41
Xnumbers Tutorial
Gamma
Cauchy
Beta
Lvy
Logistic
42
Xnumbers Tutorial
MaxwellBoltzmann
Rice
Erlang
Normal
Von Mises
Weibull
43
Xnumbers Tutorial
Log-normal
Binomial
f ( k , n, p ) =
Student
f (t , v) =
n!
p k (1 p ) n k
k!(n k )!
Poisson
( 12 (v + 1))
2 v ( 12 v)(1 + 12 t 2 ) ( v +1) / 2
f ( x, v ) =
Chi squared
x v / 21e x / 2
f ( x, v ) = v / 2 1
2 ( 2 v)
44
xve x
v!
Xnumbers Tutorial
45
Xnumbers Tutorial
Univariate Statistic
xstatis(range, [digit_max])
This function returns the univariate statistic summary of a range of data.
The statistics computed are:
Total of numerical elements of the range
Arithmetic Mean
n
Standard Deviation
(x x)
(x x)
n 1
Autocorrelation lag1
n 1
( xi x )( xi +1 x )
(x x)
n
This function returns a vector of 5 elements. Use the ctrl+shift+enter key sequence for insert it.
46
Xnumbers Tutorial
x
0.1
0.2
1991.001046
y = a0 + a1 x
0.35
0.4
0.45
0.6
1991.001831
1991.002092
1991.002354
1991.003138
0.7
0.8
0.9
1
1.5
1.8
2
3
1991.003661
1991.004184
1991.004707
1991.00523
1991.007845
1991.009414
1991.01046
1991.01569
47
Xnumbers Tutorial
Note that the x-regression functions always returns a vector of m+1 values [a0, a1, ...am]
independently if the intercept is 0 or not.
Multivariate Regression
This function can also compute a multivariate regression. This is when y depends by several
variables x1, x2, xn. Look at this example
x1
x2
x3
-4
4000.8
0.1
-2
4000.7
0.2
0.5
-1
4001.55
0.3
0.4
0.5
0.5
1
1
0
1.5
2
4001.65
4002.4
4002.59
48
Xnumbers Tutorial
10
1120
11
1473
12
1894
13
2389
14
2964
15
3625
16
4378
17
5229
18
6184
19
7249
20
8430
49
Xnumbers Tutorial
y = a0 + a1 x1 + a2 x2 + ...am xm
where:
[a0 , a1 , a2 ... am ]
X i = xi x
for i = 1..m
Y = y y
where the right values are the averages of samples y and x respectively:
y=
1
yk
n k
xi =
1
xi ,k
n k
After that, the coefficients a= [a1, a2, ....an] are the solution of the following linear system
[C] a = b
where [C] is the cross-covariance matrix, and b is the XY covariance
j X 12, j
=
C=
=
j X 1, j X 2, j j X 1, j X 3, j .. j X 1, j X m, j
j X 22, j
j X 2, j X 3, j .. j X 2, j X m, j
.. j X 3, j X m, j
=
j X 32, j
=
=
j X m2 , j
j Y j X 1, j
YX
j j 2, j
b = j Y j X 3, j
....
j Y j X m, j
a0 = Y ai X i
i =1
For m=1 we obtain the popular formulas of the monovariate linear regression
a1 =
j Yj X j
j X 2j
a0 = Y a1 X
This is the linear solution known as the Ordinary Least Squares (OLS). The analysis of this kind
of approach shows that, for large dimensions of n (many measurement values) the matrix C
becomes nearly singular
50
Xnumbers Tutorial
y = a 0 + a1 x1 + a 2 x 2 ... + a m x m
For a given set of n points Pi = ( x1i x2i
xmi , yi )
Intercept = 0
1 x11
1 x
12
X =
... ...
1 x1n
... xm1
... xm 2
... ...
... xmn
C = s2 X X T
... xm1
... xm 2
... ...
... xmn
x11
x
X = 12
...
xn 2
The covariance matrix C is
Where:
C = s2 X X T
Where:
(y
=
i
2
y i )
n m 1
(y
=
y i ) 2
nm
Note that the square roots of the diagonal elements of the covariance matrix
si = cii
are the standard deviations of the linear regression coefficients
51
Xnumbers Tutorial
S y,x
( y yi* ) 2
= 1 i i
i ( yi y ) 2
=1
y y*
2
y
Where y is the value estimated by the regression function and y is the mean of y values.
y* = a0 + a1 x1 + a2 x2 + ...am xm
y=
1
yk
n k
For monovariate regression (m=1), the above formula returns the popular formula:
R2 =
x2
y
( x )2
n
( y )2
n
Intercept constrained to 0
(y
(y
s y,x =
yi*
s y,x =
n gl 1
52
yi*
n gl
Xnumbers Tutorial
y = a0 + a1 x1 + a2 x2 + ...an xn
Example: Plot the linear regression for the following data set
x
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
y
0.58
0.65
0.88
1.25
1.32
1.14
1.31
1.51
1.54
1.48
1.98
In this worksheet, each value of linear regression y is computed by the function xRegLinEval.
The regression coefficients are computed by xRegLinCoef. The results are converted in double
by the function xcdbl.
Selecting the range A1:C12 and plotting the data we get the following regression graphs
2.4
y*
1.6
1.2
0.8
0.4
0
-1
-0.75
-0.5
-0.25
53
0.25
0.5
0.75
Xnumbers Tutorial
y = a0 + a1 x + a2 x 2 ... + am x m
with m > 1
Y is a vector (n x 1) of the dependent variable.
X is a vector (n x 1) of the independent variable
Degree is the degree m >1 of the polynomial
DgtMax sets the precision (default 30).
Intcpt = true/false. If true (default) the algorithm calculates the intercept; otherwise the intercept
is set to 0
The function returns the coefficient vector [a0, a1, a2...am]
Example. Find the 3rd degree polinomial fitting the given data set (xi, yi)
Xnumbers Tutorial
R2
S y,x
Macro - Regression
Xnumbers contains two macros performing the linear and polynomial regression in
multiprecision arithmetic. From the Xnumbers menu, select
Data XY is an array containing the column of the variable X at the left with the adjacent column
of Y at the right. For a m-multivariate regression also the columns of X must be exactly m.
Select this range before starting the macro. In this case the input box will be automatically filled
Data XY for univariate and
polynomial regression
Data XY for
multivariate regression
Output cell indicates the starting upper left cell of the output area.
Intercept. If checked the macro calculates the intercept otherwise it is set to 0
Convert to double. Converts the multiprecision in double before the output
55
Xnumbers Tutorial
R-squared + residual std. dev. Calculate the correspondent statistics
Estimate std. dev. Calculate the standard deviation of estimate
Digits Max. from 1 to 200, sets the precision (default 30)
Degree. The panel of the Polynomial Regression macro is similar to the Linear except for the
input degree box that allows to chose the polynomial degree.
56
Xnumbers Tutorial
Sub-Tabulation
One important application of linear regression is the sub-tabulation, which is the method to
extract a table of values with smaller step from an original table with bigger steps. In other
words, we can obtain a fine tabulation from a table with a few values of a function. Lets see
this example.
Example: Extract from the following dataset, a table having 11 values with step 0.1, from 0 to 1
y
x
0
0.2
0.5
0.6
0.7
1
[ a 0 , a1 ]
Than we re-calculate the values
y i = a0 + a1 h , i = 110, h = 0.1
5.50
5.00
4.50
4.00
3.50
3.00
0
0.2
0.4
0.6
0.8
The graph shows the extra points added by the sub tabulation. Note that this method is
different from the interpolation because the regression line does not pass through any of the
original points. The new values of the table B are different from the ones table A even in the
same x-values.
This feature came in handy when we want to regularize the row data.
Data Conditioning
The conditioning of the data consists of subtracting the mean from the values of the sample. It
can improve the accuracy of the linear regression, but the regression coefficients obtained conditioned coefficients - are different from the regression coefficients of the row data. They
can be back-transformed by the following method:
Given X and Y two data vectors, the linear regression polynomial of n degree well be:
57
Xnumbers Tutorial
n
p( x) = ai x i
i =0
x=
1
xi
n
y=
1
yi
n
u i = xi x
vi = y i y
p(u ) = bi u i
i =0
The original ai coefficients can be obtained from the new bi coefficients by the following
formulas.
n
a0 = y + (1)i bi x i
i =0
n
i
ak = (1)i + k bi x i k
i =k
k
This method is often useful for increasing the gloabal accuracy of the linear regression
58
Xnumbers Tutorial
y a1 x + a0
Use CTRL+SHIFT+ENTER to paste it.
Example: Suppose you have sampled 5 experimental values (xi, yi), with a (suspected) large
error in the last value 6.5.
x
1
2
3
4
5
1.1
2
3.1
3.8
6.5
7
6
5
4
Ordenadas
SM
RM
LM S
M
.CC.
SM
tandard
3
2
1
In the graph are shown the
regression lines obtained with
0
all robust methods in
0
1
2
3
4
5
6
comparison with the standard
OLS regression.
As we can see all the lines SM, RM, LMS (Robust Methods) minimize the influence of the value
(5, 6.5)
The routines for robust linear regression were developed by Alfredo lvarez Valdivia. They appear in this collection
thanks to its courtesy
59
Xnumbers Tutorial
~
y = a0 + a1 x
As known, those coefficients minimize the max absolute error for the given dataset
E = max | ~
y ( xi ) yi |
Example. Find the better fitting line that minimize the absolute error
y 0.428 + 1.142 x
Emax 0.7
As we can see, all the points lie in the plane strips of Emax around the min-max line (pink
line). (Emax 0.7)
60
Xnumbers Tutorial
StRD Datasets
Level of
difficulty
Model of
class
Coeff.
Function
Norris
low
Linear
xRegLinCoef
LRE
15.0
Pontius
low
Quadratic
xRegPolyCoef
15.0
NoInt1
Average
Linear
xRegLinCoef
15.0
Filip
high
Polynomial
11
xRegPolyCoef
15.0
Longley
high
Multilinear
xRegLinCoef
15.0
Wampler1
high
Polynomial
xRegPolyCoef
15.0
Wampler2
high
Polynomial
xRegPolyCoef
15.0
Wampler3
high
Polynomial
xRegPolyCoef
15.0
Wampler4
high
Polynomial
xRegPolyCoef
15.0
Wampler5
high
Polynomial
xRegPolyCoef
15.0
The table below gives the LRE results on the NIST test univariate data sets obtained from
xStats function
NIST test for univariate data sets
Difficulty Size
Stand.
Dev.
Mean
Autocor.
Coef.
Dataset
Category
PiDigits
Univariate
5000
15
15
15
Lottery
Univariate
218
15
15
15
Lew
Univariate
200
15
15
15
Maveo
Univariate
50
15
15
15
Michelso
Univariate
100
15
15
15
NumAcc1
Univariate
15
15
15
NumAcc2
Univariate
1001
15
15
15
NumAcc3
Univariate
1001
15
15
15
NumAcc4
Univariate
1001
15
15
15
61
Xnumbers Tutorial
Transcendental Functions
y = log base ( x)
The argument may be either normal or extended number.
Example
xlog(30) = 1.47712125471966243729502790325
Exponential
xexp(x, [Digit_Max])
Returns the exponential of x in base "e"
Example
e10
1000
xexp(x) = e
= xexp(10) = 22026.4657948067165169579006452
= xexp(1000) = 1.97007111401704699388887935224E+434
Note the exponent 434 of the second result. Such kind of numbers can be managed only with
extended precision functions because they are outside the standard limits of double precision.
= xexpa(1.234, 2) = 2.3521825005819296401155858555
100.54
= xexpa(-0.54) = 0.288403150312660594239196924659
62
Xnumbers Tutorial
Constant e
xe([Digit_Max])
Returns Euler's constant "e", the base of the natural logarithm.
The optional parameter Digit_Max, from 1 to 415, sets the number of significant digits (default
30).
xe()
= 2.71828182845904523536028747135
xe(60) = 2.71828182845904523536028747135266249775724709369995957496696
Constant Ln(2)
xLn2([Digit_Max])
Returns the constant Ln(2).
The optional parameter Digit_Max, from 1 to 415, sets the number of significant digits (default
30).
Constant Ln(10)
xLn10([Digit_Max])
Returns the constant Ln(10).
The optional parameter Digit_Max, from 1 to 415, sets the number of significant digits (default
30).
Hyperbolic Sine
xsinh(x, [Digit_Max])
Returns the hyperbolic sine of x in multiprecision arithmetic
sinh =
e x e x
2
Hyperbolic ArSine
xasinh(x, [Digit_Max])
Returns the hyperbolic arsine of x in multiprecision arithmetic
asinh( x) = ln x + x 2 + 1
63
Xnumbers Tutorial
Hyperbolic Cosine
xcosh(x, [Digit_Max])
Returns the hyperbolic cosine of x in multiprecision arithmetic
cosh( x) =
e x + e x
2
Hyperbolic ArCosine
xacosh(x, [Digit_Max])
Returns the hyperbolic Arcosine of x in multiprecision arithmetic
The argument x, normal or extended, must be x >1
acosh = ln x + x 2 1 , x > 1
Hyperbolic Tangent
xtanh(x, [Digit_Max])
Returns the hyperbolic tangent of x in multiprecision arithmetic
tanh( x) =
e x e x
e x + e x
Hyperbolic ArTangent
xatanh(x, [Digit_Max])
Returns the hyperbolic artangent of x in multiprecision arithmetic
The argument x, normal or extended, must be |x| < 1
1 1+ x
atanh ( x) = ln
2 1 x
, x <1
Euler constant
=xeu( [Digits_Max] )
Returns the Euler-Mascheroni constant
(The same constan returned by xGm function)
Example
xeu()
= 0.57721566490153286060651209008
xeu(60) = 0.57721566490153286060651209008240243104215933593992359880576
64
Xnumbers Tutorial
Trigonometric Functions
Sin
xsin(a, [Digit_Max])
Returns the sine of the angle a
xsin(a) = sin(a)
The argument a, in radians, may be either a normal or an extended number.
xsin(1.5)
= 0.997494986604054430941723371141
Cos
xcos(a, [Digit_Max])
Returns the cosine of the angle a
xcos(a) = cos(a)
The argument a, in radians, may be either a normal or an extended number.
xcos(1.5) = 7.07372016677029100881898514342E-2
Computation of cos(/2)
Example: compute cos (89,99999995) with the standard built-in function COS function
COS(89.99999995) = COS(1.570796326) = 7.94896654250123E-10
7.94896619231321E-10
(deg)
xcos()
COS() built-in
Err %
1.57
1.570
1.5707
1.57079
1.570796
1.5707963
1.57079632
1.570796326
1.5707963267
1.57079632679
89.95437383553930
89.95437383553930
89.99448088119850
89.99963750135470
89.99998127603180
89.99999846476560
89.99999961068120
89.99999995445590
89.99999999456290
89.99999999971950
7.96326710733325E-4
7.96326710733325E-4
9.63267947476522E-5
6.32679489657702E-6
3.26794896619225E-7
2.67948966192313E-8
6.79489661923132E-9
7.94896619231321E-10
9.48966192313216E-11
4.89661923132169E-12
7.96326710733263E-04
7.96326710733263E-04
9.63267947476672E-05
6.32679489666849E-06
3.26794896538163E-07
2.67948965850537E-08
6.79489670660314E-09
7.94896654250123E-10
9.48965963318629E-11
4.89658888522954E-12
7.75E-14
7.75E-14
-1.55E-13
-1.45E-11
2.48E-10
1.28E-09
-1.29E-08
-4.41E-08
2.41E-07
6.20E-06
As we can see, the accuracy of the standard function COS decreases when the angle
approaches the right angle. On the contrary, the xcos function keeps its accuracy.
65
Xnumbers Tutorial
Tan
xtan(a, [Digit_Max])
Returns the tangent of a
xtan(a) = tan(a)
The argument a, in radians, may be either a normal or an extended number.
Arcsine
xasin(a, [Digit_Max])
Returns the arcsine of a
xasin(a) = arcsin(a)
The arcsine is defined between -/2 and /2
The argument a, where | a | 1 , may be either a normal or an extended number.
Arccosine
xacos(a, [Digit_Max])
Returns the arccosine of a
xacos(a) = arccos(a)
The arccosine is defined between 0 and
The argument a, where | a | 1 , may be either a normal or an extended number.
Arctan
xatan(a, [Digit_Max])
Returns the arctan of a
xatan(a) = arctan(a)
The arctan(a) is defined between
/ 2 < arctan(a)< / 2
Constant
These functions return the following multiples of
xpi([Digit_Max])
xpi =
xpi2([Digit_Max])
xpi2 = /2
xpi4([Digit_Max])
xpi4 = /4
x2pi([Digit_Max])
x2pi = 2
The optional parameter Digit_Max, from 1 to 415, sets the number of significant digits (default
30).
Example. Compute the Hermite-Ramanujan constant with 36 significant digits
163
xexp(xmult(xpi(36),xsqr(163,36),36),36) = 262537412640768743.999999999999250005
66
Xnumbers Tutorial
xanglec() = /2
Example:
xanglec(1.4) = 0.17079632679489661923132169163
For angles not too near the right angle this function is like the ordinary subtraction. The use of
this function is computing the difference without loss of significant digits when the angle is very
close to the right angle. For example, computing in Excel the following difference:
(PI()/2 1.570796) = 1.57079632679490 1.570796 = 0.00000032679490
we have a loss of 7 significant digits, even though the computation has been made with 15
significant digits. On the contrary, if we use:
xanglec(1.570796 , 15) =
3.26794896619231E-7
we get the full precision with 15 significant digits. The "lost" digits are automatically replaced
67
Xnumbers Tutorial
Polynomial Rootfinder
The roots of polynomials are of interest to more than just mathematicians. They play a central
role in applied sciences including mechanical and electrical engineering where they are used in
solving a variety of design problems.
Xnumbes provides several macros based on the following polynomial rootfinder algorithms.
RootFinder JT
RootFinder GN
RootFinder ADK
Rootfinder RF
Rootfinder LB
Lin-Bairstow algorithm
Rootfinder SK
Siljak algorithm
Rootfinder LA
Laguerre algorithm
These macros are able to find, in a few seconds, all the roots - real or complex - of a dense
polynomial up to 15th - 20th degree, in double or multi-precision. It is remarkable that
sometimes the results has shown in an exact way, even if the computation is intrinsically
approximate.
The characteristics of each rootfinder are reassumed in the following table
Macro
Roots
Coefficients
Arithmetic
RootfinderJT
Complex
Real
Standard
RootfinderGN
Complex
Real
Multi-precision
RootfinderDK
Complex
Complex
Multi-precision
RootfinderRF
Real, Integer
Real, Integer
Multi-precision
RootfinderLB
Complex
Real
Standard
RootfinderSK
Complex
Complex
Multi-precision
RootfinderLA
Complex
Real
Standard
68
Xnumbers Tutorial
Input parameters
The polynomial rootfinder interface is simple and straight.
Method:
JT
GN
ADK
RF
LB
SK
LA
Jenkins-Traub
Gen. Newton-Raphson
Aberth-Durand-Kerner
Ruffini
Lin-Bairstow
Siljak
Laguerre
Standard
Multiprecision
Multiprecision
Standard
Standard
Multiprecision
Standard
Real coefficients
Real coefficients
Complex coefficients
Real Integer coefficients
Real coefficients
Complex coefficients
Real coefficients
Coefficients input:
is an array containing the polynomial coefficients with increasing
degree, from top to bottom. May be also a single cell containing the polynomial formula string,
such as:
-120+274x-225x^2+85x^3-15x^4+x^5
RootfinderDK and Siljak can also accept complex coefficients. In that case the input is an
(n x 2) array. Examples of possible input are (thick black box):
Remarks.
The formula string is more adapt for sparse polynomials.
Real coefficients can be put in horizontal or vertical vector. Complex coefficients, only in
vertical vectors
Results Output: It is the upper left corner of the output area. If blank, the routine assumes the
cell nearest the given coefficients range.
Error: Sets the relative roots accuracy. The algorithm terminates when the relative difference
between two iterations is less then this value.
Iter: The algorithm stops when the iterations counter reaches this value.
Multi-Precision: Enable/disable the multi-precision arithmetic
MP-out: If checked, the results are written in multi-precision, otherwise they are converted in
standard double precision.
69
Xnumbers Tutorial
Output
The rootfinder macros output their results in the following simplified layout
The roots and their estimated relative errors are written in a table starting from the left upper
cell indicated in the input window. In the right-bottom cell is written the total elaboration time in
seconds
Note: we have formatted the table
only for clarity. The macros do not
perform this task. We do it.
RootfinderRF
Integer
roots
Reduced
Polynomial
can be factorized as
( x + 2)( x 2)( x + 8) 2 ( x 4 4 x 3 + 23 x 2 38 x + 34)
70
Xnumbers Tutorial
Press run and - after a while - the routine ends and the roots will be displayed at the right,
like in the following fugure
Sparse polynomials. We can pass to the rootfinder macros also symbolic polynomial string,
(that it is the faster way for sparse high degree polynomials). Lets see this example
Find all roots of the following 16th degree polynomial
x^16-6817x^8+1679616
Write this string in a cell, select it and start a rootfinder macro
71
Xnumbers Tutorial
In this case we have used the Durand-Kerner algorithm obtaining a very high accuracy
(practically the highest accuracy in standard double precision)
~
x
xi
We have to say that this number should be regarded as an estimation of goodness of the
root found; small values (for example 1E-9 , 1E-12 ) indicate an high precision of the
correspondent root. On the contrary, larger values (for examples 1E-3 , 1E-5) indicates a
difficult roots that require an extra investigation.
For example assume to find the root of the following 6th degree polynomial
Clustering effect: In this case, the accuracy is enough good, but quite lower than the previous
example. The reason is that the roots:
1, 1.01, 1.02, 1.03, 1.04, 1.05
are very close each other (0.1% of difference)
72
Xnumbers Tutorial
Complex polynomials. The macro RootfinderDK and RootfinderSK can solve also complex
polynomials. Example: find the roots of the following polynomial with complex coefficients
P( z ) = (12 + 4i ) + 4 z + (15 5i ) z 2 5 z 3 + (3 + i ) z 4 + z 5
Select both real and imaginary coefficients columns and start the macro RootfinderKD
The roots are z = 1 , z = 2 , z = 3 j . Observe that the results are shown in exact mode even
if the computation is intrinsically approximated.
A polynomial of n degree, having as roots
the first 1, 2,..n integers, belongs to the
Wilkinson class that, as known, is
ill-conditioned. This dense polynomial is
usually assumed as standard reference for
polynomial rootfinder algorithms. We have
tabulated the LRE (log relative error)
obtained with all the rootfinder macros.
As we can see, for a Wilkinson polynomial of
20th degree, we have good about four
significant digits (0.1% accuracy)
16.0
14.0
LRE
12.0
10.0
8.0
6.0
4.0
2.0
0.0
0
10
15
20
But all polynomials are so hard to solve? Fortunately not. Many polynomials with higher
degree, can be solved with good accuracy
For example, if we try to get all real roots of the 16th degree Legendres polynomial
L16(x) = 6435 -875160 x2 +19399380 x4 -162954792 x6+ 669278610 x8
-1487285800 x10 +1825305300 x12 -1163381400 x14 +300540195 x16
73
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Rel. Err.
2.9585E-17
1.6352E-13
3.673E-14
1.1559E-14
1.0779E-14
7.4625E-16
1.9313E-16
8.5038E-18
8.5038E-18
1.4485E-16
1.5356E-15
5.0196E-15
2.5615E-14
4.6793E-14
8.4139E-14
5.5583E-15
25
Xnumbers Tutorial
(remember that the higher degree coefficients are at bottom)
In the last column there are the errors estimation given by the rootfinder DK. They are slight
different from the true roots errors, but we have to remember that this column must be regard
as an index of the root approximation: low values mean a good accuracy, larger values often
(but not always) indicate a poor approximation
Integer roots
In applied science it's rarely to came across in polynomials having exact integer roots.
Nevertheless, they are frequent in math, didactical examples and algorithm testing .
Xnumbers has a dedicated special macro for finding the integer real roots of a polynomial. It
uses the Ruffini's method with the QD algorithm for roots isolation.
This method is generally less efficient then JT or DK but it can gain in accuracy.
The roots found by this method have no round-off errors so the deflated polynomial is exact.
Therefore, in that case, the root-finding-deflating process is without errors.
For polynomial having a mix of integer real roots, complex roots and real roots the method
returns the integer roots and the coefficients of the deflated polynomial that can be solved with
the aid of the general purpose macros: DK, GN or JT. Because the deflated polynomial has a
lower degree, the roots accuracy will be generally higher than by solving directly the given
polynomials.
original
P(x)
Deflated
Q(x)
Let's see how it works practically. Assume to have the following polynomial
degree
a0
a1
a2
a3
a4
a5
a6
a7
a8
coeff
8678880
-13381116
8844928
-3279447
746825
-107049
9437
-468
10
real
complex
5, 6, 7, 8, 9
2.8
4.5 i 0.5
Select the range B2:B10 and start the macro for extracting the integer roots and deflated
polynomial
74
Xnumbers Tutorial
The original polynomial is now cracked into the following factors
Im
2.8
4.5
4.5
Rel. Err.
0
0.5
-0.5
1.14E-17
1.44E-15
1.44E-15
The general accuracy is better than 1e-14 , thousand times than the direct method.
Clearly is a good thing to keep attention to the integer roots (when they are).
Global roots accuracy
versus the solving
methods:
1.0E+00
1.0E-02
1.0E-04
1.0E-06
Rootfinder RF + DK
Rootfinder JT
Rootfinder DK
Rootfinder NG
1.0E-08
1.0E-10
1.0E-12
1.0E-14
1.0E-16
Rootfinder Rootfinder Rootfinder Rootfinder
RF + DK
JT
DK
NG
The multiprecision should be used when the coefficients exceed 15 digits (remember that the
coefficients must be exact in order to extract the exact integer roots)
Let's see the following 18th degree polynomial having the roots
Polynomial roots
Coefficients
-612914519230813800000
91181999821816015800
-5186948337826516202
137665995531841931
-1622627967498318
6214402509219
-11208193158
10605849
-5122
integer
real
complex
none
none
Note that this a so called "clustered polynomial" because some of its integer roots (1000, 1001,
1002, 1003, 1004) are very closed each other (difference less then 1%). This situation is quite
difficult for many algorithms and the accuracy is generally quite poor. On the contrary, the
Ruffini's method works very fine in that case.
75
Xnumbers Tutorial
Multiple roots
The macro "Factors" performs the decomposition of a polynomial with multiple roots into
smaller factors having all single roots. It uses the GCD method with the Euclid' algorithm
Example, the polynomial:
Each factors contains only single roots and thus can be solved with high precision by any
rootfinder macro1.
For further details see "Non Linear Equations", Foxes Team, 2006
76
Xnumbers Tutorial
Polynomial Functions
Polynomial evaluation
=POLYN(z, Coefficients, [DgtMax])
Computes the polynomial at the value z.
P ( z ) = a0 + a1 z + a2 z 2 + ...an z n
The parameter Coefficients is the (n+1) column vector containing the polynomial coefficients
from the lowest to the highest order.
This function accept also complex coefficients. In that case the parameter Coefficients is an
(n+1 x 2) array.
The optional parameter DgtMax set the precision. If omitted, the function works in the faster
double precision.
This function works also for complex arguments. In that case, z must be a complex number
(two adjacent cells) and the function returns two values. To see both real and imaginary part,
select two cells and give the CTRL+SHIFT+ENTER key sequence. If you press only ENTER,
the function returns only its real part.
Example: compute the following real polynomial
P( z ) = 2 z 4 + z 3 5 z 2 + 2 z + 4
for z = 4 2i
Otherwise, if you want to compute a real polynomial for a real argument, e.g. z = 10 - simply
pass a single value
77
Xnumbers Tutorial
Example: compute the following complex polynomial
P( z ) = 2 z 4 + (1 i ) z 3 5 z 2 + (2 i ) z + (4 5i )
for z = 4 2i
Polynomial derivatives
=DPOLYN(z, Coefficients, Order, [DgtMax])
Computes the polynomial derivative at the value z.
P( z ) = a0 + a1 z + a2 z 2 + ...an z n
D j ( z) =
d j P( z )
dz j
The parameter "Coefficients" is the (n+1) vector containing the polynomial coefficients from the
lowest to the highest order.
This function accept also complex coefficients. In that case the parameter Coefficients is an
(n+1 x 2) array.
The parameter "Order" sets the order of the derivative.
The optional parameter "DgtMax" set the precision. If omitted, the function works in the faster
double precision.
This function works also for complex arguments. In that case, z must be a complex number
(two adjacent cells) and the function returns two values. To see both real and imaginary part,
select two cells and give the CTRL+SHIFT+ENTER key sequence. If you press only ENTER,
the function returns only its real part.
Example. Compute the derivatives of the following polynomial
P( z ) = 3 + 2 z + z 2 + z 3
For z= 3, we have:
Example: calculate the 2nd derivative of the following complex polynomial at the point
z = 4 2i
P ( z ) = 2 z 4 + (1 i ) z 3 5 z 2 + (2 i ) z + (4 5i )
78
Xnumbers Tutorial
With DPOLYN and POLYN it is very easy to implement, for example, the Newtons algorithm
for finding the polynomial root with high precision
Example: find the real root of the following polynomial with Newtons algorithm
x 7 5 x 6 + 64 x 3 8000
The popular iterative Newtons formula is
xi +1 = xi +
p( xi )
p' ( xi )
Starting from the point x = 10. Note that we cannot use the handly x = 0 , because the
derivative is zero
The exact digits caught by the algorithm, are shown in blue. Note the impressive acceleration.
Try this example with 60 and more digits if you like.
Polynomial coefficients
=PolyTerms(Polynomial)
Returns the vector of the polynomial coefficients
The argument is a polynomial string like "1-3x+5x^2 +x^5" in any order.
Example
79
Xnumbers Tutorial
Note the braces { } in the formula. This indicates that the function return a vector. We must
select the range before enter the function with "shift+ctrl+enter".
Polynomial writing
=PolyWrite(Coefficients, [variable])
It returns the polynomial string from its coefficients.
The first argument may be a (1 x n) vector or an (2 x n) array. In the last case, the first row
indicates the coefficient position and the second row contains the correspondent coefficient
value.
The second optional argument specifies the variable string (default is "x").
Note that the second argument "t" must be insert as string, that is between quotes "..."
Polynomial addition
=PolyAdd(Poly1, Poly2)
Performs the addition of two polynomials. The arguments are monovariable polynomial strings.
Example:
PolyAdd("1-3x" , "-2-x+x^2")
"-1-4x+x^2" .
Polynomial multiplication
=PolyMult(Poly1, Poly2)
Performs the multiplication of two polynomials The arguments are monovariable polynomial
strings.
Example:
PolyMult("1-3x" , "-2+5x+x^2") =
"-2+11x-14x^2-3x^3" .
(1 3x )( 2 + 5 x + x 2 ) = 2 + 11x 14 x 2 3x 3
80
Xnumbers Tutorial
Polynomial subtraction
=PolySub(Poly1, Poly2)
Returns the difference of two polynomials. The arguments are monovariable polynomial strings.
Example:
PolySub("1-3x" , "-2+5x+x^2") = "3-8x-x^2" .
)(
x 4 1 = x 2 x 1 2 + x + x 2 + 1 + 3x
81
Xnumbers Tutorial
T0 = 1 , T1 = x
Tn +1 = 2 x Tn Tn 1
H 0 = 1 , H1 = x
H n +1 = 2 x H n 2n H n 1
Legendres Polynomials
Legendres polynomials can be obtained by the following well known iterative formula
Pn ( x) =
2n 1
n 1
x Pn 1 ( x)
Pn 2 ( x)
n
n
P0 = 1 , P1 = x
1
1
1
3 x 2 1 , P3 = 5 x 3 3 x , P4 = 35 x 4 30 x 2 + 3
2
2
8
The above formula is very popular, but from the point of view of numeric calculus has one
disadvantage: its coefficients are decimal and this causes round-off errors leading inaccuracy
for higher polynomial degree. It is convenient to rearrange the iterative formula to avoid
fractional coefficients.
Lets assume that a Legendres polynomial can be written as
Pn ( x ) =
1
Ln ( x)
kn
(1a)
82
Xnumbers Tutorial
k0 = 1
L0 = 1
k1 = 1
L1 = x
We can show that the following iterative process, with n 2 , gives the couples (kn , Ln(x))
U n ( x) = k n 2 ( 2n 1) x
an = k n 1 (n 1)
Vn ( x) = U n ( x) Ln 1 ( x) an Ln 2 ( x)
bn = n k n 1 k n 2
Where the coeff operator returns the coefficients vector of the polynomial Vn(x), and the GCD is
the greatest common divisor.
Simplifying, we get, finally the couple (kn , Ln(x))
kn =
bn
cn
Ln ( x) =
1
Vn ( x)
cn
This iterative algorithm, working only with integer values, is adapted to build Legendres
polynomials with high degree.
Lets see how to arrange a worksheet for finding Legendres polynomial
In the first column we insert the degree n, beginning from 0 to 2, for the moment
In the last two columns k and L(x) we have added the starting values.
The row 6 contains all the functions that the process needs.
In particularly we note:
The function polyterms(D6) gives the coefficients vectors [-1, 0, 3] of V(x) = -1+3x^2
The function xMCD returns the greatest common divisor of [-1, 0, 3, 2] 1
Select the row 6 and drag it down. We generate the Legendres polynomial in the form (1a)
83
Xnumbers Tutorial
Here is a table of Legendres polynomials obtained with the above method
n
L(x)
-1+3x^2
-3x+5x^3
3-30x^2+35x^4
15x-70x^3+63x^5
16
-5+105x^2-315x^4+231x^6
16
-35x+315x^3-693x^5+429x^7
128
35-1260x^2+6930x^4-12012x^6+6435x^8
128
315x-4620x^3+18018x^5-25740x^7+12155x^9
10
256
-63+3465x^2-30030x^4+90090x^6-109395x^8+46189x^10
11
256
-693x+15015x^3-90090x^5+218790x^7-230945x^9+88179x^11
12
1024
231-18018x^2+225225x^4-1021020x^6+2078505x^8-1939938x^10+676039x^12
13
1024
3003x-90090x^3+765765x^5-2771340x^7+4849845x^9-4056234x^11+1300075x^13
84
Xnumbers Tutorial
Polynomial shift
=PolyShift(Poly, x0)
Performs the polynomial translation to x0,
The argument "Poly" can be the polynomial strings or the vector of polynomial coefficients.
This function returns the coefficient vector of the translated polynomial.
If you select one cell, the output will be a polynomial string
Example. Given the polynomial:
188784918 47389623 x + 4952504 x 2 275809 x 3 + 8633 x 4 144 x 5 + x 6
18 + 9 z 16 z 2 z 3 9 z 4 + z 6
This function is useful for transforming polynomial for reducing the coefficients amplitude and
improving the precision of rootfinder methods. In this example we work with coefficients of two
maximum digits, instead of 9 digits. We note also that the second polynomial, having the
second coefficient = 0, is centered. His roots are the same of the given polynomial, translated
of 24, but can be factorize much better. In fact, we have
( z 2 z + 1)( z 2 + z + 2)( z 2 9)
Polynomial center
=PolyCenter(Coefficients)
Returns the center of the polynomial roots circle
The argument specifies the vector of the polynomial coefficients in the following order:
[a0 , a1 , a2 ... an ]
It can also be a polynomial string
if x1, x2, ...xn are roots of polynomial the center Bx is defined as:
Bx =
x0 + x1 + x2 ... + xn an 1
=
n
n
85
Xnumbers Tutorial
[a0 , a1 , a2 ... an ]
It can also be a polynomial string
If zi are the roots of a polynomial, the radius is defined as:
R = max (| zi |)
i =1...n
.The circle of root is very useful for locating all the roots of a polynomial. For example, given the
following 9 degree polynomial.
degree
a0
coefficents
-3098250
a1
4116825
a2
-2427570
a3
916272
a4
-244674
a5
46934
a6
-6430
a7
608
a8
-36
a9
x imm
0
-6
-4
-3
We have to point out that this method is probabilistic. It means that, picking-up a random
polynomial, the most part of the roots are found inside the circle but it is also possible to find
same roots outside the circle with 1% of probability.
Example: compute the root circle of the polynomial:
x7-5x6+64x3-8000
86
Xnumbers Tutorial
radius 4.331
center 0.714
The roots are:
x real
x imm
-2.7429701
1.6132552
-2.7429701 -1.6132552
-0.4369651
3.2182957
-0.4369651 -3.2182957
3.17993518
2.2060806
3.17993518 -2.2060806
5
Multiple roots:
This function returns the vector of polynomial coefficients if you select more than two vertical
cells. It is useful for higher degree polynomial
87
Xnumbers Tutorial
88
Xnumbers Tutorial
In the following table we have calculated the coefficient of the polynomial having as roots the
first 19 integer numbers. That is:
x1 = 1 , x2 = 2, x3 = 3 ,.... x19 = 19
Roots
PolyBuild
Diff.
-121645100408832000
-121645100408832000
431565146817638400
431565146817638000
400
-668609730341153280
-668609730341153000
-280
610116075740491776
610116075740492000
-224
-371384787345228000
-371384787345228000
161429736530118960
161429736530119000
-40
-52260903362512720
-52260903362512700
-20
12953636989943896
12953636989943900
-4
-2503858755467550
-2503858755467550
10
381922055502195
381922055502195
11
-46280647751910
-46280647751910
12
4465226757381
4465226757381
13
-342252511900
-342252511900
14
20692933630
20692933630
15
-973941900
-973941900
16
34916946
34916946
17
-920550
-920550
18
16815
16815
19
-190
-190
As we can see there are a little difference (digits in red) between the exact coefficients
computed by this macro PolyBuildCfx (multiprecision arithmetic with 30 digits) and those
returned by the function PolyBuild (standard double precision).
89
Xnumbers Tutorial
Polynomial Solving
=PolySolve (Polynomial)
This function returns the roots of a given real polynomial using the Jenkins-Traub algorithm.
a0 + a1 x + a2 x 2 + ...an x n
The arguments can be a monovariable polynomial strings like "X^2+3x+2" or a vector of
coefficients
This function returns an (n x 2) array.
It uses the same algorithm of the RootfinderJT macro. It works fine with low-moderate degree
polynomials, typically up to 10th degree. For higher degree it is more convenient to use the
macro.
Example. Find all roots of the given 10 degree polynomial
Integer polynomial
=PolyInt(Polynomial)
This function returns a polynomial with integer coefficients having the same roots of the given
polynomial. This transformation is also know as "denormalization" and can be useful when the
coefficients of the normalized polynomial are decimal.
Example: Given thefollowing polynomial:
-0.44+2.82x-3.3x^2+x^3
To eliminate decimal coefficients we denormalize the polynomial
-22+141x-165x^2+50x^3 = PolyInt("-0.44+2.82x-3.3x^2+x^3")
Take care with the denormalization because the coefficients became larger and the
computation may lose accuracy. See the example below
The following polynomials have the same root x = 11/10:
Pb(x)
= -2.4024+10.1524x-17.1x^2+14.35x^3-6x^4+x^5
Pa(x)
= -6006+25381x-42750x^2+35875x^3-15000x^4+2500x^5
90
Xnumbers Tutorial
If we compute both polynomials for x = 11/10, with standard double precision we get:
Pa(1.1) = -2.664E-15
Pb(1.1) =
4.547E-12
As we can see, the first value, obtained by the decimal polynomial, is 1000 times more precise
then the one obtained by the integer polynomial
x 2 + 2 xy + y 2 + x y = 0
2
x + y 2 10 = 0
Using SYSPOLY2 the solutions real or
complex can be obtained in a very quick
way
Real solutions represent the intersection
point of the curve poly1 and poly2.
They are: P1 = (3 , 1) , P2 = (1 , 3)
The system has also two complex solutions that have not a geometrical representation
P3 = (2.5 +j 1.118034 , 2.5 +j 1.118034) , P4 = (2.5 j 1.118034 , 2.5 j 1.118034)
The degree of the given system is 4
Example: solve the following system
xy 1 = 0
2
2 xy + y + x + y 1 = 0
91
Xnumbers Tutorial
The apparent degree of the system is 2 x 2 = 4
As we can see, the function SYSPOLY2 returns only three solutions: one real and two
complex.
P1 = (1, 1) ,
P2 = (j , j ) ,
P3 = = ( j , j )
Bivariate Polynomial
=POLYN2(Polynomial, x, y, [DgtMax])
Returns the value - real or complex - of a bivariate polynomial P(x, y).
The parameter "Polynomial" is an expression strings. Valid examples are:
13+x+y^2-y+x^2+2x*y , x^2+y^2-10 , 8x*y+y^2+2x-2 , 10+4x^6+x^2*y^2
Note: the product symbol * can be omitted except for the x*y mixed terms
The third optional parameter DgtMax sets the multiprecision. If missing, the computation is
performed in faster double precision.
The variables x , y can be real or complex. The function can return real or complex numbers.
Select two cells if you want to see the imaginary part and give the CTRL+SHIFT+ENTER
sequence
Example: Compute the polynomial
P = x 2 + 2 xy + y 2 + x y
at the point
x = (2.5 + j 1.11803398874989)
y = (2.5 + j 1.11803398874989)
Verify that it is a good approximation of the
polynomial root
92
Xnumbers Tutorial
N ( x)
R( x)
= Q ( x) +
= Q( x) + Fi
D( x)
D( x)
where each Fi is a fractions of the form
Am
A1
A2
+
+ ...
2
x + p ( x + p)
( x + p) m
or
B x + Cm
B1 x + C1
B x + C2
+ 22
+ ... 2 m
2
2
x + bx + c ( x + bx + c)
( x + bx + c) m
i b = 2 , c = 2 + 2
(1)
Many calculators and computer algebra systems, are able to factor polynomials and split
rational functions into partial fractions. A solution can also be arranged in Excel with the aid of
Xnumbers functions. Let's see
Real single poles. Find the fraction decomposition of the following rational fraction
A3
N ( x)
A1
A2
A4
=
+
+
+
D( x) x + p1 x + p2 x + p3 x + p4
where pi are the roots and Ai are unknown
Several methods exist for finding the fraction coefficients Ai . One of the most straight and
elegant is due to Heaviside that, for a real single root, simply states:
Ai =
N ( pi )
D' ( pi )
93
Xnumbers Tutorial
+
4
3
2
x 15 x + 65 x 105 x + 54
x +1 x + 2 x + 3 x + 9
You can prove yourself that this expression is an identity, thus always true for every x, except
the poles.
Complex single poles. Find the fraction decomposition of the following rational fraction
x 3 21 x 2 + 52 x + 123
N ( x)
= 4
D( x) x 2 x 3 29 x 2 42 x + 650
First of all, we try to find the roots of the denominator using, for example, the function
polysolve. We find that the roots are p = { 5 2i , 4 3i } . They are complex with unitary
multiplicity, therefore the fraction expansion will be
N ( x)
B x + C1
B x + C2
= 2 1
+ 2 2
D ( x) x + b1 x + c1 x + b2 x + c2
where bi and ci , calculated by the (1), are b1 = 10 , c1 = 26 , b2 = 8 , c 2 = 25
The coefficients Bi and Ci are unknown. For solving them we used here the so called
undetermined coefficients method
Renamed, for simplicity:
D1 ( x) = x 2 + b1 x + c1 , D2 ( x) = x 2 + b2 x + c2
The fraction expansion may be rewritten as
N ( x)
B x
C1
B x
C2
= 1 x+
+ 2 +
D ( x) D1 ( x )
D1 ( x) D2 ( x ) D2 ( x)
Giving 4 different values to x, the above relation provides 4 linear equations with the unknown
B1, C1, B2, C2, that can be easily solved. We can choose any value that we want; for example xi
= { 0, 1, 2, 3 } and we get the following linear system
0
1/17
1/5
3/5
1/26
1/17
1/10
1/5
0
1/34
2/45
3/58
1/25
1/34
1/45
1/58
B1
C1
B2
C2
123/650
9/34
3/10
63/290
Solving this linear system by any method that we like, for examply by SYSLIN , we get the
solution
[B1 , C1 , B2 , C2] = [-2 , 7 , 1 , -2]
Substituting these values, we have finally the fraction decomposition
94
Xnumbers Tutorial
x 3 21 x 2 + 52 x + 123
x2
2x + 7
= 2
+ 2
4
3
2
x 2 x 29 x 42 x + 650 x 10 x + 26 x + 8 x + 25
You can prove yourself that this expression is always valid for any compatible value of x
A possible arrangement for solving this
problem In Excel is a bit more
complicated then the previous one.
Let's see. First of all we compute the
roots with the function Polysolve; then
we compute the trinomials D1(x) and
D2(x) by the formulas (1)
Then we compute the polynomials N, D, D1, D2 for each values of x by the function polyn. We
get the 4x5 table visible at the right
From this table we get the complete system matrix in the following way.
The 4 x 4 linear system can be solved by any method that you want. For example by matrix
inversion as shown in the example.
95
Xnumbers Tutorial
Orthogonal Polynomials
Orthogonal polynomials are a class of polynomials following the rule:
b
w( x) p
( x) pn ( x) dx = mn cn
Where m and n are the degrees of the polynomials, w(x) is the weighting function, and c(n) is
the weight. m n is the Kronecker's delta function being 1 if n = m and 0 otherwise.
The following table synthesizes the interval [a, b], the w(x) functions and the relative weigh c(n)
for each polynomials family
polynomial
interval w(x)
[-1, 1]
(1 x 2 ) 1/ 2
for n = 0
/ 2 for n 0
[-1, 1]
(1 x 2 )1/ 2
/2
(1 x 2 ) 1/ 2
21- 2 (n + 2 )
for 0
n!( n + ) 2 ( )
[-1, 1]
Gegenbauer polynomial
2 / n 2 for = 0
2
2 n n!
Hermite polynomial
(-,+)
e x
Jacobi polynomial
(-1, 1)
(1 x) (1 + x)
hn
Laguerre polynomial
[0, +)
e x
generalized Laguerre
polynomial
[0, +)
xk e x
(n + k )!
n!
Legendre polynomial
[-1, 1]
2
2n + 1
Where
hn =
2 + +1
(n + + 1) (n + + 1)
2n + + + 1
n!(n + + + 1)
96
Xnumbers Tutorial
Function Poly_ChebychevU(x, n)
Function Poly_Gegenbauer(a, x, n)
Gegenbauer polynomial
Function Poly_Hermite(x, n)
Hermite polynomial
Function Poly_Jacobi(a, b, x, n)
Jacobi polynomial
Function Poly_Laguerre(x, n, m)
Function Poly_Legendre(x, n)
Legendre polynomial
Example: Tabulate the Legendre polynomial of 6th degree, for 0 x 1, with step h = 0.1
Many thanks to Luis Isaac Ramos Garcia for his great contribution in developing this software
97
Xnumbers Tutorial
98
Xnumbers Tutorial
cn = w( x)[ pn ( x)] dx
2
Function Poly_Weight_ChebychevT(n)
Function Poly_Weight_ChebychevU(n)
Function Poly_Weight_Gegenbauer(n, l)
Gegenbauer polynomial
Function Poly_Weight_Hermite(n)
Hermite polynomial
Function Poly_Weight_Jacobi(n, a, b)
Jacobi polynomial
Function Poly_Weight_Laguerre(n, m)
Function Poly_Weight_Legendre(n)
Legendre polynomial
If we divide each orthogonal polynomial family for the relative weight we have an orthonormal
polynomial family
99
Xnumbers Tutorial
L6 ( x) =
100
1 4
x 16 x 3 + 72 x 2 96 x + 24
24
Xnumbers Tutorial
Complex Addition
Complex Subtraction
Complex Multiplication
Complex Division
Polar Conversion
Rectangular Conversion
Complex absolute
Complex power
Complex Root
Complex Log
Complex Exp
Complex inv
Complex negative
Complex conjugate
Complex Sin
Complex Cos
Complex Tangent
Complex Inverse Cos
Complex Inverse Sin
Complex Inverse Tan
For entering complex functions you must select two cells, insert the complex function and give
the CTRL+SHIFT+ENTER keys sequence. If you press the ENTER key, the function returns
only the real part of the complex number.
Symbolic rectangular format
Xnumbers support the format "x+jy " only in expression strings passed to the function cplxeval.
Except this case, you must always provides a complex number as a couple of real numbers
(one or two cells).
The reason for this choice is that the rectangular format is more adapt for symbolic calculation
while the array format is more convenient for numerical computation characterized by long noninteger numbers.
But, of course, you can convert a complex number (a,b) into its symbolic format "a+jb" by the
Excel function COMPLEX, as shown in the following example
101
Xnumbers Tutorial
XNUMBERS has two sets of complex functions: for standard double precision (prefixed by
"cplx") and for multiprecision (prefixed by "xcplx").
Complex Addition
xcplxadd(a, b, [Digit_Max])
cplxadd(a, b)
Performs the complex addition:
(a 1 , a 2 ) + (b1 , b 2 ) = (a 1 + a 2 , b1 + b 2 )
Complex Subtraction
xcplxsub(a, b, [Digit_Max])
cplxsub(a, b)
Performs the complex subtraction.
(a 1 , a 2 ) (b1 , b 2 ) = (a 1 a 2 , b1 b 2 )
Complex Multiplication
xcplxmult(a, b, [Digit_Max])
cplxmult(a, b)
Performs the complex multiplication:
(a 1 , a 2 ) * (b1 , b 2 ) = (a 1 b1 - a 2 b 2 , a 1 b 2 + a 2 b1 )
Complex Division
xcplxdiv(a, b, [Digit_Max])
cplxdiv(a, b)
Performs the complex division
(a 1 , a 2 ) a 1 b1 + a 2 b 2 a 2 b1 a 1 b 2
=
,
(b1 , b 2 ) b12 + b 22
b12 + b 22
102
Xnumbers Tutorial
Polar Conversion
xcplxpolar(z, [angle], [Digit_Max])
cplxpolar(z, [angle])
Converts a complex number from its rectangular form to the equivalent polar form.
The optional parameter angle sets the angle unit (RAD, DEG) (default RAD).
x
(deg)
1
0.866025
0.707107
0.5
0
-0.5
-0.70711
-0.86603
-1
-0.86603
-0.70711
-0.5
0
0.5
0.707107
0.866025
0
0.5
0.707107
0.866025
1
0.866025
0.707107
0.5
0
-0.5
-0.70711
-0.86603
-1
-0.86603
-0.70711
-0.5
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
30
45
60
90
120
135
150
180
-150
-135
-120
-90
-60
-45
-30
(x, y) ( , )
Where
= x2 + y 2
y
x
= atan , x > 0
= sgn( y )
, x=0
2
, y = 0, x < 0
=
y
atan x + sgn( y ) , y 0, x < 0
Rectangular Conversion
xcplxrect(z, [angle], [Digit_Max])
cplxrect(z, [angle])
Converts a complex number from its polar form to the equivalent rectangular form. The optional
parameter angle sets the angle unit (RAD, DEG) (default RAD).
( , ) (x, y)
Where
x = cos( )
y = sin ( )
Complex absolute
xcplxabs(z, [Digit_Max])
cplxabs(z)
Returns the absolute value of a complex number
| z |=
z12 + z 22
103
Xnumbers Tutorial
Complex power
xcplxpow(z, [n], [Digit_Max])
cplxpow(z, [n])
Returns the nth integer power of a complex number zn (default n = 2)
z n = ( x + iy ) = n e n
n
Where
= x2 + y 2
x
y
= atan
Complex Roots
xcplxroot(z, [n], [Digit_Max])
cplxroot(z, [n])
Returns all the nth roots of a complex extended number z1/n (default n = 2)
The function returns a matrix of (n x 2) values. Remember to press the sequence
CTRL+SHIFT+ENTER for insert properly this function.
The root of a complex number is computed by the De Moivre-Laplace formula.
n
z=
x + iy =
+ 2k
+ 2k
+ i sin
n
n
cos
, k = 0,1...n 1
where
= x2 + y 2
x
y
= atan
Note: If you select only one row, the function return only the first complex root (given for k = 0).
Example: compute all the 3 complex cubic roots of the number z = 8
104
Xnumbers Tutorial
Complex Log
xcplxLn(z, [Digit_Max])
cplxLn(z)
Returns the natural logarithm of a complex number
= x2 + y2
y
x
= atan
Complex Exp
xcplxExp(z, [Digit_Max])
cplxExp(z)
Returns the exponential of a complex number
Complex inverse
xcplxinv(z, [Digit_Max])
cplxinv(z)
Returns the inverse of a complex number
1
1
x
y
=
= 2
i 2
2
z x + iy x + y
x + y2
Complex negative
xcplxneg(z)
cplxneg(z)
Returns the complex negative
z = (x + iy ) = x iy
Complex conjugate
xcplxconj(z)
cplxconj(z)
105
Xnumbers Tutorial
Returns the conjugate of a complex number
z = x + iy = x iy
Complex Sin
=cplxsin(z)
Returns the sine of a complex number
Complex Cos
cplxcos(z)
Returns the cosine of a complex number
Complex Tangent
cplxtan(z)
Returns the tangent of a complex number
Complex ArcCos
cplxacos(z)
Returns the arccosine of a complex number
Complex ArcSin
cplxasin(z)
Returns the arcsine of a complex number
Complex ArcTan
cplxatan(z)
Returns the arctangent of a complex number
106
Xnumbers Tutorial
Complex digamma
cplxdigamma(z)
Returns the logarithmic derivative of the gamma function for complex argument.
( x) =
' ( x)
d
ln ( ( x ) ) =
dx
( x)
et
dt
x t
Ei ( x) =
107
Xnumbers Tutorial
erf ( z ) =
t 2
dt
erfc( z ) = 1 erf ( z )
( x) = t x 1 e t dt
0
108
Xnumbers Tutorial
a z2 + b z + c = 0
where a, b, c are complex
The solutions are found by the resolution formula
z=
b
b 2 4ac
2a
2a
z 2 + (9 2 i ) z + 4 + i = 0
Of course the function can also works with real coefficents equations
z2 + 2 z + 3 = 0
109
Xnumbers Tutorial
Number Theory
Maximum Common Divisor
xMCD(a1, [a2])
MCD(a1, [a2], [a3]...)
Returns the Maximum Common Divisor (also called Greatest Common Divisor, GCD) of two or
more extended numbers
The arguments "a1" and "a2" may be single numbers or arrays (range). At least, two values
must be input. If "a1" is a range, "a2" may be omitted
Note that LCM may easily overcome the standard precision limit even if its arguments are all in
standard precision.
110
Xnumbers Tutorial
N 0 = 0 , N1 = 1
D0 = 1 , D1 = 0
ai +1 = int ( xi / yi )
N i +1 = ai N i + N i 1
xi +1 = yi
Di +1 = ai Di + Di 1
yi +1 = xi yi ai +1
N/D
Error
1.500000000000000
0.08579
1.400000000000000
0.01421
41
29
1.413793103448280
0.00042
99
70
1.414285714285710
7.2E-05
239
169
1.414201183431950
1.2E-05
1393
985
1.414213197969540
3.6E-07
3363
2378
1.414213624894870
6.3E-08
8119
5741
1.414213551646050
1.1E-08
10
47321
33461
1.414213562057320
3.2E-10
11
114243
80782
1.414213562427270
5.4E-11
12
275807
195025
1.414213562363800
9.3E-12
13
1607521
1136689
1.414213562372820
2.8E-13
14
3880899
2744210
1.414213562373140
4.2E-14
15
9369319
6625109
1.414213562373090
1.3E-14
You can regulate the desiderate approximation with the parameter ErrMax
111
Xnumbers Tutorial
Continued Fraction
xFractCont(x, [Digit_Max])
FractCont(x)
These functions perform the continued fraction expansion of a decimal number x
Usually the continued fraction is written in the
compact form x = [a0, a1, a2, a3...]
Each step gives the rational fraction fi = si / ti ,
where the fractions fi converge to the number x
x = a0 +
1
a1 +
1
a2 +
1
a3 + ....
Both the above functions return an array containing the integer values [ai, si, ti].
The algorithm stops when the fraction approximates x with the maximum precision allowed,
that is 10^-15 and 10^-(DgtMax) respectively for the standard and the multiprecision function.
Example. Compute the continued fraction
expansion of the number e2 = 7.38905...
with standard precision (error < 1E-15)
As we can see, the continued fraction of the
transcendental real number e2 can be written
as:
e2 = [7, 2, 1, 1, 3, 18, 5, 1, 1, 6, 30, 8...]
while the correspondent approximating
fractions are
e2
e2
e2
e2
....
15/2 (1.5%),
22/3 (0.75%),
37/5 (0.15%),
133/18 (0.002%),
Sometime the continued fraction expansion requires the multiprecision. Expand, for example,
the Ramanujian number
digits
58
58
112
Xnumbers Tutorial
n = a0 +
n = [a0 , a1 , a2 , a3 ...2a0 ]
1
a1 +
1
a2 +
1
a3 + ....
77
Check Prime
Prime(n)
Prime(n) =
Example
prime(134560093) ="P"
prime(134560079)= 89
Next Prime
NextPrime(n)
This function1 returns the prime number greater than n or "?" if the function is not able to
calculate it
nextprime(9343560093) = 9343560103
113
Xnumbers Tutorial
Modular Addition
xaddmod(a, b, m)
Performs the modular addition1
(a + b) (mod m)
where a, b integer and m positive integer
Modular Subtraction
xsubmod(a, b, m)
Performs the modular subtraction
(a b) (mod m)
where a, b integer and m positive integer
Modular Multiplication
xmultmod(a, b, m)
Performs the modular multiplication
(a b) (mod m)
where a, b integer and m positive integer
Modular Division
xdivmod(a, b, m)
Performs the modular division
(a / b) (mod m)
where a, b integer and m positive integer
Remember that the modular division is always possible if, and only, the module m is prime.
Otherwise the division could be impossible. In that case the function returns "?"
Modular Power
xpowmod(a, p, m)
Performs the modular integer power of ap
That is defined as the remainder of the integer division of ap by m
a p
r = a m
m
p
Modular function xaddmod, xsubmod, xmultmod, xdivmod appear thanks to the courtesy of John Jones
114
Xnumbers Tutorial
Example: compute
1.24575154970238125896669174496E+4250938
This result shows that 123939040 has more then 4 million of digits!
Nevertheless the remainder of this impossible division is
xpowmod(12, 3939040,3001) = 947
Examples: Miscellanea of modular function
115
Xnumbers Tutorial
Perfect Square
xIsSquare(n)
Checks if a number n is a perfect square
xisSquare(1000018092081830116) = TRUE
Because: 1000018092081830116 = 10000090462
xisSquare(2000018092081830116) = FALSE
Check odd/even
xIsOdd (n)
Checks if a number n is odd (TRUE) or even (FALSE)
Check Integer
xIsInteger(x)
Checks if a number x is integer
116
Xnumbers Tutorial
Macro - Factorize
Factorize()
This macro factorize a number of active cell returning the list of prime number and their
exponents
Click copy if you want to copy the list in the worksheet, starting from the cell just below cell
A2.
This macro uses the trial division method with the prime table generated by the Eratostene's
sieve algorithm
This method is adapt for numbers having factors no more that 6 digts max. For higher factor
the elaboration time becames extremely long and it cames usefull a second factorization
method, the so called Pollard rho algorithm, for craking a number into two lower factors (not
necessary prime). Each factors, if not prime, can be factorized separately with the trial division
method.
Example. The number
18446744073709551617 = 274177 * 67280421310721
can be factorized with both methods: it requires about 33 sec with trial division; but less then 3
sec with Pollard method
The following number instead can be factorize only with Pollard method (about 40 sec).
10023859281455311421 = 7660450463 * 1308520867
Note that in this case both factors have 10 digits. The factos are prime so the factorization
stops itself.
For testing the primality see the probabilistic Prime test
117
Xnumbers Tutorial
Large numbers having factors more than 20 digits can be only manipulate with Xnumbers but
no more factorized. This task requires sophisticated algorithms joined with extreme fast
routines, usually written in C++ or Assembler.
When the numbers are very large, no efficient integer factorization algorithm is published; a
recent effort which factored a 200 digit number (RSA-200) took eighteen months and used over
half a century of computer time. The supposed difficulty of this problem is at the heart of certain
algorithms in cryptography such as RSA.
Not all numbers of a given length are equally hard to factor. The hardest instances of these
problems are those where the factors are two randomly-chosen prime numbers of about the
same size, but not too close
Factoring software is available either in commercial math packages or in standalone freeware
programs.
One of the most interesting program released in the public domain, supporting Quadratic Sieve
(QS) and Number Field Sieve (GNFS), that we have used for many years is Msieve.
8004000546054003543176004301
8004000546054003543176004301
p10: 1000400017
prp10: 2000000011
prp10: 4000400023
In this case the program only outputs all the factors found. The code "p10" indicates a prime
factor of 10 digits; "prp10" indicates a probable prime factor of 10 digits.
118
Xnumbers Tutorial
With the option -v (verbose), the program will also output the factoring trace with many useful
information (for factoring experts, of course).
>> msieve -v
8004000546054003543176004301
Start the macro Numbers/Factors..., choose the Msieve and click on "Factorize".
Lists Refresh
Imports the results in
Excel
Kills a running job
Deletes a job
Verbose mode on/off
This Help
The jobs list is automatically refreshed every second. If the refreshing activity stops for some
reason, you can manually refresh it.
119
Xnumbers Tutorial
The factors obtained can be imported into Excel by the apposite buttom. The macro outputs
each factor in the format [exponent, factor]
Time (sec)
1.2 GHz, 256
100
10
1
Digits
0.1
0
10
20
30
40
50
60
70
80
Factorization function
Factor(n)
This function performs the decomposition in prime factors of a given integer number
Returns an array of two columns: the first column contains the prime factors and the second
column contains the exponents
This function is useful for factorizing on-line integer numbers N < 1E14 directly in the
worksheet.
It uses the so called "brute force attack" and the Fermat-Lehman method.
In this example, the given number is
decomposed in 5 factors
2277785128000 = 26 53 232 732 101
The #ND symbol indicates the end of factors
list. To make sure to get all factors you have
to extend the selection until you see this
symbol
Using this function is very simple. Select a range of 2 columns and several rows (for example 7
rows). The insert the function Factor using the ctrl+shift+enter sequence.
120
Xnumbers Tutorial
Prime Test
This macro perform the probabilistic prime test with the Fermat or Miller-Rabin method. These
tests are especially adapt for long number.
Using is very simple. Select the number that you want to test and start the macro from the
menu Macros / Numbers / Prime test
Select the method that you want and press "Test". After few seconds you get the results
Note that this test is exact for
detecting composite numbers,
but it can detect a prime number
with a finite probability (usually
very high).
The numbers satisfying the
Fermat or Miller-Rabin are called
"pseudo-prime"
The probability is correlated to the trials number T with the following approximate formula
Fermat test
Miller-Rabin test
p = 1 2 T
p = 1 4 T
1 7.8 10 31
1 7.8 10 31
You can also select a list of cells containing several numbers to test. This is useful for finding
prime in a set of consecutive integers.
121
Xnumbers Tutorial
122
Xnumbers Tutorial
Diophantine Equation
DiophEqu(a, b, c)
This function solves the Diophantine linear equation
a x+b y = c
x, y Z
xk = x0 + k Dx
y k = y0 + k D y
for k = 0, 1, 2...
x0
D
x
y0
D y
xk = 6 + 3k
y k = 6 2k
Often is not so easy to find the solution of a diophantine equation. Let's see the following.
Long numbers. This function works also with extended numbers.
Example. Find a solution of the equation ax+by = c having the following coefficients
a
b
18760000596690052 13650847757772
Note that the first coefficients has 17
digits and the second one has 14
digits. Without multiprecision it would
be difficult to solve this problem.
You can enjoy yourself to prove that
the result returned from the function
DiophEqu is correct
123
c
64
Xnumbers Tutorial
Brouncker-Pell Equation
= PellEqu(d, [n])
This function solves the so called Brouncker-Pell quadratic equation on the integer domain
x 2 d y 2 = 1 , x, y , d N
The function returns the n-th integer solution (default n = 1) using the continued fraction method.
As know, this equation has non trivial solutions if d is not a perfect square.
The function works for low-moderate integer d values but, even with this constraints,
sometimes this smallest solution is quite small, and sometimes it is huge. Let's see.
Compute the first 3 integer solutions of the equation x 31 y = 1
2
As we can see the solutions grow sharply also for very small d.
Sometime the first solution is huge also with moderate d. In that case is better to arrange the
solution in vertical cells, as shown in the following examples
Note that the "smallest" solution of the equation x 991 y = 1 has 30 digits !
2
When the solution exceed 250 digits or the time of 200 iterations the functions returns "?".
124
Xnumbers Tutorial
Remember that two numbers n , m are relative prime if, an only if, GCD(n, m) = 1
With this function is easy to set a table of the totient (n) values for 1 n 100
(n)
10
10
12
16
18
20
12
10
22
20
12
18
12
28
30
30
16
20
16
24
12
36
18
24
16
40
40
12
42
20
24
22
46
16
42
20
50
32
24
52
18
40
24
36
28
58
16
60
60
30
36
32
48
20
66
32
44
24
70
70
24
72
36
40
36
60
24
78
32
80
54
40
82
24
64
42
56
40
88
24
90
72
44
60
46
72
32
96
42
60
40
125
10
Xnumbers Tutorial
Integer relation
A set of real numbers [x1, x2, ... xn ] , is said to possess an integer relation if there exist a set of
integers [a1, a2, ...an ] , not all zero, such that
a1 x1 + a2 x2 ... + an xn = 0
The integer relation algorithm can be used to solve subset sum problems, as well as to
determine if a given numerical constant is equal to a root of a univariate polynomial with integer
coefficients; in this case we say the constant to be "rational" suche as "12/51" or "algebraic",
such as 2 . On the contrary, if such polynomial does not exist, we say the constant
"transcendental", such as .
Therefore this algorithm can be used for algebraic-transcendental screening of real numbers.
Because we always have an approximated value of the constant, the found integer relation will
not exactly zero but very close to it only if we use a sufficient number of digits.
For example, we find the following 5th degree relation
[a1, a2, a3, a4, a5 ][1, x, x2, x3, x4]T = a1+ a2 x + a3 x2 + a4 x3 + a5 x4 0
where [a1, a2, a3, a4, a5 ] = [-1, 0, -2, 0, 1] , and x = 1.553773974...
Of course, a numerical discovery of a relation by this algorithm does not in general constitute a
proof of this relation; one of the reasons being that the computer operates in finite precision. In
many cases, however, the relations we first discovered numerically subsequently received
rigorous mathematical proofs. Moreover, many complicated relations probably would never,
have been dreamed of without the assistance of the computer.
Algorithms for finding integer relations include HJLS algorithm, LLL algorithm, PSLQ algorithm.
All these algorithms requires high-precision arithmetic, but the PSLQ, developed by Ferguson
and Forcade (1979) and improved by Ferguson and Bailey (1992), is proved the most efficient
and stable integer relation algorithm. The Xnumbers VB macro has been developed from the
PSLQ descripted by Bailey, D. and Plouffe at http://www.cecm.sfu.ca/organics/papers/bailey
Norm and Bounding.
The norm of the relation is defined the Euclidean norm of the vector |x| = [x1, x2, ... xn ]
Among the relations satisfinyg the constraint | xi ai | < , we are clearly interested in those
relations having small norm, and, if possible, with the smallest nth degree.
The constraint of small norm has been introduced for filtering between relations.
In fact, if we can easily observe that, if the vector x becames exagerately large, then an integer
relation will be surely find for any real number.
| 314159265358979323 100000000000000000 | < 10-16 ,
Of course, the norm of this relation is very high (about 3.2 1017 ) and thus we have to reject it
PSLQ computes the norm of any examined relation and returns the bound of the coefficients.
Even if a relation is not found, the resulting bound means that cannot possibly be the root of a
polynomial of degree n, with coefficients of size less than the established bound. Even negative
results of this sort are often of interest.
Examples
given a real value x we build the vector [1, x, x2, x3, ... xn] with n in increasing order n = 3, 4,
5...., we are searching for possible integer relations having small error < 1E-14 and small
norm |x|
4
Polynomial:
14 32 x + 24 x 2 8 x 3 + x 4
2 +2
Polynomial:
2+ 2
4 + 24 x 12 x 2 4 x 3 + 6 x 4 x 6
126
Xnumbers Tutorial
Epprox. value: 2.991971857463750, Exact value:
2+ 3
( 5 + 1) / 2
1 + 2x 4x2
( 2 + 2) / 4
cos( / 7)
1 4 x 4 x 2 + 8x3
Exact value:
1 + x + x 2 x3
19
33 3 19
33 1
+
+
+
27
9
27
9
3
A very simple trick for testing a relation consists in increasing the degree to n+1; if the algorithm
still returns the same relation then, with high probabability, the relation is correct. But pay
attention, because, sometime a numeric value can have two different relations with different
degree. This means that the given value is the root of two different polynomials. Let's see the
following example
Epprox. value: 7.7099759466767, Exact value:
Relation: [221, -108, 18, -1], Polynomial:
5+6
221 108 x + 18 x 2 x 3
But the same value also returns the following relation of degree 5
Relation: [221, 113, -90, 17, -1], Polynomial:
221 + 113x 90 x 2 + 17 x 3 x 4
4+ 2
Relation: [ -8, 48, -20, 56, -6, 8, 5, 0, -1], Polynomial: -1+104x -18x +8x6-x8
Time: 0.4 sec
We have seen that for 8th degree polynomial we have needed about 30 digits, in this case.
Generally speaking, the required precision increases with the degree and the norm of the
coefficients of the polynomial, as reported in the following table
127
Xnumbers Tutorial
Degree
Digits
10
15
16
20
25
28
30
40
80
85
120
170
220
250
Time (sec)
0.5
4.5
5.4
23.0
81.7
126.1
217.7
Absolute limits. The table can be accessed in two ways: given a polynomial degree we get
the minimum precision of the number (number of significant digits); on the contrary, given a
precision of a number (digits) we get the maximum obtainable polynomial degree.
For example, if we are searching for a polynomial of 15 degree, we must have a number with
80 digits, at least. If we have have calculate a number with 100 digits we can search for
polynomials having degree n < 18.
In the above table and graph we have also reported the time1 in second of the PSLQ (two-level)
algorithm. As we can see, the time increases sharply with the degree. The time stays less the
few seconds for n <16, but requires about 3-4 minutes for n = 30 and 250 digits (the maximum
possible for Xnumbers)
Some other high results are shownin the following list. In these trials, the problem is to recover
the polynomial of degree n satisfied by , where = a1/r b1/s. In
other words, the input vector x = (1, , 2, 2.... n-1), where n = (r s + 1). Here the working
precision was set to the level required by PSLQ and the input number was computed with the
needed precision, as determined by the above table.
Degree: 12. Exact value: = 31/ 6 + 21/ 2 2.61515051... (50 digits)
Relation: [ -25, 0, 552, 0, -60, 0, 166, 0, -60, 0, 12, 0, -1] ,
Time: 2.8 sec
Degree: 12. Exact value: = 31/ 4 + 21/ 3 2.57599506... (50 digits)
Relation: [ -11, -216, -360, -32, 27, -288, 24, 0, -9, -8, 0, 0, 1],
Time: 3 sec
Degree: 15. Exact value: = 31/ 5 + 21/ 3 2.50565198951... (80 digits)
Relation:, [ -59, -360, -540, 80, -1620, 27, -80, -540, 0, 40, -9, 0, -10, 0, 0, 1]
Time: 5 sec
Degree: 16. Exact value: = 31/ 4 21/ 4 0.126866897949771... (85 digits)
Relation: [ 1, 0, 0, 0, -3860, 0, 0, 0, -666, 0, 0, 0, -20, 0, 0, 0, 1],
Time: 5.6 sec
Degree: 20. Exact value: = 31/ 5 21/ 4 0.0565238246127... (120 digits)
Relation: [ 49, -1080, 3960, -3360, 80, -108, -6120, -7440, -80, 0, 54, -1560, 40, 0, 0, -12, -10,
0, 0, 0, 1],
Time: 16.8 sec
Degree: 20. Exact value: = 31/ 5 + 21/ 4 2.434938054618... (120 digits)
Relation: [ 49, -1080, 3960, -3360, 80, -108, -6120, -7440, -80, 0, 54, -1560, 40, 0, 0, -12, -10,
0, 0, 0, 1],
Time: 23 sec
1
128
Xnumbers Tutorial
It is interesting to note that the two numbers 31/ 5 21/ 4 gives the same relations. In fact they
are both roots of the same 20th degree polynomial.
Degree: 25. Exact value: = 31/ 5 + 21/ 5 2.39442929461255233... (170 digits)
Relation: [-3125, 0, 0, 0, 0, 21875, 0, 0, 0, 0, -57500, 0, 0, 0, 0, -3500, 0, 0, 0, 0, -25, 0, 0, 0, 0,
1],
Time: 81.7 sec
Degree: 25. Exact value: = 31/ 5 21/ 5
Relation: [ -47, -2688, -13104, -7560, 448, -79296, 136584, -108, -672, -184128, -25956, 0,
560, -74592, 54, 0, -280, -4872, 0, 0, 84, -12, 0, 0, -14, 0, 0, 0, 1],
Time: 126 sec
Degree: 30. Exact value: = 31/ 6 21/ 5
Relation: [ 179, -4860, 30780, -65520, 30240, -192, -405, -98820, -538380, -149520, -240, 0,
270, -84240, 90360, -160, 0, 0, -90, -7380, -60, 0, 0, 0, 15, -12, 0, 0, 0, 0, -1],
Time: 218 sec
129
Xnumbers Tutorial
a0 + a1 x + a2 x 2 + a3 x 3 + ...an x n
General relation
Input: a vector x of n-th dimension
a1 x1 + a2 x2 + a3 x3 + ...an xn
Using this macro is very simple: select the cell containing the number x or the range of the
column-vector x and start the macro. The macro assumes a simple layout in order to speed-up
the input operation. The input layout is different for the two type of relation
Polynomial relation input layout
The cell B2 contains the multiprecision number x
of 30 digits and just below, the cell B3 contains
the degree n. Select the cells B2 and start the
macro
Multiple searching for one x and several degree
Multiple searching for several vectors is possible. Simple select as many adjacent vectors as
we need. Note that each vector can have different dimension. In this case, select the
rectangular range containing all the vectors.
130
Xnumbers Tutorial
Output results
The macro writes the result in the worksheet are beside the input data using a simple standard
layout almost similar for polynomial and general relation.
Let' s see with an example
Example 1. We want to search for a smallest integer polynomial having the approximate root:
x 2.99197185746375045829465694878... (30 digits)
We restrict our searching to the polynomials from 3 to 8 degree
Insert the input data x and the degree
3, 4, 5, 6 and 7 as in the sheet at the
left. Select the cell B1 and start the
macro
The coefficents of the polynomials are listed in the last section of the report, but just above, the
macro write the information returned by the PSLQ routine
Digits: the precision of the calculus
Degree: degree of the polynomial; degree +1 is the dimension of the relation
RC: return code: 0 =OK, 1 =precision exhausted, 2 = iteration overflow, 3= overflow error
This code states the "goodness" of the relation found
Residue: relative residue of the relation, computed as / a , where
a x
i i
, a = max(| ai xi
|)
Bound: this number M states that there can exist no relation vector whose Euclidean norm is
less than M. This is a very important result provided by PSLQ algorithm. Together with RC
helps us to analyze the goodness of the relation found.
Iter: number of iterations needed for reaching the result
Time: elaboration time in seconds
Example 2. We have 3 real numbers x1, x2, x3 computed with 15 precision digits.
x1 = 35.812551166675
x2 = 8.554440155849
x3 = 4.186428394404
x=
1
a a
a2 + a3e + 4 + 5
e
a1
a1 x + a2 + a3e +
a4
a5
=0
e
131
[x, ,
, e, e 1 changing the x
Xnumbers Tutorial
Arrange the 3 vectors as in the
sheet at the left. Select the range
B2:D6 and start the macro.
In very few seconds the macro succesfully finds integer relations for the first two numbers,
while, on the contrary, the third numbers has not a small simple relation. Note how large are
the coefficents of the third column. Note also that its bound M = 3.4E+9 its very high; it assures
that no integer relation exists with norm ||a|| < 3.4E+9
132
Xnumbers Tutorial
n 1 .. cn m an 1 .. an m bn 1 .. bn m
Matrix Subtraction
xMatSub(mat1, mat2, [DgtMax])
Performs the subtraction of two matrices. mat1 and mat2 are (n x m) arrays
n 1 .. cn m an 1 .. an m bn 1 .. bn m
Matrix Multiplication
xMatMult(mat1, mat2, [DgtMax])
Performs the multiplication of two matrices. mat1 (n x p) and mat2 (p x m) are arrays
a11 .. a1 m
c11 .. c1 n a11 a12 .. a1 p
=
a2 1 .. a2 m
n 1 .. cn m an 1 an 2 .. an p a
p 1 .. a p m
Matrix Inverse
xMatInv(A, [DgtMax])
Returns the inverse of a (n x n) square matrix
It returns "?" for singular matrix.
This function uses the Gauss-Jordan diagonalization algorithm with partial pivoting method.
Matrix Determinant
xMatDet(A, [DgtMax])
Returns the determinant of a square matrix.
It returns "?" for singular matrix.
133
Xnumbers Tutorial
Matrix Modulus
xMatAbs(A, [DgtMax])
Returns the absolute value of a matrix or vector.
It is also known as "modulus" or "norm"
Parameters A may be an (n x m) array or a vector
A =
(ai , j ) 2
i =1 j =1
Scalar Product
xProdScal( v1, v2, [DgtMax])
Returns the scalar product of two vectors
n
c = V1 V2 = V1 i V2 i
i =1
Note: The scalar product is zero if, and only if, the vectors are perpendicular
V1 V2 = 0
V1 V2
Similarity Transform
= xMatBAB(A, B, [DgtMax])
Returns the matrix product:
C = B 1 A B
This operation is also called the "Similarity Transform" of the matrix A by the matrix B. This
operation plays a crucial role in the computation of eigenvalues, because it leaves the
eigenvalues of the matrix A unchanged. For real, symmetrical matrices, B is orthogonal. The
Similarity Transform is also called the "orthogonal transform".
A and B must be square matrices.
Matrix Power
= xMatPow(A, n, [DgtMax])
Returns the integer power of a square matrix.
n7
time
64
48
B = A = A A A... A
n
Example
134
Xnumbers Tutorial
Matrix LU decomposition
= xMatLU(A, [Pivot], [DgtMax])
Returns the LU decomposition of a square matrix A
It uses Crout's algorithm
1 0 0 u11 u12
A = L U = l21 1 0 0 u 22
l21 l21 1 0
0
u13
u23
u33
Note: if you want to get only the L and U matrices select a range (3 x 6) before entering this
function
l11 0
T
A = L L = l21 l22
l31 l32
0 l11 0
0 l21 l22
l33 l31 l32
0
0
l33
Xnumbers Tutorial
Example.
The diagonal elements of the L matrix are all positive. So the matrix A is positive definite and
the decomposition is correct. This function simply stops when detects a negative diagonal
element, returning the incomplete decomposition.
See this example
<Attention !>
A diagonal element of the L matrix is
negative. So the matrix is not positive
definite and the decomposition cannot be
completed
Vector Product
= xProdVect(v1, v2, [DgtMax])
Returns the vector product of two vectors
[ A ] x1 = b1 , [ A ] x1 = b 2 , ... [ A ] x1 = b m
It can be rewritten as:
a11
[ A ] [ x ] = [ B ] ...
an 1
.. a1 n x11
.... ...
.. a n n x n1
.. x1m b11
.... = ...
.. x n m b n 1
.. b1 m
....
.. b n m
This function uses the Gauss-Jordan diagonalization algorithm with partial pivoting method.
136
Xnumbers Tutorial
Example. Find the solution of the following 7x7 linear system
A
462
924
1716
3003
5005
8008
12376
792
1716
3432
6435
11440
19448
31824
1287
3003
6435
12870
24310
43758
75582
2002
5005
11440
24310
48620
92378
167960
3003
8008
19448
43758
92378
184756
352716
b
4368
12376
24290
12376
31824
62856
31824
75582
149877
75582
167960
333918
167960
352716
702429
352716
705432 1406496
705432 1352078 2697968
The solution is the vector [1, 1, 1, 1, 1, 1, 1]. Solving with standard arithmetic, we have an
average accuracy of about 1E-8, while in multiprecision we have an accuracy better than 1E-28
(xi xi 1 )
2i 1
= xi
(xi 2 xi 1 + xi 2 )
i 1 i 2
2
vi = xi
This formula can be applied to the second sequence to obtain a new sequence with n-4 values,
and so on. The process stops when the last sequence has less than 3 values.
Example. we want to find the numeric solution of the equation x = cos(x)
We choose the central point method. Starting from x0 = 0 we build the iterations
xn+1 = cos(xn)
137
Xnumbers Tutorial
As we can see in the following table, the convergence is evident but very slow (after 12
iterations the precision is about 3E-5) .
The functions of this worksheet are:
The cell B2 contains the starting value x0
The cell B3 , C2, D3 contain the formulas
[B3]=C2
[C2]=COS(B2)
[D3]=ASS(B2-C2)
Selecting the range B3:D3 and dragging
down we can easily perform the iterative
process as we like.
We observe that the convergence is
evident but quite slow.
As we can see the last 12th value has an
error of about 3.5E-3. But if we perform
the delta extrapolation of the three last
values we get a new value having an
accuracy better than 1E-5.
Now let's repeat the iterative process using systematically the square delta extrapolation
In this process, we have systematically
repeated the 2 extrapolation every 3
iterations.
We have inserted in the cell B5
=ExtDelta2(B2:B4)
In the cell B8
=ExtDelta2(B3:B7)
In the cell B14
=ExtDelta2(B9:B11)
The acceleration is superb!. After only 12 steps, the precision is better than 1E-15.
The graph below shows better than many words the acceleration effect
0
10
12
1
0.01
0.0001
1E-06
1E-08
1E-10
1E-12
1E-14
Error (extrap)
Error
1E-16
The Aitken's extrapolation formula works very well with the Gauss-Seidel iterative method, and
for accelerating the convergence of many iterative processes.
138
Xnumbers Tutorial
Determinant
det(A)
Addition
A+ B
Subtraction
A B
Multiplication
A B
Scalar multiplication
kA
Inverse
A1
Similarity transform
B 1 A B
Linear System
AX = B
Gauss-Jordan algorithm
Ax = b
LU decomposition
A = LU
Crouts algorithm
Cholesky decomposition
A = LLT
Choleskys algorithm
Norm
Gauss-Jordan algorithm
Scalar product
AT B
SVD
U V T
Golub-Reinsch algorithm
The use of this macro is quite simple. If the operation requires only one matrix (determinant,
inversion, etc.) select the matrix, start the macro and choose the appropriate operation.
Other operations (addition, multiplication, etc.) require two matrices. In that case you have also
to select the second matrix in the second input-box.
The internal calculus is performed in multiprecision. The result is converted in standard
precision (15 significant digits max) for more readability, but, if you like, you may also leave it in
full multiprecision format.
Example: Solve the following linear system Ax = b.
139
Xnumbers Tutorial
Then, press OK. The result will be output starting from the output cell I2.
The special button near the input field is useful for selecting large
matrices .Select the first cell, or an internal cell of the matrix and then
press this button. The entire matrix will be selected
Smart
Selector
Elaboration time
Multiprecision computation does slow down the computation considerably. It takes much more
time then the standard double precision. The time depends on the matrix dimension and on
the precision digits. The following graphs show the average time for the inversion and for the
multiplication of two dense matrices.
160
140
Time (sec)
30 digits
time (sec)
120
100
invers.
80
multip.
60
20 x 20
40
20
Nx N
0
25
50
75
digits
100
50
100
150
200
standard precision
Multiprecision
As we can see, the inversion of a (100 x 100) dense matrix, with 30 precision digits, takes
about 150 seconds. Clearly, for this kind of tasks, macros are more suitable than functions.
140
Xnumbers Tutorial
F (k ) = Fr (k ) + i Fi (k ) =
N 1
n=0
The components (Fr , Fi) are called the harmonic spectrum of f(t)
By the Fourier series, we can approximate a periodic function f(t):
f (t ) a0 +
K 1
ak cos(k t ) + bk sin(k t )
k =1
where the coefficients (ak , bk ) are the components 2Fr and 2Fi of DFT
Example: Find the 16-FFT of the following periodic function (T = 1 sec)
where
2
T
First of all we have to sample the given function. Setting N = 16 , we have a sampling period of
t =
1
T
=
N 16
ti = i t
, i = 0, 1,...N 1
141
Xnumbers Tutorial
(FFTre )2 + (FFTim )2
Ai =
FFTim
FFTre
i = arctan
Rearranging the mirror part we can obtain the central Fourier's spectrum.
For example, below there are two representations of the same DFT, obtained setting the
"central" parameter "false" and "true", respectively.
Bilateral DFT
Central DFT
Amp
Amp
0.2
0.2
0.15
0.15
0.1
0.1
0.05
0.05
10 13 16 19 22 25 28 31
142
10 13 16 19 22 25 28 31
Xnumbers Tutorial
f ( n) =
N 1
k =0
Where the components (Fr , Fi) are the harmonic spectrum of f(t)
Example: Find the inverse transform of the FFT computed in the previous example
As we can see, the first column of FFT_INV returns the samples of f(t) that have originated the
FFT itself
143
Xnumbers Tutorial
f (t ) f (0) + An sin (n t + n )
Example: Find the harmonic spectrum of the following 32 samples
Amplitude
1.2
1
0.8
0.6
0.4
0.2
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Phase
100
50
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-50
-100
( An , n )
f (ti )
The parameter "spectrum" is an (M x 2) array. Each row contains a harmonic. The first column
contains the amplitude and the second column the phase
The optional parameter "dB" (default FALSE) sets the output in decibel
The optional parameter "Angle" (default RAD) sets the angle unit (RAD, GRAD, DEG)
The function returns the vector (N x 1) where N = 2M
144
Xnumbers Tutorial
H (0,0) = 1
H (1,0) = 0.05
H (0,1) = 0.1
If we compute the inverse transform DFT2D_INV(L10:S25) we will obtain again the given
starting matrix.
145
Xnumbers Tutorial
DFT
It works for any number N.
If N is a powers of 2 (8, 16, 32, 64, etc.) the macro uses the faster FFT algorithm and the
elaboration is more efficient.
Its use is quite simple. Select the vector of samples and then start the macro
The column x is not strictly necessary. If present, the macro uses it to calculate the sampling
parameters (see the top-right box).
For long input vector, you can select only the first cell C9 and start the macro. The entire input
data set (32 x 1) will be automatically selected.
The macro writes the results in the following way
f
=
Hre =
Him =
Amp =
Phase =
frequency sample
Real part of DFT transform
Imaginary part of DFT transform
Amplitude (if polar is checked)
Phase (if polar is checked)
146
Xnumbers Tutorial
Example of a Fourier
transform of pulse.
Period = 1 sec
Duty cicle = 5.5%
Amplitude = 1
Sampling time = 1/256
f(t)
1.2
1
0.8
0.6
0.4
0.2
0
-0.5
-0.3
-0.1
0.1
0.3
0.5
Amp(f)
0.06
0.05
0.04
0.03
0.02
0.01
0
-100
-50
50
100
Amp
0.06
0.05
0.04
0.03
0.02
0.01
0
0
Amplitude in dB of the
central DFT
(-100 < f < 100)
50
100
150
200
250
Amp (dB)
-25
-30
-35
-40
-45
-50
-55
-60
-100
-50
147
50
100
Xnumbers Tutorial
Operation DFT-inverse
In this case you have to select two columns: the real and imaginary part of the DFT (Hre, Him).
Then start the macro as usually.
If the DFT is in polar form (Amplitude, Phase), you have to check the polar option box and
choose consequently the appropriate units: dB and angle
Operation 2D-DFT
Dimension N and M must be integer power of 2
In this case you have to select a matrix of N x M values (do not select the axes-scales) and
start the macro as usually.
If you want the DFT in polar form (Amplitude, Phase), you have to check the polar option and
choose consequently the appropriate units: dB and angle
148
Xnumbers Tutorial
Macro Sampler
This is a simple but very useful macro for function sampling
It can generate samples of multivariate functions such as:
f (x) , f (x1, x2) .... f (x1, ... xm)
The samples can be arranged in a list or in a table (only for 2 variables).
Examples of lists and tables generated by this macro are shown in the following sheet
The tables at the top are the skeletons to generate the samples-list or the samples-table just
below. The skeleton contains the following parameters for the sampler.
Start
Samples
Period
Step
Cyclic
The first point and the last point, in this case, are always taken.
But, for a periodic function, the same sampling needs a step of H = 0.4
Practically, the last point X = 2, in this case, is discharged, because is f(0) = f(2). Usually
periodic functions require to set Cyclic = True for the FT analysis
The skeleton can be drawn by hand or
automatically. In this case you have only to give
the number of variables that you want.
The check-box Function seed tells the macro
to created also the cell in which you can insert
the function to sample
149
Xnumbers Tutorial
A simple skeleton for one variable is:
In the cell C2 you must insert the function
f(x) to sample. The reference for the
independent variable x is the cell B2. For
example, if the function is y = x +2x2
You have to insert the formula
= B2+2*B2^2 in the cell C2
Parameters N (Samples), P (Period), H (Step) are not all independent. Only two parameters
can be freely chosen.
The macro chooses the first two parameters found from top to bottom
The remain parameter is obtained by the step-formula
Synthetically you can have one of the following three cases
Given parameters
Samples, Period (N, P)
Samples, Step
(N, H)
Period, Step
(P, H)
Calculated parameter
Step
(H)
Period (P)
Samples (N)
Look at the following three examples below for better explanation. The given parameters are in
blue while the calculated parameter is in red.
After you have set and filled the skeleton, select it and start the sampler macro again
(remember that range must always have 6 rows, including the header)
The macro show the following window
The check-box Add formula tells to the macro to leave the formula in the sample set,
otherwise it contains only the values. Formula can be added only for a monovariable list or for a
table.
150
Xnumbers Tutorial
Integral function
=IntegrData(xi, yi, [IntType])
Computes numerically the integral functions F(xi) of a given dataset (xi, yi)
xi
F ( xi ) = yi dx
0
I12 = h( f1 + f 2 ) / 2
symmetric
E h 3 f ( 2 ) / 12
I 23 = h( f1 + 13 f 2 + 13 f 3 f 4 ) / 24
Left side
I12 = h(9 f1 + 19 f 2 5 f 3 + f 4 ) / 24
Right side
I 34 = h( f1 5 f 2 + 19 f 3 + 9 f 4 ) / 24
E 11 / 720 h 5 f ( 4 )
symmetric
E 191 / 60480 h 7 f ( 6)
Left side
Right side
Depending on the case, the algorithm uses these formulas at the beginning, at the center and
the end of the integration interval.
2 points formula
f1
f2
x
h
4 points formulas
f1
f2
f3
f1
f4
f2
f3
x
h
f1
f4
f2
x
h
151
f3
f4
Xnumbers Tutorial
6 points formulas
f1
f2
f3
f4
f5
f1
f6
f1
f2
f3
f4
f5
f3
f4
f5
f6
f6
x
h
h
f1
f2
f2
f3
f4
f5
f6
f1
f2
f3
f4
f5
f6
x
h
Example. Compute the integral function of the following tabulated function y(xi)
1.E+00
err1
err2
err3
1.E-01
1.E-02
1.E-03
1.E-04
1.E-05
1.E-06
0
Usually the 3rd degree formulas are the best compromise between cost and precision
Avoid discontinues. But, generally, do highest integration degree formulas always give the
best precision? Not always. When the function to integrate shows jumps or direction
discontinuities, the better choice is the linear formula. See the following example.
Given the following functions
y ( x ) = (| x 4 | + x ) / 2 | x 2 |
its exact integral function is
x
F ( x) = y ( x)dx = ( x 4) | x 4 | 2( x 2) | x 2 | + x 2 + 8 / 4
0
152
Xnumbers Tutorial
Sampling the function y(x) and F(x) with h = 0.25 for 0 x 6, we have the following data
sets (xi, y(xi)) and (xi, F(xi))
4.5
4
3.5
3
2.5
y dx
1.5
1
0.5
0
0
As we can see, the function y(x), always linear, has no derivative at the points x = 2, and x = 4.
If we integrate the data set (xi, yi) with the 1st degree formula (IntType = 1) the result coincides
with the exact solution (error = 0). But if we try with the other higher formulas the average error
is, surprisingly, about 0.005
The first method is simple and it is already shown in the previous chapter; the second way
need some more explanation.
The function y(x) that we want to plot is defined as
x
y ( x) =
f ( x)dx
x0
Taking the derivatives of both sides and remebering Leibniz's rule, we have
y ' ( x) = f ( x)
y ( x0 ) = 0
As we can see, the computing of any integral function is equivalent of solving an ODE.
Therefore we can use any method that we have used for solving ODE: Runge-Kutta, PredictorCorrector, Taylor, etc. (see chap. ODE for further details)
The third method, less efficient then the others, may be successfully used when the function
f(x) or its derivatives f'(x) has some singularities in the integration range.
The following example explain better the concept. Assume to have to plot the integral function
of the following function
x
y ( x) = ln( x 2 )dx
0
x 0
Therefore, x = 0 is a singular point. From theory we know that the integral exists, thus we can
project to tabulate the given integral for several points xi = ih with a suitable step h, for
example h = 0.1
For this scope we may use the function integr_de or Integr that are more suitable for such
singularities
153
Xnumbers Tutorial
Insert the function definition in cell B1
Ln(x^2)
Build a sequence x = 0, 0.1, 0.2...4 in the
range A4:A44
Insert the function integr_de in cell B5 and the
function = LN(A5^2) in cell C5 and drag down
the range B5:C5.
Note that we cannot complete the first cell C4
because of #NUM! error.
Now, plotting the the range A5:C44, we have the following graph
Comparing with the exact
solution
4
f(x)
y ( x) = x ln( x 2 ) 2 x
f(x)
2
1
0
-1
-2
-3
-4
0
0.5
1.5
2.5
3.5
y ( x) =
f (t )dt = 0
xn +1 = xn
x0
y ( xn )
f ( xn )
154
Xnumbers Tutorial
I = f ( x)
a
The parameter "Funct" is a math expression string in the variable x, such as:
"x*cos(x)", "1+x+x^2", "exp(-x^2)", ecc.. .
Remember the quote " " for passing a string to an Excel function.
"Funct" may be also a cell containing a string formula
"Param" contains label and values for parameters substitution (if there are)
"Rank", from 1 to 16 (default), sets the maximum integration rank.
"ErrMax" (default 1E-15) , sets the maximum relative error.
For further details about writing a math string see Math formula string
The algorithm starts with rank = 1 and incrementing the rank until it detects a stop condition.
|R(p, p) - R(p, p-1)| < 10^-15
or
(|R(p, p) - R(p, p-1)|) / |R(p, p)| < 10^-15
or
rank = 16
Example. Compute the integral of "x*cos(x)" for 0 x 0.4
Integr_ro("x*cos(x)", 0, 0.4) = 0.0768283309263453
This function can also display the number of sub-intervals and the estimate error.
To see these values simply select three adjacent cells and give the CTRL+SHIFT+ENTER key
sequence.
This result is reached with rank = 4 , s = 16 sub-intervals, and an estimate error of about
E = 3.75E-16
The function accepts also external parameters. Remember only to include the label in the
parameter selection.
155
Xnumbers Tutorial
I = f ( x)dx
f ( x)dx
I=
I=
f ( x)dx
The parameter "funct" is a math expression string in the variable x, such as:
"x*cos(x)", "1+x+x^2", "exp(-x^2)", ecc.. .
Remember the quote " " for passing a string to an Excel function. "funct" may be also a cell
containing a string formula.
The limits "a" and "b" can also be infinite. In this case insert the string "inf"
"Param" contains labels and values for parameters substitution (if there are)
For further details about writing a math string see Math formula string
The Double Exponential method is a fairly good numerical integration technique of high
efficiency, suitable for integrating improper integrals, infinite integrals and "stiff" integrals having
discontinue derivative functions.
This ingenious scheme, was introduced first by Takahasi and Mori [1974]
For finite integral, the formula, also called "tanh-sinh transformation", is the following
b
x(t ) =
b+a ba
+
tanh (sinh(t ) )
2
2
h(t ) =
ba
cosh(t )
2 cosh 2 (sinh(t ) )
Example
1
0.5
(1 x) 0.3 dx = 0.474421154996...
The above integral is very difficult to compute because the derivative is discontinue at 0 and 1
The Romberg method would require more than 32.000 points to reach an accuracy of 1E-7. On
the contrary, this function requires less then 100 points for reaching the high accuracy of 1E-14
This function uses the double exponential quadrature derived from the original FORTRAN subroutine INTDE of the
DE-Quadrature (Numerical Automatic Integrator) Package , by Takuya OOURA, Copyright(C) 1996
156
Xnumbers Tutorial
Example
dx
As known, the integral exist if n > 1 and its value is I = 1/(n-1). The parameter "n" is called
"order of convergence". For n = 1.1 we get I = 10
Note that we need to pass the parameter with its label "n". (Param = "D1:D2")
This function cannot give reliable results if n is too close to 1.
The minimum value is about n = 1.03. For lower values the function returns "?".
The DE integration works very well for finite improper integral
Example
1
( )
( )
2
2
ln x dx = lim+ ln x dx = 2
0
a 0
ln( x)
x dx = 4 / 9
157
Xnumbers Tutorial
f ( x)dx
f ( x)dx
f ( x)dx
f ( x)dx
This function can compute definite integrals, improper integrals and piece-wise functions
integrals. The parameter "funct" is a math expression string in the variable x, such as:
"x*cos(x)", "1+x+x^2", "exp(-x^2)", ecc.. .
Remember the quote " " for passing a string to an Excel function.
"funct" may be also a cell containing a string formula
The limits "a" and "b" can also be infinite. In this case, insert the string "inf"
"Param" contains labels and values for parameters substitution (if there are)
This function uses two quadrature algorithms
1) The double exponential method1 (see function integr_de )
2) The adaptive Newton-Cotes schema (Bode's formula) (see macro Integral_Inf )
If the first method fails, the function switches on the second method
Oscillating functions, need specific algorithms. See Integration of oscillating functions (Filon
formulas) and Fourier's sine-cosine transform
Example. Compute the integral of xcos(x) for 0 x 0.4
In the given interval the function is continuous, so its definite integral exists. This result is
reached with rank = 4, s = 16 sub-intervals, and an estimate error of about 3.7E-16. This
function returns the integral and can also displays the number of sub-intervals and the estimate
error. To see these values simply select three adjacent cells and give the
CTRL+SHIFT+ENTER keys sequence.
Note that the function Integr is surrounded by { } . This means that it returns an array
The function Integr can accept also parameters in the math expression string.
See the example below.
This function uses the double exponential quadrature derived from the original FORTRAN subroutines INTDE and
INTDEI of the DE-Quadrature (Numerical Automatic Integrator) Package , by Takuya OOURA, Copyright(C) 1996
158
Xnumbers Tutorial
Note that we must include the parameter labels in order to distinguish the parameters "k", "w",
and "q". The integration variable is always "x"
Beware of the poles
Before attempting to evaluate a definite integral, we must always check if the integral exists.
The function does not perform this check and the result may be wrong. In other words, we have
to make a short investigation about the function that we want to integrate. Let's see the
following example.
Assume the following integrals to have to compute
1/ 2
2
2x 1
2
dx ,
2
2x 1
2
dx
We show that the first integral exists while, on the contrary, the second does not exist
For x p =
2
lim+ 2 = +
x x p 2 x 1
The first integral exists because its interval [0, 0.5] does not contain the pole and the function is
continuous in this interval. We can compute its exact value:
2x
2
2
dx =
| 2x 1|
2
log
2
| 2x +1|
1/ 2
2x
2
2
dx = 2 log 2 1
The interval of the second integral contains the pole, so we have to perform some more
investigation. Let's begin to examine how the integral function approaches the pole xp taking
separately the limit from the right and from the left
lim log
x x p
2 x 1
=
2 x + 1
lim+ log
x x p
2 x 1
=
2 x + 1
As we can see the both limits are infinite, so the second integral does not exists
Note that if we apply directly the fundamental integral theorem we would a wrong result:
1
2
| 2 x 1 |
=
log
dx
0 2 x 2 1
| 2 x + 1 | = 2 ln 2 1
2
0
wrong !
159
Xnumbers Tutorial
The numeric result is, of course,
completely wrong because the
given integral goes to the infinity.
But, even in this situation, this
function gives us an alert: the subintervals have reached the
maximum limit of 65536 (216)
So the result accuracy must be
regarded with a reasonable doubt.
F (b) F (a ) = f ( z )dz
a
The integration function "Funct" must be a string in the variable z and can be defined mixing all
arithmetic operators, common elementary functions and complex numbers like:
"z*cos(z)", "1+(1+i)*z+z^2", "exp(-z^2)", ecc.. .
Remember the quote " " for passing a string to an Excel function.
Parameters "a" and b can be real or complex. Complex values are inserted as arrays of two
cells.
Example: Evaluate the following integral
1+i
1+ i
dz
2
z
1i
Because the integration function is analytic, then the given integral is independent form the
integration path. Therefore it can be calculated by the function cplxintegr
The exact result is the complex
number (1+i)
Note that, thanks to the excellent
accuracy, the result is shown exactly
even if it is intrinsically approximated
160
Xnumbers Tutorial
h n
f j bj
k j =0
f ( x)dx =
x0
10
45
288
140
17280
14175
89600
299376
b0
14
95
41
5257
3956
25713
80335
b1
64
375
216
25039
23552
141669
531500
24
250
27
9261
-3712
9720
-242625
64
250
272
20923
41984
174096
1362000
14
375
27
20923
-18160
52002
-1302750
95
216
9261
41984
52002
2136840
41
25039
-3712
174096
-1302750
5257
23552
9720
1362000
3956
141669
-242625
25713
531500
b2
b3
b4
b5
b6
b7
b8
b9
b10
80335
As we can see, for degree=1, the Newton-Cotes formula coincides with the trapezoidal rule
and, for degree = 2, with the popular Cavalieri-Simpson formula.
Trapezoid rule
Cavalieri-Simpson rule
x2 x0
2
x2
h
f ( x) 3 ( f 0 + 4 f1 + f 2 )
x0
h = x1 x0
h=
x1
h
f ( x) 2 ( f 0 + f1 )
x0
h=
x4
x 4 x0
4
f ( x)dx 45 (14 f
+ 64 f 0 + 24 f 0 + 64 f 0 + 14 f 0 )
x0
161
Xnumbers Tutorial
As we can see, the convergence to the exact result is evident. The most accurate result is
reached with the 6th degree Newton-Cotes formula. The IntegrDataC can work with random
samples.
Example. Given the data table (xi yi) , approximate the integral with the Cavalieri-Simpson
formula.
y
1
1.1
1.2
1.4
1.8
2.4
3.2
4
5
0
0.09531018
0.182321557
0.336472237
0.587786665
0.875468737
1.16315081
1.386294361
1.609437912
1.6
1.2
0.8
0.4
0
0
Converted to
Equidistant Samples
{ (xi = x0+i h , yi (xi ) ; i = 0, 1, ... m }
For computing the values f(x0+i h ) at the equidistant grid points, IntegrDataC uses the Aitken
Interpolation algorithm.
Aitken interpolation algorithm.
Given a set of points:
{ (xi , yi)
i = 0, 1, ... n }
162
Xnumbers Tutorial
This method is used to find the interpolation point yp at the value xp .
It is efficient as the Newton formula, and it is also very simple to code.
For j = 1 To n - 1
For i = j + 1 To n
y(i) = y(j) * (x(i) - xp) - y(i) * (x(j) - xp)/ (x(i) - x(j))
Next i
Next j
yp = yi(n)
F (b) F (a ) = f ( x)dx
a
The parameter "Funct" is a math expression string in the variable x, such as:
"x*cos(x)",
"1+x+x^2",
"exp(-x^2)", ecc.. .
Remember the quote " " for passing a string to an Excel function.
"Funct" may be also a cell containing a string formula
The parameters "a" and "b" are the limits of integration interval
The parameter "Intervals" sets the number of sub-intervals of the integration interval.
The parameter "degree", from 1(default) to 10, set the degree of the Newton-Cotes formula.
degree = 1 coincides with the Trapezoidal rule; degree = 2 coincides with the CavalieriSimpson formula; degree = 4 with the Bode's rule.
Remember that the total knots of the function computation is:
knots = Intervals Degree + 1
Example: Approximate the following integral using 10 sub-intervals and three different
methods: trapezoidal, Cavalieri-Simpson, and Bode's rule.
1
xe
dx
xe
dx = ( x + 1)e x
1 2e 1 0.264241117657115356
163
Xnumbers Tutorial
Integr_nc("x*exp(-x)",0,1,10,1) = 0.263408098685072
0.4
0.35
(8.3E-04)
f(x)
0.3
0.25
0.2
0.15
0.1
0.05
0
0
0.2
0.4
0.6
0.8
1.2
Integr_nc("x*exp(-x)",0,1,10,2) = 0.264241039074082
The Cavalieri-Simpson
rule, with 10 subintervals, requires 3
knots for each subinterval for a total 21
function evaluation (21
knots)
0.4
0.35
(7.8E-08)
f(x)
0.3
0.25
0.2
0.15
0.1
0.05
0
0
0.2
0.4
0.6
0.8
1.2
Integr_nc("x*exp(-x)",0,1,10,4) = 0.264241117655293
0.4
0.35
(1.8E-12)
f(x)
0.3
0.25
0.2
0.15
0.1
0.05
0
0
0.2
0.4
0.6
0.8
164
1.2
Xnumbers Tutorial
F ( x) = f ( x) dx
and the second step is the evaluation of the definite integral applying the fundamental
integration theorem.
b
This approach can only be adopt for the set of the functions of which we know the antiderivative in a closed form. For the most f(x), the integral must be approximated either by
numerical quadrature or by same kind of series expansion.
It is usually accepted that symbolic approaches, when possible, gives more accurate result
then the numeric one. This is not always true. Even if the symbolic anti-derivative is known in a
closed form, it may often be unsuitable for further numerical evaluation. In particular, we have
cases in which such "exact" answers, when numerically evaluated, give less accurate results
than numerical quadrature methods1
Let's see. Assume to have the following integral functions
F ( x) =
( )
3x 2
dx = arctan x 3 + c
6
x +1
"Improving Exact Integral from Symbolic Algebra System", R.J. Fateman and W. Kaham, University of California,
Berkeley, July 18,2000
165
Xnumbers Tutorial
f ( x) sin(kx) dx
f ( x ) cos( kx) dx
for k = 1, 2, 3...N
The parameter "Funct" is a math expression string in the variable x, such as:
"x*cos(x)",
"1+x+x^2",
"exp(-x^2)", ecc.. .
Remember the quote " " for passing a string to an Excel function.
"Funct" may be also a cell containing a string formula
The parameters "a" and "b" are the limits of integration interval
The parameter "k" is a positive integer
The parameter "Intervals" sets the number of sub-intervals of the integration interval.
Remember that the total number of the evaluation nodes is: Nodes = Intervals 2 + 1
To understand the effort in this kind of numerical integration let's see this simple test. Assume
we have to evaluate the following integral for several integer values k, with 0 < k < 25
cos(kx) dx
If we perform the computation with the Cavalieri-Simpson formula (80 nodes) and with the Filon
formula (80 nodes), we get the following result
0
1.E+00
10
15
20
25
30
Cavalieri-Simpson
1.E-01
Fillon
1.E-02
1.E-03
1.E-04
1.E-05
1.E-06
1.E-07
1.E-08
1
sin(8 x)
+1
g ( x) sin(8 x)
g ( x) =
where
1
x +1
2
The plot of the integration function and its envelope function g(x) are shown in the following
graph
166
Xnumbers Tutorial
1.2
1
1/(x^2+1)
0.8
0.6
1/(x^2+1)*sin(8*x)
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1/(x^2+1)
-1
-1.2
0
The approximate error is less then 1E-8, with 300 intervals (default)
167
Xnumbers Tutorial
f ( x) sin( k x) dx
f ( x) cos(k x) dx
a
sin x
dx =
x
2
0
sin x
0 x dx =
1
sin x dx
x
These functions use the double exponential quadrature derived from the original FORTRAN subroutine INTDEO of
the DE-Quadrature (Numerical Automatic Integrator) Package , by Takuya OOURA, Copyright(C) 1996
168
Xnumbers Tutorial
We see that the accuracy is better than 1E-15. Note that the function Fourier_sin automatically
multiply the integration function f(x) for the factor sin(k*x), so we have only to pass the f(x)
expression.
Example. Verify that is
+
cos 4 x
dx =
8
x
0
cos 4 x
0 x dx =
1
cos 4 x dx
x
cos( x ) cos(2 x )
dx
x
The integration function coverges to zero but it contains two oscillating terms. So we cannot
use directly the integr or integr_de function because they returns "?"
For solving we can use the Fourier's cosine trasform, separating each oscillating term.
The given integral can be re-arranged in the following way
+
cos( x ) cos(2 x )
cos( x ) cos(2 x )
dx =
dx +
x
x
0
1
cos( x )
dx +
x
cos(2 x )
dx
x
Note that the last two integrals cannot have the lower limit 0 because they do not converge for
x approaching to 0.
169
Xnumbers Tutorial
The first integral can be evaluted with the function integr and the two last integrals are
evaluated with the function Fourier_cos with a = 1. Let's see the following spreadsheet
arrangement
sin 4 ( x)
dx
x2
Remembering that is
3 cos(2 x) cos(4 x)
+
sin 4 ( x) =
8
2
8
The given integral can be arranged as
+
sin 4 x
sin 4 x
dx
=
0 x 2 dx +
x2
3
cos(2 x )
1 8 x 2 dx + 1 2 x 2 dx +
cos(4 x )
dx
8x 2
1
The first and second integral can be evaluted with the function integr and the two last integrals
are evaluated with the function Fourier_cos with a = 1.
170
Xnumbers Tutorial
Example. Calculate the following integral
+
sin (x ) dx
2
This function oscillates very badly. Note that the function does not converge to zero, oscillating
continuously from 1 and 1, but we can show that its integral is finite.
x2 = t
x= t
dx =
1
2 t
sin (x ) dx =
2
sin (t )
dt
2 t
171
dt
Xnumbers Tutorial
Double Integral
2D Integration for Normal Domains
Xnumbers contains routines for integrating bivariate functions f(x, y) over a normal domain
(normal to the x-axis and/or to the y-axis) or a circular domain.
g 2(x)
x2+y2 R2
d
h 1(y)
g 1(x)
h 2(y)
x
x
x
a
b
Domain normal to x-axis
Circular Domain
For those kinds of 2D-domains the integration formulas can be re-written as the following
b g 2 ( x)
f ( x, y)ds = f ( x, y)dydx
DX
a g1 ( x )
d h2 ( y )
f ( x, y)ds = f ( x, y)dxdy
DY
c h1 ( y )
2 R
f ( x, y)ds =
C
f ( cos( ), sin( )) d d
0 0
Note that a normal domain implies that - at least - one axis must have constant limits.
Rectangular domains are a sub-case of normal domains in which both axes have constant
limits.
The macro Integr2D - suitable for integrating smooth functions f(x, y) and its function version
Integr_2D use the same bidimensional Romberg algorithm, but the function is limited to about
65.000 points.
f ( x, y)dydx
X min Ymin
The integration functions f(x, y) and eventually also the bounding limits Xmin, Xmax,
Ymin, Ymax -can be written in symbolic expression. For further details about the math string
see Math formula string
The integration function can be:
Xnumbers Tutorial
ln(1 + x + y )
Integration domain D
0 x 1
x2 y x +1
The domain D is shown in the above plot. As we can see, it is an x-nomal-domain domain.
Verify that the given integral approximates the symbolic expression at the right
1 x +1
D ( x, y )
0 x2
9 ln(3)
3 17
+ 7 ln(2)
4
12
8
173
Xnumbers Tutorial
0 x 1 , 0 y x
Another elegant way to insert constant in the integration function is using parameters
Example. Evaluate numerically the following double integral
sin(nx) cos(my)dxdy
0 0
174
Xnumbers Tutorial
1
128 2 + 256
3
f ( x, y, z )dxdydz = f ( x, y, z )dxdydz
D
x = sin cos
y = sin sin
z = cos
where , from 0 to 2, is the rotation angle on the xy-plane and , from 0 to , is the colatitude
angle
The triple integral changes in
f ( x, y, z )dxdydz = f ( x, y, z )
D
min
min
sin d d d
min
The macro can also integrate in cylindrical coordinates system, using the formulas
x = cos
y = sin
z=z
175
Xnumbers Tutorial
where , from 0 to 2, is the rotation angle on the xy-plane
The triple integral changes in
f ( x, y, z )dxdydz = f ( x, y, z ) dddz
D
min
min
z min
Functions f(x, y, z) and eventually also the boundary functions may be written in symbolic
expression..
For further details about the math string see Math formula string
Integration function can be:
three-variate functions like x^2+y^2-x*z , log(1+x+y+z) , (x+z)/(1+x^2+y^2) , etc.
Constant numbers like 0 , 2 , 1.5 , 1E-6, etc.
Constant expressions like 1/2 , 2+1 , sin(pi/4) , etc.
Boundary limits can be:
Constant numbers like 0 , 2 , 10 , 3.141 , etc.
Constant expressions like 1/2 , 2+1, pi, sin(1/2*pi) , exp(1) , etc.
univariate or bivariate functions like x/2 , 3y-10 , x^2+x-1 , sin(x+z), Ln(x+y) , etc.
A normal domain has, at least, two constant boundary limits.
The Integration function and the boundary limits can be passed to the macro directly or by
reference. That is: we can write directly the symbolic expressions into the input fields, or you
can pass the cells that containing the expressions (simpler), or even a mixed mode.
Lets see how it works
Example 1. Approximate numerically the following triple integral
1 2 3
54 xyz dxdydz
0 0 0
Now select the cell A2 containing the integration function and start the macro from the
Xnumbers toobar Macros > Integral > Triple.
176
Xnumbers Tutorial
As we can see, all the input
boxes are filled with the right
references.
The output result will start
from the A4 cell
Optionally we can adjust the
Rank, increasing it, if we want
to increase the final accuracy.
But usually the only thing to
do is click on the run button
Warning: The Rank increase
exponentially the computation
effort, because the number of
max points is (2*Rank)^3
Parameter input box may be
used to pass values of one or
more parameters eventually
present in the integration
function
The macro outputs 5 results:
1) Integral
2) Relative error estimation
3) Total points evaluated (function + boundaries)
4) Elaboration time
5) Error message (if any)
The results will appear as the following
( x
+ y 2 ) dxdydz
x2 + y2 + z 2 1
This domain is a sphere of unitary radius. Therefore is better to pass to the spherical
coordinates because the integration domain becomes much simpler, being
0 1 , 0 2
The macro automatically performs the spherical transformation; so we have only to set the right
boundaries
Select the cell A2 and start the macro. Select "Polar" and set the Rank = 25. Press "Run"
177
Xnumbers Tutorial
f ( x, y)dydx
X min Ymin
The integration functions f(x, y) and eventually also the bounding limits Xmin, Xmax,
Ymin, Ymax -can be written in symbolic expression. For further details about the math string
see Math formula string
The integration function can be:
bivariate functions like x^2+y^2-x*y, log(1+x+y), 1/(1+x^2+2*y^2), etc.
constant numbers like 0 , 2, 1.5, 1E-6 , etc.
constant expressions like 1/2, 2+1, sin(0.1), etc.
The boundary limits can be:
constant numbers like 0 , 2 , 10 , 3.141 , etc.
constant expressions like 1/2 , 2+1, pi, sin(1/2*pi) , exp(1) , etc.
monovariable functions like x/2 , 3y-10 , x^2+x-1 , etc.
A normal domain has, at least, two constant boundary limits.
Example. Approximate the following double integral
1 x +1
ln(x + y + 1) dy dx
0 x2
3 17
9 ln(3)
+ 7 ln(2)
4
12
8
In order to avoid long elaboration time, the function limits the total evaluation points to about
65.000 (rank = 8). For heavy computations use the macro Integr2D
178
Xnumbers Tutorial
Note: this function can also return the relative error, the total of evaluation points and the error
message (if any). To see these values simply select a range of two, three or four, adjacent cells
(vertical or horizontal) and give the CTRL+SHIFT+ENTER key sequence.
Example: Approximate the following integral
1
ex
0 y/2
1
dxdy
x + y2 +1
2
0 y 1
y
x ey
2
As we can see the domain is
normal to the y-axes
The calculus of this double integral can be arranged as the following
( a x
e
+ b y 2 )
dxdy
0 0
Note that the parameters "a" and "b" must be passed with their labels.
179
Xnumbers Tutorial
Example. Compute numerically the following integral
x 2 + y 2 dxdy
180
Xnumbers Tutorial
Infinite integral
Integral_Inf()
This macro performs the numeric integration of a smooth, regular, not oscillating function f(x)
over an unlimited (or very long) interval
f ( x)dx ,
f ( x)dx ,
f ( x)dx
The Bode formula with 8 steps to calculate the integral and the truncation error.
I h1 =
2h
(7 f 0 + 32 f1 + 12 f 2 + 32 f 3 + 7 f 4 )
45
I h2 =
2h
(7 f 4 + 32 f5 + 12 f 6 + 32 f 7 + 7 f8 )
45
I h = I h1 + I h 2
ET
I h I h2
63
After each step the routine detects the truncation error and recalculates the step in order to
keep a constant error (variable step integration method).
The double exponential algorithm, also called "tanh-sinh quadrature". first introduced by
Takahasi and Mori, is based on the hyperbolic variable transformations.
It is more complicated then the polynomial Newton-Cotes schema but, on the other hand, it is
much more efficient.
Using this macro is very easy.
Example: Approximate the given integral
100 x 2 e x dx
The integration function is regular over the entire x-axes; the exponential assures the
convergence. Therefore the infinite integral exists.
Put the symbolic expression 100*x^2*exp(-x) in any cell that you like (A3 for example), and
arrange the worksheet in the following way (but it is not obligatory at all)
The word inf means of course infinity. It is not necessary to specify the sign, because the
macro always assumes b as +inf , a as -inf
Now select the cell A3 and run the macro Integral_Inf . The input fields will be automatically
filled
181
Xnumbers Tutorial
Choose run to start the integration routine. The result will be similar to the worksheet below
(without formatting) where we have compared the results of both methods
As we can see the integral is 100 with an excellent approximation for both methods but the
double exponential is more efficient. It required only 199 function evaluations.
Sometime we have to calculate the integral over the entire x- axes. Let see
x2 + 2x + 3
dx
x4 + x +1
Note that, in this case, we have needed more than 10.000 evaluation points for the variable
step method but only 344 for the DE method. The superiority is ever so evident? Not always.
There are cases in which the adaptive quadrature schema works better. For example when the
integration function has a finite discontinuity (jump) inside the integration interval; this usually
happens for the piecewise functions.
Example, Assume to have to compute the following didactical integral
+
sgn (1.5 x ) x
dx
182
Xnumbers Tutorial
As we can see the variable step method has find the result with high precision using about
7200 steps. The double exponential algorithm fails the convergence
We have to put in evidence that using quadrature algorithms in a blind way, may lead to
wrong result. We should always study the integration function to discover singularities,
discontinuities, convergence rate, etc. If the integration function is sufficiently smooth, then
the numeric integration can give good approximate results.
This routine can also be used over a closed long interval, when other algorithms would take too
long computational time.
this function computes the numerical double integral over the domain D
f ( x , y)dxdy
D
183
Xnumbers Tutorial
f ( x , y) = e x / 3 + e y
with xi = 0.3 i and yi = 0.2 j
Therefore the above result is an approximation of the following integral
3 4
x/3
+ e y dydx
0 0
Ln(x + 2 y + 1)
D
3 3
2 1
0 3
0 1
1 0
184
Xnumbers Tutorial
But it could be approximated in a worksheet sampling the domain for 0 <= x <= 3 and 0 <= y <=
4 with a suitable grid, for example hx = 0.1 , hy = 0.1
185
Xnumbers Tutorial
Series Evaluation
=xSerie(Funct, Id, a, b, [Param], [DgtMax])
Returns the numeric series of a function f(n) .
b
S = f ( n)
n=a
(1) n+1
n =1
xn
n
(1) n+1
n =1
2n
2 2 23 2 4
210
= 21 + ...
n
2 3 4
10
xSerie("(-1)^(n+1)*x^n/n","n",1,10,2)= -64.8253968253968
Example 2. Compute
10
s=
n =0
xn
n!
for x = 1.5, with standard precision (15 digits) and with 25 digits. As known, this series
approximates the exponential e^(-1.5)
186
Xnumbers Tutorial
s=
n =1
bn + a
n
Note that we have enclosed the labels "a" and "b" in the range B4:C5 passed to the function as
the argument "Param". The labels indicate to the function the correct assignment between the
variables and their values
Labels are optional. If we pass only the range B5:C5, without labels, the function assign the
values to the variables in the order from left to right.
Note how compact and straight is this calculation using the xSerie function.
S =
k =0
(1) k
1+ k
= Log(2) = 0.693147180559945...
In the cell B4 we insert the formula
=Series($B$1;"k";0;A4)
In the cell C4 we insert
=(B4-LN(2))
we fill the rows from 5 to 16 simply selecting the range
B4:C4 and dragging it down.
In the last cell B17 we have inserted the function
=ExtDelta2(B10:B16)
performing the 2 extrapolation using the last 7 values
of the sum
As we can see, the cell B16 shows the sum with 12 terms; its approximation is very poor
having an error of more than 0.01. But if we apply the 2 extrapolation at the last seven partial
sums S(12), S(11), S(10) .... S(6) we have a good approximation with an error less then 1E-8
Note that for reaching this accuracy the given series would need more than 100 million terms!
187
Xnumbers Tutorial
S = f ( z , n)
n=a
"Formula" is a math expression string defined by arithmetic operators and common elementary
functions such as:
"2^n/n*(-1)^(n+1)", "x^n/n!", "(-1)^(n)*(3+j)*x/(n-1)", ...
Remember the quote """ to pass a string to an Excel function.
The integer variable must be n.
The parameters "a" and "b" set the minimum and the maximum limits of the integer variable "n".
The function may have also a complex variable "z". In that case specify its value in the
parameter z0.
Example: evaluate the given series for z = z0 = 2-i
20
S =
n =1
z
z z
z
= z + + + ...
n
2 3
20
188
Xnumbers Tutorial
Double Series
= xSerie2D(Funct, Id1, a, b, Id2, c, d, [Param], [DgtMax])
Returns the numeric double series of a function f(n, m).
b
S = f (m, n)
m = a n =c
s=
10
m = 0 n =1
x (n + 2m )
n!m!
for x = 0.8
Take care to the index limits because, for large interval, this function can slow down your Excel
application
189
Xnumbers Tutorial
Trigonometric series
= Serie_trig(t, period, spectrum, [offset], [angle], [smooth])
It returns the trigonometric series
N
f (t ) = f (0) + an sin (n t + n )
The set
(an , n )
n =1
2
T
, n = 1...N
f (t ) = f (0) + n an sin(n t + n )
n =
n =1
sin(n / N )
n / N
T = T/(N-1)
The table at the left contains the
parameters for each harmonic: the
integer multiple of the harmonic, its
amplitude and its phase
Period T = 1
4
n Arm.
1
2
3
3.5
3
2.5
Amp
1
0
0.4
Phase
45
0
-45
2
1.5
1
Period T
0.5
0
0
0.5
1.5
190
cos( ) = sin( + / 2)
Xnumbers Tutorial
The ringing phenomenon is an overshoot of Fourier series occurring at simple discontinuities
(jumps). The series does not converge uniformly to a discontinuous function in a small interval
of the discontinuity point. It can be proven that, at each discontinuity point, the series either
overshoots or undershoots by about 9% of the magnitude of the jump.
The ringing can be removed with the Lanczos sigma factors.
Example. The phenomenon is illustrated for a square wave.
Given the spectrum of the first 20 harmonics An = { 0, 1, 0, 1/3, 0, 1/5, 0, 1/71/19, 0 } and n
= 0, of the square wave with period T = 1, lets plot its Fourier series with and without Lanczos
sigma factors (parameter smooth = true / false respectively)
1.2
1
0.8
0.6
0.4
0.2
0
-0.2 0
-0.4
-0.6
-0.8
-1
-1.2
1.2
1
0.8
0.6
0.4
0.2
0
-0.2 0
-0.4
-0.6
-0.8
-1
-1.2
0.2
0.05
0.4
0.6
0.1
0.8
0.15
0.2
1.2
0.25
As we can see, the series with Lanczos factors (pink line) shows a more stable and smooth
behavior. Note, however, that ringing has interesting physical consequences. Consider, for
example, a linear electric circuit in which, by means of a switch, a fast voltage transition is
created: then the response of the circuit will really exhibit an overshoot
191
Xnumbers Tutorial
f ( x, y ) = f 0 + an ,m cos( n x x + m y y + n , m )
n =1 m =1
where
x =
The set
[a
n ,m
2
Lx
, y =
2
Ly
, n ,m ] n = 0...N , m = 0...M
Amplitude
Phase
45
0.5
-45
0.25
15.5
0.125
30
192
Xnumbers Tutorial
Discrete Convolution
Convol(f, g, h, [algo])
This function approximates the convolution of two sampled functions f(ti), g(ti)
+
f *g =
f (v) g (t v)dv
In the signals analysis the function f is called "input signal" x(t) and g is called "system impulse
response" h(t). The convolution fg is called "system responce" y(t)
The system behavior is reassumed in the following schema
193
Xnumbers Tutorial
x(t)
h(t)
y(t)
In a linear system, the outputs signal y(t) depends by the input signal x(t)
and by the inpulse responce of the system h(t). That is:
y(t) = x(v) h(t-v) dv
If the system is described by the following differential equation
y ' (t ) + k y (t ) = x(t )
which has an impulse response given by
h(t ) = e k t
We will use convolution to find the zero input response of this system to the square signal of
period T = 1 and amplitude xmax = 1.5
For obtaining this gaph we have used a sampling step of t = 0.02, but this value is not critical.
You can choose the size that you like in order to obtain the needed accuracy.
194
Xnumbers Tutorial
Interpolation
Polynomial interpolation
=PolyInterp(x, xi, yi, [degree], [DgtMax])
=PolyInterpCoef(xi, yi, [degree], [DgtMax])
The first function performs the interpolation of a given set of points (x,y), and returns the value
at the point x.
The Input parameters Xi and Yi are vectors.
The parameter "degree" sets the interpolation polynomial degree (default = 1)
The optional parameter DgtMax sets the maximum digits of the multiprecision arithmetic. If
omitted or 0, the functions works in faster double precision.
The second function returns an array containing the coefficients of the polynomial interpolation.
Use CTRL+SHIFT+ENTER for inserting this function.
This function use the following popular Newton's formula:
m 1
n
p( x) = y1 + D( x1 ,...xm ) ( x x j )
m =1
j =1
where D(x1,...xn) is the "divided difference", given by the following recursive formulas:
D( x1 , x2 ) =
D( x1 , x2 , x3 ) =
y1 y2
x1 x2
, D( x2 , x3 ) =
y 2 y3
,....
x2 x3
D( x1 ,...xm 1 ) D( x2 ,...xm )
D( x1 , x2 ) D( x2 , x3 )
, ..... D( x1 ,...xm ) =
x1 xm
x1 x3
Example : Compute the sub-tabulation between a set of 6 given points (x, y) using a linear
polynomial and a 3rd degree polynomial and a step of h = 0.2. Note that the given points are not
equidistant.
195
Xnumbers Tutorial
Sub-Tabulation with Degree = 1
1.2
1.2
0.8
0.8
0.6
0.6
y Interp
0.4
y Interp
0.4
0.2
0.2
0
0
0
10
10
If we wonder which is the 3rd degree polynomial used for interpolating the point x = 3.2 we can
use the function PolyInterpCoef.
p( x) = a0 + a1 x + a2 x 2 + a3 x 3
with the coefficients [a0, a1, a2, a3] returned from the function PolyInterpCoef
We can plot this polynomial by the function Polyn. The interpolation polynomial is shown in the
above graph.
Note that the function has selected the 4 points [x2, x3, x4, x5], discharging the first point x1 and
the last point x6, in order to get the most possible accurate interpolation.
Note. when the number of the points (x, y) is exactly degree+1, then the polynomial is
univocally determined no matter which the interpolation point is: we can pass any number x
that we like, for example x = 0.
In the following example we determine the 2nd degree polynomial interpolating the given 3
points with 30 significant digits
196
Xnumbers Tutorial
Interpolation schemas
If the number N of the points (x, y) is exactly equal to degree+1, then the polynomial is
univocally determined; but if N > degree+1 there are several different polynomials that can be
used for interpolating a given point x. A popular method, adopted by the function PolyInterp is
called "sliding centered polynomial"
Linear interpolation
xi,
xi+1
The linear interpolation is always performed between the nodes xi xi+1 where x [xi xi+1]
For degree > 1 the interpolation strategy is more complicated.
Odd degree polynomial (example degree = 3)
The 3rd degree interpolation is performed between the nodes {xi-1 xi, xi+1, xi+2 } where
x [xi , xi+1]. At the first of the segment, the interpolation is performed between the nodes
{x1, x2, x3, x4 } where x [x1 , x3]. At the end, the interpolation is performed between the
nodes { xN-3, xN-2, xN-1, xN } where x [xN-2 , xN ].
Even degree polynomial (example degree = 2)
average interpolation
x1, x2, x3
xN-2, xN-1, xN
Right polynomial
The 2rd degree interpolation is performed between the nodes {xi-1 xi, xi+1 } and { xi, xi+1, xi+2 }
where x [xi , xi+1]. The first set gives the left interpolation polynomial while the second set
gives the right interpolation polynomial. In the range x [xi , xi+1] the final interpolation is
obtained taking the average of the two polynomials. At the first of the segment, the interpolation
is performed between the nodes {x1, x2, x3 } where x [x1 , x2]. At the end, the interpolation is
performed between the nodes { xN-2, xN-1, xN } where x [xN-1, xN ].
The average interpolation schemas adopted for even degree polynomials can often increase
the gloabal accuracy but, on the other hand, it reduces the efficence.
This example helps to explain this trick.
Assume to have the data set composed by 4
points; we want to perform the parabolic
interpolation of a point y(x) where 0.6 x 1
and y(0.6) = y2 and y(1) = y3
1
2
3
4
0.2
0.6
1
1.4
0.163746
0.329287
0.367879
0.345236
197
Xnumbers Tutorial
0.5
0.45
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0
0.2
0.4
0.6
0.8
1.2
1.4
1.6
0.2
0.4
0.6
0.8
1.2
1.4
1.6
0.5
0.45
0.35
0.4
0.3
0.25
0.2
0.15
0.1
0
If we compute the absolute errors |y(x) - PR(x)| , |y(x) - PL(x)|, |y(x) - PM(x)| in the range
0.6 x 1, we observe a significant error reduction for the average polynomial, as shown in
average
0.005
left
0.004
right
0.003
0.002
0.001
0
0.4
0.6
0.8
1.2
In this case the average-parabolic polynomial accuracy is comparable with the cubic
polynomial.
cubic
0.0016
average
0.0012
0.0008
0.0004
0
0.4
0.6
0.8
1.2
But we have to consider that the simple cubic interpolation schema is more efficient then the
average-parabolic. Generally odd degree interpolation schemas are preferable.
198
Xnumbers Tutorial
y a0 +
x x0
x x1
a1 +
x x2
a2 +
x x3
a3 +
a4
y=
x2 + 2
x 2 0 .9
You can verify that the interpolation with these coefficients are better than 1E-14 for all x values
in the range [0.4 1.6]
Note also that this great precision is reached in spite of the pole (x 0.95) in the interpolation
range. The continued fraction interpolation is just suitable for interpolating rational functions.
The following graph shows very well how interpolate points fits the curve.
199
Xnumbers Tutorial
Interpolation with continued
fraction
50
40
y samples
30
y interp
20
10
0
-10
-20
-30
-40
-50
0.4
0.5
0.6
0.7
0.8
0.9
1.1
1.2
1.3
Example: Find an interpolation formula for the function tan(x) in the range 0 x 1.5 with no
more than 7 points.
The function tan(x) has a pole at x 1.57 , near to the upper bound 1.5; so its presence
suggests to adopt a fraction interpolation.
Assume to sample the function tan(x) at the
values (0, 0.2, 0.6, 1, 1.25, 1.45, 1.5).
The column A contains the knots of the
interpolations
In colum B we have inserted the
correspondent values of tan(x)
In column C we have computed the
coefficients of the fraction interpolation.
Using the function FracInterp we can interpolate any value between 0 and 1.5
obtaining the graph to the left. The second graph shows the absolute error in the given range.
You can verify that the interpolation is better than 1E-5 for any value x in the given range.
200
Xnumbers Tutorial
201
Xnumbers Tutorial
The points of the original table was extracted from the function y = [cos(x)]4 .
You can verify that the interpolation accuracy is better than 1% over the entire range.
202
Xnumbers Tutorial
ys = as ,3 ( x xs )3 + as , 2 ( x xs ) 2 + as ,1 ( x xs ) + as ,0
where s = 1, 2, (n-1)
Example. Find the cubic spline polynomials that fit the given knots
203
Xnumbers Tutorial
2D Mesh Interpolation
=Interp_Mesh(TableXY)
This function performs the linear interpolation of a bivariate function given in a pivot table XY.
The x-values and y-values must be sorted but not necessarily equidistant. This function returns
an array. Let's see how it works.
Regularization
As we can see, the use of this function
is straight. Simply select the area
where you want to insert the new
table, insert the function Interp_mash
and pass the old table as parameter.
The function Interp_mesh returns the
equidistant-linear-interpolated array.
Or, in other words, it returns the
regularized table
Rescaling
We can obtain a sub-tabulated
function in an very fast way
Simply select a larger area
The function Interp_mesh
counts the cells that you have
selected and fill all the cells with
the linear interpolated values
In this case the given table has
5 x 4 = 20 values.
The new table has 9 x 7 = 63
values; therefore, there are 43
new interpolated values
204
Xnumbers Tutorial
aij = 2i 3 j
205
Xnumbers Tutorial
for i = 2...N
for i = 2...N
for i = 2...N1
for i = 2...N1
, for i = 1...(N-1)
Where:
A = (xi+1 x)/ (xi+1 xi)
B= 1A
C = 1/6 (A3 A) (xi+1 xi)2
D = 1/6 (B3 B) (xi+1 xi)2
The 2nd derivatives can be evaluated by the following linear equations
(xi x i-1) Pi-1 + 2 (xi+1 xi-1) Pi + (xi+1 xi) Pi+1 = Hi
for i = 2...(N-1)
where:
Hi = 6[(Pi+1 Pi)/(xi+1 xi) (Pi Pi-1)/(xi xi-1)] , P1 = 0 , PN = 0
That gives the following tridiagonal matrix system
2(x3 x1)
(x3 x2)
...
P2
H2
(x3 x2)
2(x4 x2)
(x4 x3)
...
P3
H3
(x4 x3)
2(x5 x3)
(x5 x4)
...
P4
(x5 x4)
2(x6 x4)
...
...
P5
...
...
...
...
...
(xN xN-1)
...
...
(xN xN-1)
2(xN xN-2)
PN-1
xi x < xi+1
H4
H5
HN-1
Xnumbers Tutorial
We note also that its solution (P1 , P2 , ... PN ) depends only by the given knots, therefore the
2nd derivatives can be evaluated only once for any interpolate.
This example shows how the interpolation spline works.
Y
X
0
1
2.5
3
4
5
0
2
4
3
4
1
For these 6 knots we obtain 5 cubic polynomials having the following coefficients
Polynomials
1st spline
2nd spline
3rd spline
4th spline
5th spline
a3
a2
a1
Range
0x<1
1 x < 2.5
2.5 x < 3
3x<4
4x<5
a0
0.20148927
1.79851073
-0.8783764
0.60446781
2.40297854
5.54708717
-3.348226
-1.7126588
-3.0718353
4.97240473
-0.9005694
1.41436706
-4.2431012
-0.1712659
In the graphs below we can see the interpolated points (dotted line) fitting the data points and
the cubic polynomials (green line) passing through the nodes of each segment. Each
polynomial interpolates inside the proper segment. That is: the 1st spline works for 0 x < 1,
the 2nd spline for 1 x < 2.5, and so on.
In the graphs below are shown the entire interpolation line (left) and the 1st spline (right).
6
spline Interp
knots
0
-1
-1
spline Interp
knots
1st spline
0
1
-1
-2
-1
-2
In the graphs below are shown the 2nd spline (left) and the 3rd spline (right)
6
5
0
-1
-1
spline Interp
knots
3rd spline
spline Interp
knots
2nd spline
0
1
-1
-2
-1
-2
In the graphs below are shown the 4th spline (left) and the 5th spline (right)
207
Xnumbers Tutorial
spline Interp
knots
4th spline
6
5
1
0
0
-1
spline Interp
knots
5th spline
-1
-1
-1
-2
-2
Lets examine the 1st and 2nd derivatives. We can compute them either analytically or
numerically using for example -the following derivative formulas:
y(xi) (yi+1 2 yi + yi-1)/ x2
Y''
15
3
2
10
1
0
-1 0
-2
-3
-5
-4
-5
-10
As we can see the 1st derivatives is smooth and the 2nd is continuous. This last feature is
particularly appreciated in many fields of engineering. Although this algorithm is less efficient
than other polynomial interpolation methods, it has the advantage of following the interpolated
curve without the spurious oscillations that other schemes can create
208
Xnumbers Tutorial
1.2
cos(x)^10
1
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
-1
cubic spline
cubic poly
0
-2
cos(x)^10
-2
-1
-0.2
-0.2
The curves appear acceptable in both graphs. The second shows a closer fit near the points x
= 1 and x = -1 where are "knees" of the curve.
But matching the error plots, we see clearly the better accuracy of the spline interpolation.
0.06
0.04
0.02
0
-0.02
error cubic poly
-0.04
-1.5
-1
-0.06
-0.5
0
0.5
1.5
209
Xnumbers Tutorial
12
10
10
8
y
y
cubic
poly
knots
4
0
0
0.2
0.4
0.6
0.8
1.2
12
0.2
0.4
0.6
0.8
1.2
12
y
10
10
cubic spline
fraction
0
0
0.2
0.4
0.6
0.8
1.2
0.2
0.4
0.6
0.8
1.2
We can see a good general accuracy except for the final part of the polynomial interpolation
method. In this case, the worst accuracy is concentrated where the function is more flat, but,
surprisingly, this perturbation is due to the distant pole in x = -0.01. We note also that both
spline and fraction methods keep a good accuracy also for point external at the interpolation
range ( extrapolation for x >1 )
0
0.2
0.4
0.6
0.8
10
1
0.1
0.01
poly
spline
fraction
0.001
0.0001
210
Method
avg. err.
Cubic spline
0.22
Cubic poly
0.19
Contined fraction
0.003
Xnumbers Tutorial
Differential Equations
Xnumbers contains functions for solving the following differential problem of the 1st order with
initial conditions (Cauchys problem):
y = f (t , y )
, y (t0 ) = y0
y = f (t , y )
, y (t0 ) = y 0
y1 = f1 (t , y1 , y2 ... yn )
y1 (t0 ) = y10
y = f (t , y , y ... y ) y (t ) = y
2
2
1
2
n
20
, 2 0
....
....
yn = f n (t , y1 , y2 ... yn ) yn (t0 ) = yn 0
ODE Runge-Kutta 4
= ODE_RK4(Equations, VarInit, Step, [Par, ])
This function integrates numerically a 1st order ordinary differential equation or a 1st order
differential system, with the Runge-Kutta formula of 4th order
k1 = f (ti , yi )
k 2 = f (ti + 0.5 h, yi + 0.5 h k1 )
k3 = f (ti + 0.5 h, yi + 0.5 h k 2 )
k 4 = f (ti + h, yi + h k3 )
yi +1 = yi +
h
(k1 + 2k 2 + 2k3 + k 4 )
6
"Equations" is a math expression string containing the equation to solve. For a system It is a
vector of equations. Examples of correct equation definition are:
y = -2*y*x
v = 2*x-v^2+v
y1 = -3*y1+y2+sin(10*t)
Each string may contain symbolic functions with variables, operators, parenthesis and other
basic functions.
The parameter "VarInit" is a vector containing the initial values. It has two values for two
variables [ t0, y0 ].
For a system with n+1 variables, "Varinit" is an (n+1) vector [ t0, y10 , y20, .yn0 ].
The parameter "Step" is the integration step.
The optional parameter "Par" contains the values of other extra parameters of the equations.
Lets see how it works with an example
Solve numerically the following Cauchys problem for 0 x 3
y = 2 xy
, y ( 0) = 1
x2
211
Xnumbers Tutorial
We have also added the column with the exact values in order to check the approximation
error. Both exact and approximated solutions are plotted in the following graph
1.2
y
y exact
0.8
0.6
0.4
0.2
0
0
0.5
1.5
2.5
The approximate solution (dots) fits very good the exact solution (pink curve).
212
Xnumbers Tutorial
If you need, you can include parameters inside the differential equation
Example. Solve the following differential problem
y ' = k x n y
y (0 ) = 1
where k = 2 and n = 1
Note that we have added the
labels "k" and "n" above the
cells D2 and E2. In this way,
the parser will correctly
substitute the value 2 for the
variable "k" and 1 for the
variable "n". in the differential
equation
Do not forget the labels "x"
and "y" in the cells A5 and B5
y '+
1
y = a x n , y (1) = 0
x
y' = a x n
y
, y (1) = 0
x
Note the labels "a" and "n"
above the cells D2 and E2. In
this way, the parser will
substitute the value 1 for the
variable "a" and 3 for the
variable "n". in the differential
equation
Do not forget the labels "x"
and "y" in the cells A5 and B5
With the step h = 0.1, we have a numerical solution with a very good approximation comparing
with the exact solution y = ( x 1) /(5 x ) , (better than 1E-6)
5
Relative Error
8.E-07
7.E-07
6.E-07
5.E-07
4.E-07
3.E-07
2.E-07
1.E-07
0.E+00
0
0.5
1.5
213
2.5
3.5
Xnumbers Tutorial
This function can be used to solve ordinary differential systems.
Example: Solve numerically the following differential system, where v(t) and i(t) are the voltage
and the current of an electric network
v' = i 7 v
i ' = 5 i + 15 v
v(0) = 10
i (0) = 0
The computation can be arranged as
following.
Write the variables labels in the row 6. The
labels v and i must be the same that
you have written in the equations. Just
one row below, insert the starting values in
the same order.
Select the range A8:C8 and insert the
function ODE_RK4. The first step will be
returned.
Now select this row and drag it down for
evaluating all the steps that you need
The graph below shows the transient of v(t) and i(t) with good accuracy
Note that you can change the
step h in order to re-compute
the transient in a very fast and
quick way.
12
v
10
8
6
4
2
0
0
0.4
0.8
1.2
Optional constant parameters can be arranged. For example if you want to add a parameter R,
independent from the time t, write:
Constant parameters can be
written in any part of the
worksheet. You need only to add
the labels with the same symbols
with they appear in the differential
equations. In this case, we have
added the label "R" in the cell C1,
upon its values.
You can add as many optional
parameters that you like
214
Xnumbers Tutorial
ODE Multi-Steps
Another very popular method for integrating ordinary differential equations adopts the multistep Adams formulas. Even if a little formally complicated, they are very fast, and adapted to
build a large family of ODE integration methods
The multi-step Adams formulas can be generally written as:
yi +1 = yi +
h
M
yi +1 = yi +
h
M
where
k =1
N k
y 'i k +1 = yi +
h
( N 1 y'i + N 2 y 'i 1 +... 0 y'i N +1 )
M
N k
y 'i k + 2 = yi +
h
( N 1 y 'i +1 + N 2 y 'i +... 0 y 'i N + 2 )
M
k =1
y 'i = f (ti , yi )
ti = t 0 + h i
The first formula generates the explicit formulas also called predictor formulas.
The second formula generates the implicit formulas also called corrector formulas.
The number N is the order of the formula. A formula of N order requires N starting steps. Of
course, formulas with high N are more accurate.
For N = 1 we get the popular Euler integration formulas
yi +1 = yi + h y 'i
h
yi +1 = yi + ( y 'i +1 + y 'i )
2
1 2 ( 2)
h y
2
1
e h 3 y ( 3)
12
e
h
(55 y 'i 59 y 'i 1 +37 y 'i 2 9 y 'i 3 )
24
h
yi +1 = yi + (9 y 'i +1 +19 y 'i 5 y 'i 1 + y 'i 2 )
24
yi +1 = yi +
Predictor (4 step)
Corrector (4 step)
251 5 ( 5)
h y
720
19 5 ( 5)
e
h y
720
215
Xnumbers Tutorial
10
12
24
720
1440
60480
120960
3628800
7257600
-1
-9
251
-475
19087
-36799
1070017
-2082753
-16
37
-1274
2877
-134472
295767
-9664106
20884811
23
-59
2616
-7298
407139
-1041723
38833486
-94307320
55
-2774
9982
-688256
2102243
-91172642
252618224
1901
-7923
705549
-2664477
137968480
-444772162
4277
-447288
2183877
-139855262
538363838
198721
-1152169
95476786
-454661776
434241
-43125206
265932680
14097247
-104995189
1
2
3
4
5
6
7
8
9
30277247
10
12
24
720
1440
60480
120960
3628800
7257600
-1
-19
27
-863
1375
-33953
57281
-5
106
-173
6312
-11351
312874
-583435
19
-264
482
-20211
41499
-1291214
2687864
646
-798
37504
-88547
3146338
-7394032
251
1427
-46461
123133
-5033120
13510082
475
65112
-121797
5595358
-17283646
19087
139849
-4604594
16002320
36799
4467094
-11271304
1070017
9449717
2
3
4
5
6
7
8
9
2082753
Error coefficient
The general error is e -khOrd+1y(Ord+1) where k is given by the following table
Ord.
predictor
corrector
0.5
0.41667
0.375
-0.0833
-0.0417
10
-0.0188
-0.0143
-0.0114
-0.0094
-0.0079
-0.0068
Evaluation
Correction
f(t1, yp1)
f(t2, yp2)
The value y1 can be reused to evaluate again the function f(t1, y1), that can be used in the
corrector formula to obtain a more accurate value for y1.
216
Xnumbers Tutorial
If we indicate the first value obtained by the corrector with y1(1) and the second value with y1(2)
we can arrange a new following schema
Prediction
Evaluation
yp1
Correction
f(t1, yp1)
y1(1)
Evaluation
Correction
f(t1, y1(1))
y1(2)
Evaluation
Correction
f(t1, yp1)
y1
Evaluation
f(t1, y1)
This schema is called PECE and it is used very often being a reasonable compromise between
the accuracy and the computation effort.
Using different schemas with different predictor-corrector formulas we can build a wide set of
algorithms for the ODE integration. Of course they are not equivalent at all. Same of them have
a high accuracy, others show a better efficiency and others have a better stability. This last
characteristic may be very important for long integration intervals. In fact, the most algorithms,
especially those with higher order, become unstable when the integration step grows over a
limit. Algorithms that are stable for any integration step (so called A-stable algorithms) are
much appreciated, but unfortunately they require implicit formulas that, generally, can be
solved only by iterative algorithms.
The 2nd order trapezoid formula is one of the most popular A-stable formula.
217
Xnumbers Tutorial
Predictor- Corrector
= ODE_PRE(yn, f, h)
= ODE_COR(yn, fp, f, h)
These functions perform the integration of the ordinary differential equations with the popular
multi-step predictor-corrector Adams formulas
y = f (t , y )
, y (t0 ) = y0
The first function returns the predictor value yn+1,p while the second function returns the
corrector yn+1.
The parameter yn is the last point of the function y(t).
The parameter f is a vector containing the last N values of the derivative of y(t). That are the
last N-1 values of the corrector.
The parameter fp, only for the corrector, is the best approximation of the derivative of y(t) at
the step n+1. Usually it is provided by a predictor formula
The parameter h sets the integration step
y ' = xy 2
, y (0) = 2
Let's set in a cell that we like the integration step h and then the heading of the data table. We
set separate columns for predictor and corrector values
Build the first row.
Begin to insert the starting
values (x0, y0) in the cells A6
and B6 respectively, and the
formula evaluations of f(x,y) in
the cell C6 and E6. The
corrector value is set equal to
the starting value B6
218
Xnumbers Tutorial
Insert in the cell B7
=ODE_PRE(yn, f, h)
yn is the last value of y(x).
contained in D6. f is the last
value of f(x,y) contained in E6.
h is the step B3.
The yP and yC values can be compared with the ones of the exact solution.
y=
2
1+ x2
0.1
err predictor
0.08
The differences:
0.06
d ip = yip y ( xi )
0.04
d ic = yic y ( xi )
0.02
2nd PECE
-0.02
-0.04
219
Xnumbers Tutorial
Now we solve the above differential equation with a 4th order PECE algorithm using the 4 steps
Adams-Bashforth-Moulton formulas
y ' = xy 2
, y (0) = 2
To start this algorithm needs 4 steps. A good set of starting steps is:
x
y(x)
0
0.2
0.4
0.6
2
1.9230769231
1.7241379310
1.4705882353
The first 4 rows of the PECE algorithm are built as shown in the previous example.
The first 4 values of yp and yc are
the same.
Now let's insert in the cell B10
=ODE_PRE(yn, f, h)
where yn is the last value of
y(x), D9 in that case.
f is a vector of the the last four
values of f(x,y), E6:E9 in this
case.
h is the step B3.
0.015
0.01
0.005
0
0
-0.005
0.5
1.5
2.5
ep
4th PECE
-0.01
220
Xnumbers Tutorial
In order to compare the accuracy of the solutions of the this algorithm with the 2nd order
algorithm of the previous example let's draw both the error curves in a same graph
0.01
0.008
0.006
0.004
0.002
0
-0.002
0.5
1.5
2.5
4th PECE
-0.004
2nd PECE
-0.006
As we can see, the 4th order algorithm is evidently more accurated then the 2nd order. On the
other hand, the first one requires an extra work for providing 3 starting points.
ODE Predictor-Corrector 4
= ODE_PC4(Equations, VarInit, Step, [Par, ])
This function integrates numerically an ordinary differential equation of 1st order or differential
system of 1st order, with the 4th order P(EC)^2 schema predictor-corrector of AdamsBashforth-Moulton.
The input arguments are identical to the function ODE_RK4
The function can return all the solution points in an array. Before inserting the function, select
as many rows that you want to fill. For example if you select a (p x n+1) array , the function will
return p solution points of a n x n differential system.
Lets see how it works with an example
w' = v w
v(0) = 0
w(0) = 1
(FitzHug-Naguno model)
Insert the equations in the cell A2 and A3. Insert the starting point [t0, v0, w0 ] = [0, 0, -1] in the
range A7:C7
Select the range A8:C167 in order to get simultaneously 160 integration points and insert the
function ODE_PC4 by the CTRL+SHIFT+ENTER sequence.
221
Xnumbers Tutorial
The following plot shows the obtained functions v(t) and w(t) for 0 <= t <= 8
Starting
x0, y0 , h
yp
fp
Starting points
x0, y0
x1, y1
x2, y2
x3, y3
yc
Evaluate the function
fc = f (x4, yc)
P (EC)2
Predictor-Corrector
schema of 4th order
right-shift the
points and repeat
x1, y1
x2, y2
x3, y3
x4, y4
fc
Refine the step by the
4th order Corrector
y4
The initial extra 3 steps, necessary for starting the predictor-corrector algorithm, are calculated
by the function ODE_RK4 requiring 4 function evaluations for step. After that, the PC schema
require only 2 function evaluations for step. Conventionally we measure the effort (EF) counting
the number of function evaluation for n steps.
EF = 12+2*n (for PC schema),
For n >> 1 the effort reduction of the P(EC)2 schema is about 50%
222
Xnumbers Tutorial
yn +1 = yn + h f (t n , yn )
yn +1 = yn + h / 2 ( f (t n , yn ) + f (t n +1 , yn +1 ) )
The second non-linear equation is started with the predicted value and then solved respect to
the variable yn+1 till the convergence.
This algorithm, despite its low order, exibits a large stability and, thus, it is suitable for solving
"stiff" problems
Lets see how it works with an example
Solve numerically the following 2nd order Cauchys problem for 1 x 7 and k = 100
d2y
dy
+ (k + 1) + k y = 0
2
dx
dx
First of all, we transform the problem in a 1st order differential equations system taking
y1 = y , y2 = y '
y1 ' = y2
y2 ' = k y1 (k + 1) y2
y1 (1) = 1
y2 (1) = 0.5
The scatter plot of the 30 points (x, y1) is shown in the following graph
223
Xnumbers Tutorial
Compare the approximate solution (dotted line) with the exact one (pink continue line)
The fitting, even with only 30 points, looks good. If we try to solve this problem with the 4th order
Runge-Kutta algorithm we have to choose a step less then 0.025 for avoiding the instability
and, thus, we need more than 250 points for reaching the same integration interval.
dx
dt = a1 x a2 x y
dy = a y + a x y
3
4
dt
is called the Lockta-Volterra model or also "prey-predator" model. It is very useful in biology,
chemistry and many other fields. The numerical integration of this ODE family requires a stable
algorithm otherwise the result are not acceptable
The function x(t) and y(t), depending from the time, may represent different things. In a
biological models, for example, they simulate respectively the population of pray (rabbits) and
predator (foxes) at time t. The proportionality constants a1 , a2 , a3 , and a4 are positive. It is
known that its solution leads to oscillate steady-state.
. Let's see with a practical example
x' = 2 x 2 xy
y ' = 5 x + 2 xy
x(0) = 1
y (0) = 1
Insert the equation defintion in the cells
A1 and A2 , the step in the cell C2 = 0.02
and the starting values [0, 1, 1] in the
range A6:C6
Do not miss the labels "t", "x", "y"
Then, select the range A7:C407 and
insert the function ODE_PC2I with the
ctrl-shift-enter keys sequence
The following graph at the left shows the result of the function x(t) and y(t). By performing the
scatter plot of x-y variable we have the steady-state plot at the right. It shows a closed loop, a
limit cycle.
224
Xnumbers Tutorial
6
5
4
1
0
0
10
12
We can easily change the zoom of the graph by changing the integration step h
Note that the oscillations are quite deep. The above system has two equilibrium points where
dx/dt = 0 and dy/dt = 0 simultaneously, that can be found solving the algebric system
2 x 2 xy = 0
5 x + 2 xy = 0
x = 0
y = 0
x = 2.5
y =1
The non trivial solutions means that if the initial populations start from x0 = 2.5 and y0 = 1, then
there will be no oscillation and the population fraction x/y will be always constant in the time.
On the contrary, the populations become progressively to oscillate when the initial populations
are different from the equilibrium point [2.5 , 1].
Here same examples:
x(0) = 2.45 and y(0) = 1
2.5
2.5
1.5
1.5
0.5
0.5
0
0
10
12
225
10
12
Xnumbers Tutorial
Differential Systems
OD Linear System
= ODE_SYSL(A, y0, step, [b]))
This function integrates numerically a system of ordinary linear differential equations of 1st
order with constant coefficients, starting from an initial value. For example, the general form of
a 3x3 linear differential system is:
y ' = [ A] y + b
where
a11
A = a21
a31
a12
a22
a32
y = [ y1 , y2 , y3 ]
a13
a23
a33
b = [b1 , b2 , b3 ]
(0)
(0)
y0 = y1 , y2 , y3
(0) T
y ' = [ A] y
where
20 10 19
6
16
A = 16
2 2
1
y 0 = [1 , 0 , 0]
226
Xnumbers Tutorial
All the 240 cells will be filled with the nodal solutions of y1, y2, y3.
The scale can be esily arranged simply by changing the parameter h
1.5
1.5
0.5
0.5
y1
y2
y3
0
y1
-0.5
-0.5
y2
y3
-1
-1
0
0.5
1.5
2.5
3.5
h = 0.05
0.25
0.5
0.75
h = 0.012
y1 = 2e x + e 2 x + 2e 10 x
2 x
10 x
y2 = 2e 2e
x
2 x
y3 = 2e + 2e
y1 ' 0
y ' 0
2
L = K
y n 1 ' 0
y n ' a 0
1
0
0
1
K
0
K
0
a1
a2
0 y1 0
0 y 2 0
O
K L + L
1 y n 1 0
M
M a n 1 y n b
M
M
y 0 = [ y1 (0) , y 2 (0) , y 3 (0) , y n (0) ] = y (0) , y ' (0) , y ' ' (0) , y n 1 (0)
T
227
Xnumbers Tutorial
For example assume tha you have to calculate the solution of following IVP problem:
y ' ' '+5 y ' '+9 y '+5 y = 0 , with y (0) = 2 , y ' (0) = 3 , y ' ' (0) = 4
Introducing the axiliary variables y1 = y , y2 = y' , y3 = y'' , we get the following equivalent
differential system
1
0 y1
y1 ' 0
y
y ' = 0
0
1
2
2
y3 ' 5 9 5 y3
y1 (0) = 2
y2 (0) = 3
y (0) = 4
3
with
Observe that the last row of the matrix contains the coefficients of the given ODE with the
opposite sign; besides of that, it has only all "1" in the upper subdiagonal.
Insert the initial values in the first row (range B10:D10). The column "x" was added only for
clarity but it is not indispensable at all.Select the range B11:D40, where you want to otput the
results and insert the function ODE_SYSL giving the suitable parameters: A, y0, h.
Then press CTRL+SHIFT+ENTER
The selected area will be filled with the numerical solution of the given system
2.5
2
y1
Exact
1.5
1
0.5
0
0
Observe that the solution y1(x) is also the solution y(x) of the given ODE. Compare with the
exact solution
y ( x) = e x + e 2 x cos x
Of course the above differential system can be also solved with other methods.
In order to show the accuracy of the
exponential method we put in a graph the
average relative error
e(x) = |yi - y(xi)| / | y(xi)| ,
obtained in the same condition, with 3
different methods: Exponential, Euler,
and Runge-Kutta 4.
The graph is eloquent. The error of the
Exponetial method is several times more
accurate then the others
100
1
0.01
0.0001
Euler
1E-06
RK 4
1E-08
Expo
1E-10
1E-12
1E-14
1E-16
0
Clearly it takes advantages using dedicated methods for linear differential equations.
Another important feature of the exponential method is its high stability
Let' s try the following test stiff system
y1 ' = y2
y2 = 20 y1 21 y2
y1 (0.4) = 0.6706555
y2 (0.4) = 0.6770293
228
Xnumbers Tutorial
The exact solution is
y1 = e x + e 20 x
y2 = e x 20e 20 x
In the following graph we shows the numerical result obtained with three different integration
methods, Exponential, Runge Kutta of 4th order and Euler, using different integration steps
The Expo method reaches the integration length of about x = 19 with a step h = 0.4
1
0.8
Expo method
h = 0.42
0.6
0.4
0.2
0
-0.2 0
10
15
20
-0.4
-0.6
-0.8
-1
The Runge-Kutta method, using a step h = 0.14 gives accurate only for x < 3; after that the
solution begins to diverge.
1
0.8
Runge Kutta 4
h = 0.14
0.6
0.4
0.2
0
-0.2 0
10
15
20
-0.4
-0.6
-0.8
-1
The Euler method, with a step h = 0.11, begins to oscillate even from the first steps. At this step
the Euler method is completely unstable.
1
0.8
Euler method
h = 0.11
0.6
0.4
0.2
0
-0.2 0
10
15
20
-0.4
-0.6
-0.8
-1
As we can see the stability step of the Exponential method is here about 3 times greater than
the others methods.
229
Xnumbers Tutorial
y ( x) =
f ( x)dx
y ' ( x) = f ( x)
x0
y ( x0 ) = 0
As we can see, the computing of any integral function is equivalent of solving an ODE.
Example. Plot the integral function of f ( x ) = x e
1.2
1
0.8
0.6
f(x)
0.4
f(x)
0.2
0
0
230
Xnumbers Tutorial
Example. Solve the following linear differential equation of 3rd order.
y ' ' '+5 y ' '+33 y '+29 y = 0 with y (0) = 2 , y ' (0) = 3 , y ' ' (0) = 20
This linear equation with constant terms can be transformed into the equivalent differential
system:
1
0 y1
y1 ' 0
y ' = 0
0
1 y2
2
y3 ' 29 33 5 y3
with
y1 (0) = 2
y 2 ( 0) = 3
y (0) = 20
3
y = e x + e 2 x cos(5 x)
The following graph shows the exact solutions (continue lines) compared with the calculated
solutions (dotted lines). We note a global good fitting.
5
4
3
2
1
0
-1
y1
-2
y2
-3
y3
-4
-5
0
0.5
1.5
231
2.5
Xnumbers Tutorial
y ' = f ( x, y ) , y ( x0 ) = y0
x0 x xmax
y ' = f ( x, y ) , y ( x0 ) = y 0
x0 x xmax
where y = y1 , y2 ... yn
]T
The macro works with equation definited by worksheet formulas (on site) or even with equation
definited by symbolic string. The macro implements a control of the local error and changes the
integration step consequently Therefore the precision can be set independently from the
tabulating step. The independence of the integration step from the tabulation step is the main
feature of this macro.
The macro implement a predefined simple input schema. Let's see how to use it with a simple
example
Example 2. Find a numerical solution of this simple differential system
y1 ' = y 2
y 2 ' = 4 y1 5 y 2
with
y1 (0) = 0
y 2 ( 0) = 2
and with 0 x 5
Arrange the worksheet reserving two columns for [y1 , y2 ] and the two adjacent columns for the
derivatives [y1', y2']. In the first column set a x-grid with 50 step of increment x = 0.1.
Then select the area A4:E55 and start the macro ODE Solver.
Differential Equations links to the cells where are the equation formulas: = C5, = (4*B5+5*C5) .
Variables are the cells (x, y1, y2) referenced by the formulas; in that case A4:C5
Starting values indicate the starting cells of the table (they may or not may coincide with the
variables cells).
If we have followed the above schema, the input fields are correctly filled.
We have only to set the required precision: Err. Max = 1E-6
Optionally, if we want the macro to fill also the derivative columns, activate the check box
Press "Run" to start the RKF integration algorithm. After few seconds and about 1400 function
evaluations, the macro output its result. Each solution node has a relative error less then 1E-6.
Compare it with the exact solution
232
Xnumbers Tutorial
y1 = e x e 4 x
y2 = e x + 4e 4 x
The following graphs shows the exact solution (pink line) and the calculated solution (dotted
line)
Solution y1(x)
Solution y2(x)
Note the general good fitting. It is a remarkable result overall if we consider the relative few
points in the initial range where both functions have high swinging.
For further details see " ODE tutorial" by Foxes Team, 2006
y '+ y = e x
y ' = xe x y
y in a
Select the range I4:K4 and start the macro ODE Slope Field
Option Tab
233
Xnumbers Tutorial
In the Axes tab we can set the domain D. Click the "Draw" button to generate the plot
The macro generates a graphical object
showing the slope y' of each point of the
grid.
Every solution y(x) of the differential
equation follows the direction of the slope
field. Therefore the field gives a global
view of the solutions crossing the given
domain.
For example, the solution crossing the
x
y ' = 2 xy
y' = x 1 y 2
234
Xnumbers Tutorial
Nonlinear Equations
Bisection
=Zero_bisec(a, b, func, [step], [param])
Approximates the zero of a monovariable function f(x) with the bisection method
f ( x) = 0
This function needs two starting points [a, b] bracketing the zero.
Parameter "func" is a math expression string containing the symbolic function f(x)
Examples of correct function definitions are:
-2*ln(x)
2*cos(x)-x
3*x^2-10*exp(-4*x) , etc.
The optional parameter "step" sets the maximum number of steps allowed. If omitted the
function iterates still the convergence. Step = 1 is useful to study the method step-by-step
Param contains labels and values for parameters substitution (if there are)
At the first step, the function returns a new segment
[ a1, b1] where a1 < x0 < b1
At the second step, the function return a new segment
[ a2, b2] where
After several iterations, the interval [an , bn ], with n>>1, will be very closed to the value x0
Example: Find the approximated zero of the following equation and show the first steps of the
bisection method.
3 log10 ( x) +
2
log10 ( x)
5 = 0
235
Xnumbers Tutorial
We can also solve this equation step-by-step in order to investigate how this algorithm works
As we can see, the convergence is quite low but very robust because the zero always remains
bracketed between the interval limits [a, b]. The error estimation is also very quick. Simply
taking the difference |b-a|
Secant
=Zero_sec(a, b, func, [step], [param], [DgtMax])
Approximates the zero of a monovariable function f(x) with the secant method
f ( x) = 0
This function needs two starting points [a, b] bracketing the zero.
This version accepts also a worksheet function.
The parameter "Func" is a math string containing the symbolic function f(x) or a range of two
adjacent cells containing the worksheet functions [ f(a) , f(b) ] (see example).
Examples of correct symbolic function definitions are:
-2*ln(x)
2*cos(x)-x
3*x^2-10*exp(-4*x) , etc.
The optional parameter "Step" sets the maximum number of iterations. If omitted, the function
iterates still the convergence. Step = 1 is useful for investigation about the algorithm.
"Param" contains labels and values for parameters substitution (if there are)
Both parameters "step" and "param" are ignored if funct is not a symbolic function.
The optional parameter "DgtMax" set the number of the precision digits. If omitted, the function
works in the faster double precision.
At the first step, the function returns a new segment
[ a1, b1] where a1 < x0 < b1
At the second step, the function return a new segment
[ a2, b2] where
After several iterations, the interval [an , bn ], with n>>1, will be very closed to the value x0
Use the CTRL+SHIFT+ENTER sequence to paste this function
Example: Find the approximated zero of the following equation and show the first steps of the
secant method.
236
Xnumbers Tutorial
exp(-6*x*Ln(2))-sin(pi*x)
1.5
1
0.5
0
-0.5
0.2
0.4
0.6
0.8
-1
Lets see now the iteration trace setting the parameter step = 1
As we can see this convergence is much faster than the one of the bisection method. On the
other hand, it is no guaranteed that the zero always remains bracketed into the interval.
237
Xnumbers Tutorial
Insert in A3:B3 the array function zero_sec(a, b, func) using the sequence Ctrl+Shift+Enter
In this case, none parameter is necessary because the function always returns one step of the
secant algorithm.
Now insert the functions in the range C3:D3 by simply dragging-down the range C2:D2
Insert the function =ABS(A3-B3) in E3. This is not necessary but it is usefull for checking the
convergence. Now, let's select the last row A3:E3 and drag it down until the convergence
shows the minimal error
We can compute this result also in multiprecision. In this case we have use, of course, the
equivalent
x-functions; in cell D2 = xsub(A4, xcos(A4)), E2 = xsub(B4, xcos(B4)) and in cell E3 =
ABS(xsub(A5, B5)).
In the range A3:B3 insert the array function {Zero_sec(A4, B4, C4:D4, , , 30)}.
The parameter DgtMax = 30 switches the function in multiprecision mode
Following the other steps we get the result below
238
Xnumbers Tutorial
Derivatives
First Derivative
=Diff1(x, func, [lim], [param])
Approximates the first derivative of an univariate function f(x) at the given point x
f ' ( x) =
d
f ( x)
dx
The parameter func is a math expression string containing the symbolic function f(x)
Examples of function definition are:
-2*Ln(x) ,
2*cos(x) ,
The optional parameter lim (default = 0) sets the way how the limit approach to x. If lim = 1, it
approaches from the right; if lim = -1, it approaches from the left;
if lim = 0 , it approaches centrally. That is, it returns the following derivatives
lim f ( x) = f ' ( x )
h0
f ( x) = f ' ( x + )
hlim
0+
"Param" contains labels and values for parameters substitution (if there are)
This function uses the following formulas to approximate each derivative
f '(x )
1
(25 f ( x) 48 f ( x h) + 36 f ( x 2h) 16 f ( x 3h) + 3 f ( x 4h) )
12h
1
( f ( x 2 h) 8 f ( x h) + 8 f ( x + h ) f ( x + 2 h) )
12 h
1
(25 f ( x) 48 f ( x + h) + 36 f ( x + 2h) 16 f ( x + 3h) + 3 f ( x + 4h) )
f ' (x+ )
12h
f ' ( x)
Example. Evaluate numerically the left, right and central derivatives of the given function at the
point x = 0, and check if the given function is differentiable in that point
f ( x) =
x
x + | x | +1
2
239
Xnumbers Tutorial
Second Derivative
=Diff2(x, func, [param])
It approximates the second derivative of an univariate function f(x) at the given point
f ' ' ( x) =
d2
f ( x)
dx 2
The parameter "func" is a math expression string containing the symbolic function f(x)
Examples of function definition are:
-2*Ln(x) ,
2*cos(x) ,
"param" contains labels and values for parameters substitution (if there are)
Example: Evaluate the first and second
derivatives at the point x = 2 for the
following function
f ( x) =
x+3
x2 +1
Gradient
=Grad(p, func, [param])
Approximates the gradient of a multivariate function f(x, y, z) at the given point
f f f
f ( x , y , z ) =
,
,
x y z
The parameter "p" is the vector of the variables [x, y, z]
The parameter "func" is an expression string containing the function f(x, y, z). Examples of
function definition are:
-2*ln(x+3y), 2*exp(-x)*cos(3*t), 3*x^2-y^2+z^2, (x^2+y^2)^(1/3),etc.
For performance problem, the number of variables is restricted to 4, x, y, z, t. The
variables values must be always passed in this order.
"param" contains labels and values for parameters substitution (if there are)
Example. Evaluate the gradient of
the following function at the point
P(1, 1)
f ( x, y ) =
1
x + 5y2
2
240
Xnumbers Tutorial
Jacobian matrix
=Jacobian (p, func, [param])
Approximates the Jacobians matrix of a multivariate vector-function F(x, y, z) at the given point
(x, y, z)
f1 ( x, y, z )
F ( x, y, z ) = f 2 ( x, y, z )
f 3 ( x, y, z )
f1 f1 f1
x , y , z
f 2 f 2 f 2
,
,
J ( x, y , z ) =
y
z
x
f 3 f 3 f 3
,
,
y
z
x
f1 ( x, y, z ) =
1
x2 + 5 y2 + z 2
f 2 ( x, y, z ) = z ln( x + 2 y )
f 3 ( x, y, z ) = 4 xyz
Hessian matrix
=Hessian (p, func, [param])
Approximates the Hessian matrix of a multivariate function f(x, y) at the given point p(x, y)
2 f
2 f
,
2
x
xy
H ( x, y ) = 2
f
2 f
,
2
yx y
The parameter "p" is the vector of the variables [x, y]
The parameter "Func" is an expression string containing the function f(x, y, z). Examples of
function definition are:
-2*ln(x+3y), 2*exp(-x)*cos(3*t), 3*x^2-y^2+z^2, (x^2+y^2)^(1/3), etc.
241
Xnumbers Tutorial
For performance problem, the number of variables is restricted to 4, x, y, z, t. The
variables values must be always passed in this order.
"Param" contains labels and values for parameters substitution (if there are)
This function returns a square a matrix (n x n) of the second derivatives
The accuracy of this function is about 1E-10
Example. Approx. the Hessians matrix of the following function at the point (2,1,1)
f ( x, y , z ) =
1
x + 5y2 + z2
2
Parameters. All the differential functions accept parameters into the string definition. They
must be different from the canonical variables "x", "y", "z", "t" but apart this, can have any name
that you like.
Example: Calculate the Hessian matrix of the function
f ( x, y , z ) =
kz
x + y2 + a
2
Note the "param" range G2:H3: the parameters must be always passed with theirs labels "k"
and "a". On the contrary the variables do not need labels but must always be passed in the
order x, y, z.
Using the trick of the scaling for 243, the inverse of the determinant, we get an integer matrix,
that represent the numerator of the Hessian itself. Then, simplifying each element for 243, we
obtain the Hessian matrix in the following exact fractional form
242
Xnumbers Tutorial
f ( x) = x 2 sin x
and draw its plot. The point x where f ( x) = 0 is
the solution of the given equation We see that the
zero exists and it is near the point 1.
We note also that in the interval [0.5 1.5] the
function is monotonic
In this interval the Newton-Raphson iterative algorithm, starting from x = 1.5, should work fine.
xn +1 = xn
f ( xn )
f ' ( xn )
n = 0, 1, 2 ...
To implement this algorithm we need the evaluation function f(x) with about 30 significant digits.
For that, it comes in handy the multiprecision function xeval. For the derivative we have to way:
computing the function f'(x) by hand and evaluating it by xeval or approximating the derivative
by the function diff1 in standard precision. Because we are a bit lazy and the derivatives is not
so immediate, we chose the second way. A simple spreadsheet arrangement may be the
following
As we can see the convergence is superb!. After few iteration the solution is
x 0.9496166887146629471509830317 with |f(x)| < 1e-28
This excellent result has been obtained in spite of the limited precision (1e-13) of the derivative.
The reason is simple: the accuracy of the derivative does not influence the final accuracy of the
root. We note that the derivative, after very few iterations, remains constant: we might
substitute this value with an even more approximated values, i.e. f' = 1.57, for all iterations. The
final accuracy will not change. We will need only more few steps, at the most.
243
Xnumbers Tutorial
But this method show its power overall for non-linear systems. For a 2 variables problem the
Newton-Raphson method becomes
f ( x, y ) = 0
g ( x, y ) = 0
fx
x
x
=
y n +1 y n +1 g x
fy
g y
f
g n
The (2 x 2) matrix is the Jacobian calculated at the point (xn, yn). In Xnumbers it can be
evaluated by the function Jacobian
Example. Solve the following system
x 5 + y 2 x 6 = 0
x y
e + x + y 1 = 0
setting:
f ( x, y ) = x 5 + y 2 x 6
g ( x, y ) = e x y + x + y 1
the contour plots of the functions f = 0 and g = 0 show two
intersection points: one near the point (-1 2) and another
near (-1, -2)
The function f(x,y) and g(x,y) are
evaluated and converted in double
precision by the nested functions
=xcdbl(xeval(B4,B7:B8))
=xcdbl(xeval(B5,B7:B8))
At the begin, insert the starting point
(-1, 2) in the cells B7:B8.
The new point is calculated in the
cells E7:E8. Copy this range and reinsert in the range B7:B8. At each
iteration the increments dx,dy of the
range E10:E11 becomes more and
more small.
Starting from (-1, 2) and (-1, -2) the iteration algorithm converges to the correct solutions
x
-1
-1
-2
-1.0201151219
1.9698273171
-0.7964138633
-2.3053792051
-1.0196483063
1.9693084022
-0.8079928505
-2.2042117521
-1.0196480758
1.9693081215
-0.8107932120
-2.1997452584
-1.0196480758
1.9693081215
-0.8108021826
-2.1997248438
244
Xnumbers Tutorial
Conversions
Decibel
=dBel(A, [MinLevel])
Converts a positive number A into decibel
AdB = 20 log10 ( A)
If zero, A is substituted with the value contained in the parameter "MinLevel" (default 1E-15)
Example
A
A dB
1
0.5
0.1
0.05
0.01
0.001
0.0001
0
0
-6.0206
-20
-26.021
-40
-60
-80
-300
Base conversion
cvDecBin(DecNum)
base 10 base 2
cvBinDec(BinNum)
base 2 base 10
cvDecBase(DecNum, Base)
cvBaseDec(BaseNum, Base)
xBaseChange 2
(base 2)
(base 3)
(base 10)
245
(base 8)
Xnumbers Tutorial
In spite of its digits limitation (15), this function has several interesting features
It converts any number into many different bases (up to 36). The digits greater then 9 are
indicated as A, B, C, D E, F, G, H, etc. It converts also decimal numbers. It formats the result
consistently with the source cell. Let's see how it works
The cell C4 is formatted with 7
digits and consequently its results
have the same format; the cell D4
is formatted with 2 decimals and its
result has the same format.
213.02[4]
The oldnumber is assumed to be base 10; otherwise oldbase is provided between square
brackets [].
xBC_NewBase is the new base. If omitted it is assumed 10 as default.
If the base > 35 the letters are no more sufficients and the digits are represented as group of
digits separate with colon :
9:34:9:23[36]
6:54:122:42:65[200]
xBaseChange("9:34:9:23[36]", 7)
3642455[7]
Example:
Results in:
xBaseChange(1098414 , 16)
10C2AE[16]
246
Xnumbers Tutorial
Example:
Results in:
xBaseChange(1098414 , 46)
11:13:4:26[46]
Example:
Results in:
xBaseChange("1F0C2AE[16]")
32555694[10]
Example
Results in
xBaseChange(10092.102 , 2048 , 6)
4:1900.208:1835:16:786:884:1507...[2048]
Note that, as in the last case, the digits groups can have different lenght: one , two, or more
digits
If we wan to force all the groups having the same number of digits simply insert the new base
with prefix "0"
Example
Results in
xBaseChange(10092.102 , "02048" , 6)
0004:1900.0208:1835:0016:0786:0884:1507...[02048]
if | q | > 1
LRE = 0
if c = 0
LRE = min( log(q ) , NoSD )
| q |< 1
if c 0 LRE = NoSD if c = q
LRE = 0
if else
Example: Assume that you want to compare an approximate value with a 15 digits certified
value of . LRE metric can show this in a easy way
Certified value C = 3.14159265358979
Approx. value Q = 3.14159265300001
mjkLRE(C, Q, 15) = 9.7
This means that two values are close for about 10 significant digits. LRE metric rejects non
significant digits. Look at this example:
Certified value C = 0.000133333333333333
1
These functions appear by courtesy of Michael J. Kozluk. This algorithm was first programmed into an Excel user
function, by Michael, in standard 32 bit precision. As it works fine also for comparing long extended numbers (NoSD>
15), we have now developed its multiprecision version xLRE().
247
Xnumbers Tutorial
Approx. value Q = 0.000133333333333311
mjkLRE(C, Q, 15) = 12.8
The two numbers appear exact up to the 17th digit, but the relative error is about 1E-13
LRE is very useful when you work with long string of extended numbers.
For example, compare this approximation of "e" (Napiers number)
Certified value C = 2.71828182845904523536028747111
Approx. value Q = 2.71828182845904523536028747135
xLRE(C, Q, 30) = 28.1
At the first sight it is hard to say, but the LRE function shows immediately a precision of about
28 digits
248
Xnumbers Tutorial
Special Functions
The computation of special functions is a fundamental aspect of numerical analysis in virtually
all areas of engineering and the physical sciences.
All these special functions have a high-fixed-precision. Because most of these special functions
are in the form of infinite series or infinite integrals, their numeric solutions are quite
complicated, and we have spent many times for selecting and testing many different algorithms
in order to achieve the highest possible accuracy in 32 bit arithmetic.
erf ( x) =
e t dt
et
dt
t
x
Ei ( x) =
Accuracy: about 1E-14 for any x 0
This version1 accept also negative argument
For definition is
Ei ( x) = E1 ( x) x > 0
e xt
En ( x) = n dt
t
1
Accuracy: about 1E-14 for x> 0 and n > 0
249
Xnumbers Tutorial
Euler-Mascheroni Constant
xGm([Digit_Max])
Returns the Euler-Mascheroni gamma constant.
The optional parameter Digit_Max sets the maximum digits (default 30, max 415)
1 1
2 3
1
n
( x) = t x 1 e t dt
0
Optional parameter Prec sets the maximun precision from 15 (default) to 30 digits
When Prec = 15 the routine works in faster double arithmetic.
This routine uses the excellent Lanczos series approximation1
2 x + g + 12
( x) g
e
e
x + 12
N
c
c0 + i
i =1 x + i
where: g = 607/128, ci are the Lanczos' coefficients and 14 < N < 22.
Relative accuracy in double precision is better than 10^-14, (except very near to the poles x =
0, -1. -2, -3, etc.). In extended precision the accuracy is better then 1E-30
xGamma(5.1)
= 27.9317537383684
xGamma(5.1, 30) = 27.9317537383683833586731052773
This function works also with large argument because it uses the multiprecision format to avoid
the overflow for arguments greater than 170.
Example,
x
0.0001
0.001
0.01
0.1
1
10
100
1
xgamma(x)
Rel. Error
9.99942288323162E+3
9.99423772484596E+2
9.94325851191507E+1
9.51350769866874
1
3.6288E+5
9.33262154439441E+155
1.00E-15
1.02E-15
1.00E-15
9.33E-16
0
0
5.64E-16
This high accuracy algorithm has been extracted form a very good note by Paul Godfrey, Intersil , C.2001
250
Xnumbers Tutorial
1,000
10,000
100,000
1,000,000
4.02387260077093E+2564
2.84625968091705E+35655
2.82422940796034E+456568
8.26393168833122E+5565702
1.92E-15
1.58E-15
2.75E-15
2.54E-15
2.84711361574652325360317551421E+35667
30 digits, slower
xgamma(10003) =
2.84711361574651E+35667
15 digits, faster
1051287.7089736568948
xgammalog(100000) =
456568.45089997090835
Gamma quotient
xGammaQ(x1, x2)
Performs the division of two gamma functions.
q = (x1) / (x2)
Relative accuracy is better than 1E-14, for x1 > 0 and x2 > 0
Example: suppose you have to calculate for v =1,000,000 the following quotient
q=
Taking
( v 2+1)
( 2v )
Note that if you have used the standard GAMMALN() function, you should have:
251
Xnumbers Tutorial
EXP(GAMMALEN(500000.5) - GAMMALEN(500000)) = 707.106604681849
(with a rel. error = 3.846E-10)
As we can see, In this case, the error is more than 500,000 times bigger that the previous one!
Gamma F-factor
xGammaF(x1, x2)
Returns the gamma factor of the Fischer distribution.
x +x
1 2
2
k=
x x
1 2
2 2
Relative accuracy is better than 1E-14, for x1 > 0 and x2 > 0
Digamma function
digamma(x)
Returns the logarithmic derivative of the gamma function
( x) =
d
' ( x)
ln(( x) ) =
dx
( x)
value
rel. error
-100.560885457869
-10.4237549404111
-0.577215664901532
2.25175258906672
4.60016185273809
6.90725519564881
3.24E-15
2.23E-15
1.49E-15
4.92E-16
5.65E-16
2.97E-16
Beta function
xBeta(a, b)
Returns the beta function
1
B(a, b) = t a 1 (1 t )b 1 dt
0
252
Xnumbers Tutorial
Sel =2
Sel = 3
(a, x) = t a 1e t dt
(a, x) = t a 1 e t dt
P ( a, x ) =
Sel = 4 (Tricomi)
( a, x )
* ( a, x ) =
(a )
( a, x )
x a (a )
Sel = 2
Bx (a, b) = t a 1 (1 t )b 1 dt
I x ( a , b) =
Bx ( a , b )
B ( a, b )
Combinations function
xcomb_big(n, k)
Returns the combination, or binomial coefficients, for large integer numbers
n
n!
Cn, k = =
k
(
n
k )!n!
Relative accuracy is better than 1E-14, for n >> 0 and k >> 0
This function uses the gamma function to calculate the factorials. It is much faster than xcomb
function. For this reason is adapted for large integer values (10,000 - 1,000,000)
xcomb(5000,2493) =
1.5627920156854189438574778889E+1503
xcomb_big(5000,2493) =
1.56279201568542E+1503
253
Xnumbers Tutorial
Relative accuracy is better than 1E-13, for x > 0 and n any integer
These routines1 have a high general accuracy. Look at the following example. We have
compared results obtained from our BesselJ with the standard Excel similar function
x
0.1
0.5
1
5
10
50
J0(x) (BesselJ)
Rel. Error
0.997501562066040
0.938469807240813
0.765197686557967
-0.177596771314338
-0.245935764451374
0.055812327669252
1.11E-16
1.06E-15
7.25E-16
2.66E-15
1.06E-13
3.98E-15
Rel. Error
2.71E-09
1.95E-10
3.66E-09
1.58E-08
2.72E-10
1.26E-09
ci( x ) =
x
cos(t )
dt
t
si( x) =
0
sin(t )
dt
t
All these special functions are provided thanks to the FORTRAN 77 Routines Library for Computation of Special
Functions developed by Shanjie Zhang and Jianming Jin . The programs and subroutines contained in this library are
copyrighted. However, authors kindly gave permission to the user to incorporate any of these routines into his
programs.
254
Xnumbers Tutorial
S ( x ) = sin ( 12 t 2 ) dt
0
k sin (t 2 ) dt = S (k z )
where:
k=
C ( x) = cos( 12 t 2 ) dt
0
k cos(t 2 )dt = C (k z )
where:
k=
Fibonacci numbers
xFib(n, [DgtMax])
Returns the Fibonacci's numbers defined by the following recurrent formula:
F1 = 1 , F2 = 2 ,
Fn = Fn 1 + Fn 2
Example:
xFib(136)
= 11825896447871834976429068427
xFib(4000) = 3.99094734350044227920812480949E+835
255
Xnumbers Tutorial
Hypergeometric function
Hypgeom(a, b, c, x)
Returns the Hypergeometric function
The parameter "a" is real, "b" is real, "c" is real and different form 0, -1, -2, -3 ...
The variable "x" is real with |x| < 1
Relative accuracy is better than 1E-14, for -1 < x < 1
The hypergeometric function is the solution of the so called Gaussian-hypergeometric
differential equation
x(1 x ) y + (c (a + b + 1)x ) y + ab y = 0
An integral form of the hypergeometric function is
1
F (a, b, c.x) =
(c)
c b 1
(1 t x )a dt
t b1 (1 t )
(b)(c b) 0
More known is the series expansion that converges for !x| < 1
F (a, b, c.x) = 1 +
F ( p,1,1, x) = (1 x) p
ln(1 + x)
x
F (1,1,2, x) =
F ( 13 , 23 , 56 , 27
32 ) = 1.6
(s) =
k =1
1
ks
Analytic continuation. It can be defined for 0< s <1 by the following analytic continuation:
1
(s) =
1 21 s
k =1
(1) k 1
ks
(1 s ) = 2(2 ) s cos( 12 s ) ( s) ( s)
256
Xnumbers Tutorial
Same known exact results are: (2) = (2) /6 , (4) = (4)/90
Zeta function is very useful in computing series. Look at this example:
k =0
1
1
1
1
5
=
=
1 2 = ( 2)
2
2
2
( k + 2)
2
4
k =2 k
k =1 k
Airy functions
= AiryA(x)
= AiryB(x)
= AiryAD(x)
= AiryBD(x)
Return the Airy functions A(x), B(x) and theirs derivatives A'(x), B'(x)
A(x) =
B(x) =
1
32 / 3
1
31 / 6
n=0
n=0
n!
3
( 13 (n + 1)) 1 / 3 n 2( n + 1)
3 x sin
n!
3
Elliptic Integrals
= IElliptic1(, k)
= IElliptic2(, k)
Return the Jacobian Elliptic Integrals of 1st and 2nd kind
IElliptic1 =
F ( , k ) =
0
d
1 k 2 sin 2
IElliptic2 =
E ( , k ) = 1 k 2 sin 2 d
0
257
Xnumbers Tutorial
d 2w
dw
+ (b a )
aw = 0
2
dz
dz
(b)
M ( a , b, z ) =
e zt t a 1 (1 t ) b a 1 dt
(b a )(b) 0
1
U ( a , b, z ) =
e zt t a 1 (1 + t ) b a 1 dt
(a ) 0
a
0.5
0.2
M(a,b,z)
0.5
0.2
601.287114305
0.40255172241
0.5
0.2
10
112016.644576
0.29849708947
0.5
0.2
20
3063046479.13
0.21689337800
0.5
0.2
30
7.6396125E+13
0.17882728338
8.2
1.4
41.1797940694
1.39280467E-06
-0.9
0.4
10
-345.535973205
7.72952303674
5.85803416181
U(a,b,z)
0.70928623024
258
Xnumbers Tutorial
CPI ( x, n) = (cos t ) n dt
SPI ( x, n) = (sin t ) n dt
1.4
1.2
CPI(x)
SPI(x)
1.5
n=8
1
0.5
0.8
0.6
0.4
-0.5
0.2
-1
-1.5
-0.2
0.5
1.5
2.5
3.5
n= 8
CPI(x)
SPI(x)
-2
-6
-4
-2
sin x(cos x ) n 1 n 1
+
CPI ( x, n 2) ,
n
n
SPI ( x, n) =
CPI ( x, n) =
The recursive formula of CPI(x, n) is very stable and accurate for all values x 0 , n 0, n N
On the contrary, the recursive formula of SPI(x, n) degrades precision for small value of x
In that case, the function automatically switches on the power expansion series
x
(sin t )
0
ak
1
dt = y n +1
y 2k
+
n + 1 k =1 2k + n + 1
where
k
2i 1 1 3 5...( 2k 1)
ak =
=
2 4 6...( 2k )
i =1 2i
259
y = sin x
x <1
Xnumbers Tutorial
jn ( x ) =
yn ( x) =
2x
2x
J n + 1 ( x)
Yn + 1 ( x)
The Spherical Bessel functions are the solutions of the Helmholtz radial equation in spherical
coordinates
x2
d2y
dy
+ 2 x + ( x 2 n 2 n) y = 0
2
dx
dx
yn(x)
n
x
jn(x)
-------------------------------------------------------------------------------0
1
2
0.5
1
3
0.958851077208406
0.301168678939757
0.298637497075734
-1.755165123780750
-1.381773290676040
-0.267038335264499
260
Xnumbers Tutorial
Formulas Evaluation
Multiprecision Expression Evaluation
These functions realize a little math shell, putting together the power of multiprecision numeric
computation with the ease of symbolic calculus. Sometime we may want to perform the
computation using symbolic formulas. We would pass these strings to a routine for evaluation,
returning the numerical results with a given accuracy. These functions perform this useful task.
The optional parameter "Var" is an array containing one or more value for variables
substitution. Before computing, the parser substitutes each symbolic variable with its
correspondent value. It can be a single value, an array of values or, even an array of values +
labels (see examples).
The optional parameter "Var1", "Var2"... are single values or array as "Var" but without labels,
because the function xevall automatic finds by itself the appropriate labels. (See example)
The optional parameter "DgtMax" from 1 to 200 - sets the maximum number of precision
digits (default=30). Setting DgtMax = 0 will force the function to evaluate in faster standard
precision.
The optional parameter "Angle" sets the angle unit "RAD (default) DEG, GRAD.of for
trigonometric computation:
Example:
xeval("(1+sqr(2))/2+5^(1/3))") = 2.91708272786324451375395323463
xeval("(1+cos(x))/2+x^y" , {5, 1.2}) = 7.5404794000376872941836369067
xeval("(a+b)*(a-b)", {2, 3})= (2+3)*(2-3) = -5
All the function parameters can also be passed by cell references, like A1, $B$2, etc.
Example. Tabulate the following function for x = 1, 1.5, 2, with 30 significant digits
f ( x) =
1+ x
1+ x2
The algorithm is divided into two steps: parsing and evaluation. The first step is performed by the MathParser class.
The evaluation is performed with the x-functions of XNUMBERS.
261
Xnumbers Tutorial
Note how the use of this function is simple and straight comparing with the correspondent
nested formulas
=xdiv(xadd(1,A6),xsqr(xadd(1,xpow(A6,2))))
Calculating functions with more than one variable a bit complication arises, because we have to
pay attention which values are assigned to the variables. Lets see this example
Calculate the following bivariate function for x = 2.4, y = 5.5
f ( x, y ) =
ln( y ) + xy
1+ x2
In order to pass to the parameter "Var" the correct value for each variable we select the
variables range B2:C3 including the labels "x" and "y" (header). The labels must contain the
same symbols contained into the formula string
Note. If we pass the range B3:C3 without labels, the function assigns the values to the
variables in the same order that they appear in the formula, from left to right. In our example
the first variables is y and the second is x, so the function assignes the first value 2.4 to y
and the second value 5.5 to x
To by-pass the variable order rule, the function uses the trick of the variables labels. On the
contrary, for one or none variable it is impossible to make confusion so the header can be
omitted.
Variables order. The function returns the variables order in the Excel function insertion panel
In our example we see the string y x , that means you have to pass the first value for the
variable y and the second value for the variables x
262
Xnumbers Tutorial
The variables order is by-passed by labels. Using labels you do not need to worry about the
variables order
Lets see another example. Calculat,e with 30 digits precision, the following function
f ( x, a, b) = a sin( x) b cos(2 x)
for x = 30 deg , a = 1 , b = -2
f (t ) = a cos( t ) + b cos( t )
where a = 0.5 and b = -2
The above sheet shows a possible arrangement. If we look the last cell B8 we discover that the
parameters are:
Var1 the cell A8 containing the value of the independent variable t
Var2 the range C4:D4, containing the values of the parameters a and b
Var3 range C7:D7, containing the internal parameter DgtMax and AngleSet
The internal parameters DgtMax and AngleSet are reserved word and must write as is.
Note also that the cell A8 has no label, but the function performs the correct assignment to the
t variable.
263
Xnumbers Tutorial
Label Rules. Labels must stay always at the
top or at the left of the corresponding values.
Labels can have any alphanumeric name
starting with any letter and not containing any
blank.
In the example:
t = 0.1, a = 0.5 , DgtMax = 30
The function xevall only assigns the cell value to the variable on top to the correspondent
column. Othewise it assigns the value to the variable on the left to the correspondent row.
264
Xnumbers Tutorial
(1+i)*ln(1+3i) ,
((x+3i)/(x+4-2i))^(1-i)
The optional parameter "Var1", "Var2",... can be single or complex value. See How to insert a
complex number for better details
Example: Evaluate the given complex polynomial for z = 2 i
z 2 + (3 + i ) z + (2 + 5i )
Note that we use the complex rectangular format, i.e. "3+2j", only in the symbolic math
formula.
When we pass a complex value to a variable
we must always use the double cell format.
Note also that we can write i or j as well for
imaginary symbol, the parser can recognize
both of them.
For complex numbers labels are not supported. When we have formulas with two or more
variables, we must provide the values for variable substitutions in the exact order that they
appear in the formula, starting from left to right. The formula wizard will easily help you. Look at
this example.
Example. Compute the expression for the given complexes values
e ks
F ( s) =
( s a )( s b)
In the cell B2 we have inserted the string
s = 1 + j , a = 1 4j , b = 3 + 6j ,
k = 0.5
exp(k*s)/((s-a)(s-b)
265
Xnumbers Tutorial
ATANH
Nota. The functions are indicated with their original English names, that usually are different from the local names.
Let's see how it works. Assume to have in a cell the following Excel formula
=(A2*EXP(B2)+A4*EXP(B4))/(A2^2+A4^2)
Note that the formula references the values of other 4 cells: A2, B2, A4, B4
The formula value, calculated in standard precision, is 0.0140820785524786
We can get the value in 30 significant digits applying the xCalc function
=xCalc( (A2*EXP(B2)+A4*EXP(B4))/(A2^2+A4^2) )
For that, simply, select the cell D2 and move the mouse to the input field; insert xCalc( ... ) just
around the original formula.
266
Xnumbers Tutorial
Note that, using the x-function, the above formula should be translated as
=xdiv(xadd(xmult(A2,xexp(B2)),xmult(A4,xexp(B4))),xadd(xpow(A2,"2"),xpow(A4,"2")))
The result is equivalent but it is evident the great advantage to keep the original formula.
267
Xnumbers Tutorial
sqr(2)+asin(x)
(a+b)*(a-b)
x^2+3*x+1
1.5*exp(-t/12)*cos(pi*t + pi/4)
(1+(2-5)*3+8/(5+3)^2)/sqr(5^2+3^2)
2+3x+2x^2
0.25x + 3.5y + 1
sqr(4^2+3^2)
1/(1+e# ) + Root(x,6)
(-1)^(2n+1)*x^n/n!
|x-2|+|x-5|
And((x<2),(x<=5))
sin(2*pi*x)+cos(2*pi*x)
Variables can be any alphanumeric string and must start with a letter
x, y, a1, a2, time, alpha , beta
Also the symbol "_" is accepted to build variable names in "programming style".
time_1, alpha_b1 , rise_time
Capitals are accepted but ignored. Names such as "Alpha", "alpha", "ALPHA" indicate the
same variable.
Implicit multiplication is not supported because of its intrinsical ambiguity. So "xy" stands for
variable named "xy" and not for x*y. The multiplication symbol "*" generally cannot be omitted.
It can be omitted only for coefficients of the classic math variables x, y, z. It means that string
like 2x and 2*x are equivalent
-3234
1.3333
-0.00025
1.2345E-12
Note: This version support also the comma "," as decimal separator, depending on your system
internation option setting.
1,3333
-0,00025
1,2345E-12
x+2y >= 4
x^2+5x-1>0
t<>0
(0<x<1)
Logical expressions return always 1 (True) or 0 (False). Compact expressions, like 0<x<1 ,
are now supported; you can enter: (0<x<1) as well (0<x)*(x<1)
Numerical range can be inserted using logical symbols and Boolean functions. For example:
For
2<x<5
insert
(2<x)*(x<5)
insert
OR(x<2, x>=10)
For -1<x<1
insert
(x>-1)*(x<1)
268
or also (2<x<5)
or also (x<2)+(x>=10)
, or (-1<x<1) , or also
|x|<1
Xnumbers Tutorial
Piecewise Functions. Logical expressions can also be useful for defining a piecewise
function, such as:
f(x) =
2x-1-ln(2)
ln(x)
x/2-1+ln(2)
x 0.5
0.5< x < 2
x2
The parser adopts a new algorithm for evaluating math expressions depending on logical
expressions, which are evaluated only if the logical conditions are true (Conditioned-Branch
algorithm). Thus, the above piecewise expression can be evaluated for any real value x without
any domain error. Note that without this features the formula could be evaluated only for x>0.
Another way to compute piecewise functions is splitting it into several formulas (see example 6)
Math Constants supported are: Pi Greek (), Euler-Napier (e)
pi = 3.14159265358979
or
pi# = 3.14159265358979
e# = 2.71828182845905
Angle expression
This version supports angles in RAD radians, DEG degree, or GRAD degree.
For example if you set the unit "DEG", all angles will be read and converted into degrees
sin(120) => 0.86602540378444
asin(0.86602540378444) => 120
rad(pi/2) => 90
, grad(400) => 360
Angles can also be write in DMS format like for example 29d 59m 60s
sin(29d 59m 60s)
=>
0.5
=>
30
Note This format is only for sexagesimal degree. It is independent from the unit set
(a, b)
(-1, -0.05)
(-1.4142135623731,
-9.94665E-18)
On the other hand, complex numbers can also be indicate by the common rectangular form:
3+3j
a+bj
-1 0.05j
-1.4142135623731 9.94665E-18j
You note that the second form is suitable for integer numbers, while, on the contrary, for
decimal or exponential number the first one is clearer. The parenthesis form is more suitable
also in nested results like
((2+3*4), (8-1/2)) that gives the complex number (14, 7.5)
Note: Pay attention if you want to use the rectangular convention in nested formulas.
wrong (2+3*4)+(8-1/2)j.
correct (2+3*4)+(8-1/2)*j
Do not omit the product symbol * before j because the parser recognize it as an expression,
not a complex number. The product symbol can be omitted only when before the letter j is a
constant number
Note: You can use both j and i for indicating the imaginary number
Functions
Functions are called by their function-name followed by parentheses. Arguments can be:
numbers, variables, expressions, or even other functions.
sin(x)
max(a,b)
log(x)
root(x,y)
cos(2*pi*t+phi)
comb(n,k)
269
atan(4*sin(x))
beta(x,y)
Xnumbers Tutorial
For functions having more than one argument, the successive arguments are separated by
commas "," or alternatively, by semicolon ";" if your system has comma as decimal separator.
max(a;b)
root(x;y)
comb(n;k)
beta(x;y)
max(a,b)
root(x,y)
comb(n,k)
beta(x,y)
270
Xnumbers Tutorial
Use
Description
RCM
subtraction
Note
RCM
factorial
5!=120
RM
percentage
RCM
multiplication
RCM
division
35/4 = 8.75
RCM
integer division
35\4 = 8
RCM
raise to power
3^1.8 = 7.22467405584208
||
RCM
absolute value
|-5|=5
RCM
addition
<
RM
less than
<=
RM
<>
RM
not equal
RM
equal
>
RM
greater than
>=
RM
abs(x)
RCM
absolute value
abs(-5)= 5
acos(x)
RCM
inverse cosine
argument -1 x 1
acosh(x)
RCM
argument x 1
acot(x)
RM
inverse cotangent
acoth(x)
RM
acsc(x)
RM
inverse cosecant
acsch(x)
RM
alog(z)
10^z
and(a,b)
logic and
arg(z)
asec(x)
RM
inverse secant
asech(x)
RM
argument 0 x 1
asin(x)
RCM
inverse sine
argument -1 x 1
asinh(x)
RCM
atanh(x)
RCM
atn(x), atan(x)
RCM
inverse tangent
beta(x,y)
RC
beta
betaI(x,a,b)
cbr(x)
cube root
clip(x,a,b)
Clipping function
comb(n,k)
RCM
combinations
conj(x)
conjugate
cos(x)
RCM
cosine
cosh(x)
RCM
hyperbolic cosine
cot(x)
RM
cotangent
coth(x)
RM
hyperbolic cotangent
csc(x)
RM
cosecant
csch(x)
RM
hyperbolic cosecant
dec(x)
RM
decimal part
dec(-3.8) = -0.8
deg(x)
RM
argument in radians
271
Xnumbers Tutorial
angle
digamma(x)
RC
digamma
argument x>0
Ei(x)
RC
argument x>0
Ein(x,n)
x >0 , n = 1, 2, 3
Elli1(x)
, 0<k<1
Elli2(x)
, 0<k<1
erf(x)
RC
argument x>0
erfc(x)
RC
eu
RM
exp(x)
RCM
exponential
exp(1) = 2.71828182845905
fact(x)
RM
factorial
argument x >0
fix(x)
RM
integer part
fix(-3.8) = 3
FresnelC(x)
FresnelS(x)
gamma(x)
RC
gamma
argument x>0
gammaln(x)
RC
logarithm gamma
argument x>0
gcd(a,b)
grad(x)
HypGeom(x,a,b,c)
Hypergeometric function
im(z)
int(x)
integer part
int(-3.8) = 4
integral(f,z,a,b)
Integral('1/z^2','z',1-i,1+i)
inv(x)
inverse of a number
1/x
lcm(a,b)
RM
ln(x), log(x)
RCM
logarithm natural
argument x>0
max(a,b,...)
RM
maximum
min(a,b,...)
RM
minimum
mcd(a,b,...)
RM
mcm(a,b,...)
RM
mod(a,b)
RM
modulus
mcm(4346,174) = 2
mcm(1440,378,1560,72,1650) =
21621600
mod(29, 6) = 5 mod(-29, 6) = 1
nand(a,b)
logic nand
neg(z)
opposit of complex
-z
nor(a,b)
logic nor
not(a)
logic not
nxor(a,b)
logic exclusive-nor
or(a,b)
logic or
pi
RM
Pi greek
3.141.
PolyCh(x,n)
Chebycev's polynomials
x , orthog. for -1 x 1
PolyHe(x,n)
Hermite's polynomials
x , orthog. for x +
PolyLa(x,n)
Laguerre's polynomials
x , orthog. for 0 x 1
PolyLe(x,n)
Legendre's polynomials
x , orthog. for -1 x 1
rad(x)
RM
radians conversion
re(x)
rnd(x)
random
root(x,n)
RCM
n-th root
round(x,d)
RM
round(1.35712, 2) = 1.36
sec(x)
RM
secant
sech(x)
RCM
hyperbolic secant
serie(.)
Serie('z/n','n',1,10,'z',1+3i)
sgn(x)
RC
sign
sin(x)
RCM
sin
argument in radians
sinh(x)
RCM
hyperbolic sine
272
Xnumbers Tutorial
sqr(x)
RCM
square root
tan(x)
RCM
tangent
tanh(x)
RCM
hyperbolic tangent
xor(a,b)
BesselI(x,n)
BesselJ(x,n)
BesselK(x,n)
BesselY(x,n)
J0(x)
logic exclusive-or
Bessel's function of 1st kind, nth
order, mod.
Bessel's function of 1st kind, nth
order
Bessel's function of 2nd kind, nth
order, mod.
Bessel's function of 2nd kind, nth
order
Bessel's function of 1st kind
Y0(x)
x 0
I0(x)
x >0
K0(x)
Si(x)
Ci(x)
Cosine integral
x >0
zeta(x)
AiryA(x)
AiryB(x)
Mean(a,b,...)
RM
Arithmetic mean
Meanq(a,b,...)
RM
Quadratic mean
meanq(8,9,12,9,7,10) = 9.300
Meang(a,b,...)
RM
Arithmetic mean
meang(8,9,12,9,7,10) = 9.035
Var(a,b,...)
RM
Variance
var(1,2,3,4,5,6,7) = 4.6666
Varp(a,b,...)
RM
Variance pop.
varp(1,2,3,4,5,6,7) = 4
Stdev(a,b,...)
RM
Standard deviation
Stdev(1,2,3,4,5,6,7) = 2.1602
Stdevp(a,b,...)
RM
Stdevp(1,2,3,4,5,6,7) = 2
Step(x,a)
Returns 1 if x a , 0 otherwise
DSBeta(x, a, b, [j])
DSBinomial(k, n, p, [j])
DSCauchy(x, m, s, n, [j])
DSChi(x, r, [j])
DSErlang(x, k, l, [j]))
k integer, x > 0
DSGamma(x, k, l, [j]))
DSLevy(x, l, [j]))
x > 0, l > 0
DSLogNormal(x, m, s, [j]))
DSLogistic(x, m, s, [j]))
DSMaxwell(x, a, [j]))
DSMises(x, k, [j]))
DSNormal(x, m, s, [j]))
DSPoisson(k, z, [j]))
k integer, z > 0
DSRayleigh(x, s, [j]))
x > 0, s > 0
DSRice(x, v, s, [j]))
x > 0, v 0 , s > 0
DSStudent(t, v, [j]))
DSWeibull(x, k, l, [j]))
x >0 , n = 0,1, 2, 3
x 0 , n = 0, 1, 2, 3
x >0 , n = 0,1, 2, 3
x 0 , n = 0,1, 2, 3
x 0
x >0
n integer , s > 0
r integer, x > 0
x > 0, m 0, s > 0
x > 0, m 0, s > 0
x > 0, a > 0
k > 0, - < x <
s>0
Symbol "!" is the same as "Fact", symbol "\" is the integer division, symbols |x| is the same as Abs(x)
Logical function and operators returns 1 (true) or 0 (false)
Note: the arguments separator of the functions changes automatically from "," to ";" if your system decimal separator is
comma ",".
273
Xnumbers Tutorial
Function Optimization
Macros for optimization on site
These macros has been ideated for performing the optimization task directly on the worksheet.
This means that you can define any function that you want simply using the standard Excel
built-in functions.
Objective function. For example: if you want to search the minimum of the bivariate function
51
35
) + ( y 100
)
f ( x, y ) = (x 100
2
insert in the cell E4 the formula "=(B4-0.51)^2+(C4-0.35)^2", where the cells B4 and C4
contain the current values of the variables x and y respectively. Changing the values of B4 e/o
C4 the function value E4 also changes consequently.
For monovariable
function only. It
needs the segment
where the max or
min is located
f ( x) = e 3 x sin(3 x) + e x cos(4 x)
1
The Downhill-Simplex of Nelder and Maid routine appears by the courtesy of Luis Isaac Ramos Garcia
274
Xnumbers Tutorial
Select the cell of the function C6 and start the macro "1D divide and conquer", filling the input
field as shown
The following examples are extracted from "Optimization and Nonlinear Fitting" , Foxes Team, Nov. 2004
275
Xnumbers Tutorial
f ( x, y ) = m ( y x 2 ) + (1 x )
2
The parameter "m" tunes the difficult: high value means high difficult in minimum searching.
The reason is that the minimum is located in a large flat region with a very low slope. The
following 3D plot shows the Rosenbrock's parabolic valley for m = 100
The function is always positive except in the point (1, 1) where it is 0. it is simple to
demonstrate it, taking the gradient
f = 0
4m x 3 + 2 x(1 2m y ) 2 = 0
2m( y x 2 ) = 0
276
Xnumbers Tutorial
From the second equation, we get
2m( y x 2 ) = 0
y = x2
2x 2 = 0
4m x 3 + 2 x (1 2m x 2 ) 2 = 0
x =1
So the only extreme is the point (1, 1) that is the absolute minimum of the function
To find numerically the minimum, let's arrange a similar sheet.
We can insert the function and the parameters as we like
Select the cell D4 - containing the objective function - and start the macro "Downhill-Simplex".
The macro fills automatically the variables-field with the cells related to the objective function.
But, In that case, the cell A4 contains the parameter m that the macro must not change. So
insert only the range B4:C4 int the variables field.
Algorithm
Simplex
Simplex
error
2.16E-13
4.19E-13
f ( x, y ) = x 2 + 2 xy 4 x + 4 y 2 10 y + 7
with the ranges constrains
0 x 2 , 0 y 0.5
The Excel arrangement can be like the following
277
time
2 sec
2 sec
Xnumbers Tutorial
278
Xnumbers Tutorial
f ( x, a , k ) = a e k x
The goal of the regression is to find the best couple of parameters (a, k) that minimizes the sum
of the absolute errors between the regression model and the given data set.
AS = | yi f ( xi , a, k ) |
The objective function AS depends only by parameter a, k. Giving in input this function to our
optimization algorithm we hope to solve the regression problem
A possible arrangement of the worksheet may be:
We hope that changing the parameters "a" and "k" int the cells E2 and F3, the objective
function (yellow cell) goes to its minimum value. Note that the objective function depends
indirectly by the parameters a and k.
1.2
1
0.8
0.6
y*
0.4
0.2
0
0
0.2
0.4
0.6
0.8
1.2
Starting form the point (1, 0) you will see the cells changing quickly until the macro stops itself
leaving the following "best" fitting parameters and the values of the regression y*
Best fitting parameters
a
-2
279
Xnumbers Tutorial
x( x)e
dx
Here, we have choose three different algorithms. They seem work very fine for this problem
(max)
Algorithm
error
Divide-conquer
2.210360464
9.8E-09
Downhill-Simplex
Excel Solver
2.210360527
2.210361438
5.4E-08
9.6E-07
Another example. Find the maximum of the following function for 0 < < 2
f ( ) = sin( x)dx
0
280
Xnumbers Tutorial
by reference method
by Application.Run method
281
Xnumbers Tutorial
Sub Test()
Dim a, b, c, DgtMax
DgtMax = Range("B2")
a = Range("B3")
b = Range("B4")
c = XNUMBERS.xdiv(a, b,
DgtMax)
Range("B5") = "'" & c
End Sub
Note that the above code works also if we write the compact statement
c = xdiv(a, b, DgtMax)
The XNUMBERS prefix is not necessary; it is useful only - at the developing time - to generate
automatically the list of the functions when we write the dot "." after XNUMBERS.
The result of the Test macro will be:
282
Xnumbers Tutorial
As we have seen calling x-function using the reference method is very easy and straightforward
because it works as we have "virtually" copied all the Xnumbers.xla code in our project
The main drawback is that the link set in our workbook is static. This mean that if we move or
install the Xnumbers.xla addin in another directory, also the link must be removed and then
rebuilt.
Application.Run method
A metod for calling external functions that always works, independently where you have
installed the addin, uses the Excel Application.Run method. Using this method we do not need
to add any reference link. We have only to load the addin in Excel.
Therefore our VBA environment looks like as simple as possible and the code of the macro
Test will modified as the following
Sub test()
Dim a, b, c, DgtMax
DgtMax = Range("B2")
a = Range("B3")
b = Range("B4")
With Application
c = .Run("xdiv", a, b,
DgtMax)
End With
Range("B5") = "'" & c
End Sub
The first argument of the "Run" method is the name of the function that we want to call, that is
"xdiv" in our case (note the quotes around the name).
The other arguments are, in sequence, the parameters that we pass to the function xdiv.
The "Run" method returns in the variable c the result of the xdiv function.
This method is both simple and efficient. The only drawback is that it cannot accept nested
functions. Thus the Test1 macro becomes a bit more tricky.
Sub test1()
Dim a, b, c, DgtMax
DgtMax = Range("B2")
a = Range("B3")
b = Range("B4")
With Application
c = .Run("xLn", b, DgtMax)
c = .Run("xmult", a, c, DgtMax)
End With
Range("B5") = "'" & c
End Sub
The final result, of course, is the same.
283
Xnumbers Tutorial
284
Xnumbers Tutorial
"Optimization for Engineering Systems", Ralph W. Pike, 2001, Louisiana State University
(http://www.mpri.lsu.edu/bookindex)
"Zeros of Orthogonal Polynomials" , Leonardo Volpi, Foxes Team
(http://digilander.libero.it/foxes/Documents)
"How to tabulate the Legendres polynomials coefficients" Leonardo Volpi, Foxes Team
(http://digilander.libero.it/foxes/Documents)
"DE-Quadrature (Numerical Automatic Integrator) Package", by Takuya OOURA, Copyright(C) 1996
Advanced Excel for scientific data analysis", Robert de Levie, 2004, Oxford University Press
"Microsoft Excel 2000 and 2003 Faults, Problems, Workarounds and Fixes", David A. Heiser, web site
http://www.daheiser.info/excel/frontpage.html
"NIST/SEMATECH e-Handbook of Statistical Methods", January 26, 2005
(http://www.itl.nist.gov/div898/handbook)
"DE-Quadrature (Numerical Automatic Integrator) Package", by Takuya OOURA, Copyright(C) 1996,
Research Institute for Mathematical Sciences, Kyoto University, Kyoto 606-01, Japan
(http://momonga.t.u-tokyo.ac.jp/~ooura)
"A Comparison of three high-precision quadrature schemes", David H. Bailey and Xiaoye S. Li, Copyright
2003, University of California (http://repositories.cdlib.org/lbnl/LBNL-53652)
"Asymptotic Bit Cost of Quadrature Formulas Obtained by Variable Transformation" P. Favati, Appl. Math.
Lett. Vol. 10, No. 3, pp. 1-7, 1997, Pergamon Copyright 1997
"Gli algoritmi della crittografia a chiave pubblica", Giovanni Fraterno, settembre 2000.
http://digilander.libero.it/crittazione
Bailey, D. H.; Borwein, J. M.; Calkin, N. J.; Girgensohn, R.; Luke, D. R.; and Moll, V. H. "Integer Relation
Detection." 2.2 in Experimental Mathematics in Action. Wellesley, MA: A K Peters, pp. 29-31, 2006.
Bailey, D. H. and Broadhurst, D. J. "Parallel Integer Relation Detection: Techniques and Applications."
Math. Comput. 70, 1719-1736, 2001.
Bailey, D. H. and Ferguson, H. R. P. "Numerical Results on Relations Between Numerical Constants Using
a New Algorithm." Math. Comput. 53, 649-656, 1989.
Bailey, D. and Plouffe, S. "Recognizing Numerical Constants."
http://www.cecm.sfu.ca/organics/papers/bailey/.
Borwein, J. M. and Lisonek, P. "Applications of Integer Relation Algorithms." To appear in Disc. Math.
http://www.cecm.sfu.ca/preprints/1997pp.html.
Weisstein, Eric W. "Integer Relation." From MathWorld--A Wolfram Web Resource.
http://mathworld.wolfram.com/IntegerRelation.html
Helaman R. P. Ferguson and David H. Bailey , "A Polynomial Time, Numerically Stable Integer Relation
Algorithm" RNR Technical Report RNR-91-032, July 14, 1992
285
Xnumbers Tutorial
Credits
Software developed
Xnumbers contains code developed by the following authors that kindly contributed to this
collection.
Luis Isaac Ramos Garcia
Olgierd Zieba
Michael J. Kozluk
Ton Jeursen
Richard Huxtable
Michael Ruder
Thomas Zeutschler
Lieven Dossche
Arnaud de Grammont
Rodrigo Farinha
Vladimir Zakharov
Hans Gnter
David A. Heiser
John Jones
Software translated
Xnumbers contains VB code translated from the following packages:
Takuya OOURA
Software used
This documentation was developed thanks to:
Microsoft Help Workshop 4
Msieve 1.17
Many thanks to everybody that have contributed to this document and made it more intelligible.
I am especially grateful for invaluable help on many occasions to Robert de Levie.
286
Xnumbers Tutorial
Analytical Index
Analytical index
Complex Function Integration (Romberg
method); 156
Complex Gamma Function; 104
Complex Hyperbolic Cosine; 103
Complex Hyperbolic Sine; 102
Complex Hyperbolic Tan; 103
Complex inverse; 101
Complex Inverse Hyperbolic Cos; 103
Complex Inverse Hyperbolic Sin; 103
Complex Inverse Hyperbolic Tan; 103
Complex Log; 101
Complex Logarithm Gamma Function; 104
Complex Multiplication; 98
Complex negative; 101
Complex power; 100
Complex Quadratic Equation; 105
Complex Roots; 100
Complex Series Evaluation; 184
Complex Sin; 102
Complex Subtraction; 98
Complex Tangent; 102
Complex Zeta Function; 104
Constant e; 59
Constant Ln(10); 59
Constant Ln(2); 59
Constant pi; 62
Continued Fraction; 108
Continued Fraction of Square Root; 109
Convert extended into double; 34
Convol; 189
corrector; 211
Corrector; 212; 214
Cos; 61
Cosine Integral Ci(x); 249
CosIntegral; 249
cplxabs; 99
cplxacos; 102
cplxacosh; 103
cplxadd; 98
cplxasin; 102
cplxasinh; 103
cplxatan; 102
cplxatanh; 103
cplxconj; 101
cplxcos; 102
cplxcosh; 103
cplxdigamma; 103
cplxdiv; 98
cplxei; 103
cplxEquation2; 105
cplxerf; 104
cplxerfc; 104
cplxeval; 260
cplxExp; 101
cplxgamma; 104
cplxgammaln; 104
A
Absolute; 28
Adams; 211; 212
Adams-Bashfort-Moulton; 211
Addition; 23
Airy functions; 252
AiryA; 252
AiryAD; 252
AiryB; 252
AiryBD; 252
Aitken; 158; 183
Arccos; 62
Arcsine; 62
Arctan; 62
Arithmetic Mean; 40
B
Base conversion; 240
baseChange; 240
Bessel functions; 249
BesselSphJ; 255
Beta function; 247
Bisection; 231
Bivariate Polynomial; 88
Brouncker-Pell Equation; 120
C
Cebychev; 78
Change sign; 28
Check digits; 32
Check Integer; 112
Check odd/even; 112
Check Prime; 109
Cholesky; 131
Coefficients of Orthogonal Polynomials; 96
Combinations; 39
Combinations function; 248
Complement of right angle; 63
Complex absolute; 99
Complex Addition; 98
Complex ArcCos; 102
Complex ArcSin; 102
Complex ArcTan; 102
Complex Complementary Error Function; 104
Complex conjugate; 101
Complex Cos; 102
Complex digamma; 103
Complex Division; 98
Complex Error Function; 104
Complex Exp; 101
Complex Exponential Integral; 103
Complex Expression Evaluation; 260
287
Xnumbers Tutorial
cplxintegr; 156
cplxinv; 101
cplxLn; 101
cplxmult; 98
cplxneg; 101
cplxpolar; 99
cplxpow; 100
cplxrect; 99
cplxroot; 100
cplxserie; 184
cplxsin; 102
cplxsinh; 102
cplxsub; 98
cplxtan; 102
cplxtanh; 103
cplxzeta; 104
Crout; 131
cspline_coeff; 199
cspline_eval; 197
cspline_interp; 197
cspline_pre; 197
Cubic Spline 2nd derivatives; 197
Cubic Spline Coefficients; 199
cvBaseDec; 240
cvBinDec; 240
cvDecBase; 240
cvDecBin; 240
errfun; 244
Error Function Erf(x); 244
Euler; 211
Euler constant ; 60
Euler-Mascheroni Constant; 245
Euler's Totient function; 121
exp_integr; 244
expn_integr; 244
Exponential; 58
Exponential any base; 58
Exponential integral Ei(x); 244
Exponential integral En(x); 244
Extended Number Check; 32
F
Factor; 116
Factorial; 39
Factorial with double-step; 39
Factorize; 113
Factorize function; 116
FFT; 137; 142
FFT_INV; 139
FFT2D; 141
FFT2D_INV; 141
Fibonacci numbers; 250
First Derivative; 234
Flip; 33
Format Extended Number; 32
Fourier; 165
Fourier_cos; 164
Fourier_cos; 166
Fourier_cos; 166
Fourier_sin; 164
fract; 107
Fract_Interp; 195
Fract_Interp_Coef; 195
FractCont; 108
FractContSqr; 109
Fresnel cosine Integral; 250
Fresnel sine Integral; 250
Fresnel_cos; 250
Fresnel_sin; 250
Function Integration (Double Exponential
method); 152
Function Integration (mixed method); 154
Function Integration (Newton-Cotes); 159
Function Integration (Romberg method); 151
D
Data Conditioning; 53
Data Integration (Newton Cotes); 157
dBel; 240
Decibel; 240
Decimal part; 29
DFSP; 140
DFSP_INV; 140
DFT; 137; 142
DFT_INV; 139
Diff1; 234
Diff2; 235
digamma; 247
Digamma function; 247
Digit_Max; 22; 35
Digits count; 31
Digits sum; 33
DigitsAllDiff; 32
Diophantine; 119
Diophantine Equation; 119
DiophEqu; 119
Discrete 2D Fourier Transform; 141
Discrete Convolution; 189
Discrete Fourier Inverse Transform; 139
Discrete Fourier Spectrum; 140
Discrete Fourier Transform; 137
Division; 24
Double Data integration; 179
Double Exponential; 152
Double Integral; 168
Double integration function; 174
Double Series; 185
Downhill; 268
DPOLYN; 74
G
Gamma F-factor; 247
Gamma function); 245
Gamma quotient; 246
GCD; 106
Geometric Mean; 40
Grad; 235
Gradient; 235
Greatest Common Divisor; 106
H
Hermite; 78
Hessian; 236
Hessian matrix; 236
Hyperbolic Arc Cosine; 60
Hyperbolic Arc Sine; 59
E
Elliptic Integrals; 252
288
Xnumbers Tutorial
I
I BesselSphY; 255
IElliptic1; 252
IElliptic2; 252
Incomplete Beta function; 248
Incomplete Gamma function; 248
Infinite integral; 177
Infinite Integration of oscillating functions; 165
Integer Division; 24
Integer part; 29
Integer polynomial; 86
Integer relation; 122
Integer Remainder; 25
Integer roots; 70
integr; 166
Integr; 154
Integr_2D; 174
Integr_fcos; 162
Integr_fsin; 162
Integr_nc; 159
Integr_ro; 151
Integr2D; 168
Integr3D; 171
Integral function; 147
Integral of sine-cosine power; 254
Integral_Inf; 177
Integration of oscillating functions (Filon
formulas); 162
Integration of oscillating functions (Fourier
transform); 164
IntegrData; 147
IntegrData2D; 179
IntegrDataC; 157
Interp_Mesh; 200
Interpolation with continue fraction; 195
Interpolation with Cubic Spline; 197
IntPowCos; 254
IntPowSin; 254
Inverse; 24
Inverse 2D Discrete Fourier Transform; 141
Inverse Discrete Fourier Spectrum; 140
M
Macro for Double Integration; 168
Macro for Multiprecision Matrix operations; 135
Macro for Triple Integration; 171
Macro Integer relation finder; 126
Macro Mesh Fill; 201
Macro Poly Regression; 51
Macro Regression; 51
Macro Sampler; 145
Macros for optimization on site; 267
Macros X-Edit; 35
Math expression strings; 263
MathParser; 265
matrix; 135
Matrix Addition; 129
Matrix Determinant; 129
Matrix Inverse; 129
T
Matrix LL decomposition; 131
Matrix LU decomposition; 131
Matrix Modulus; 130
Matrix Multiplication; 129
Matrix Power; 130
Matrix Subtraction; 129
Maximum Common Divisor; 106
MCD; 106
MCM; 106
Mesh Interpolation 2D; 200
Minimum Common Multiple; 106
mjkLRE; 242
Modular Addition; 110
Modular Division; 110
Modular Multiplication; 110
modular power; 110
Modular Power; 110
Modular Subtraction; 110
Multiple roots; 72
Multiplication; 24
Multiprecision Base Conversion; 241
Multiprecision Excel Formula Evaluation; 261
Multiprecision Expression Evaluation; 256
J
Jacobian; 236
Jacobian matrix; 236
K
Kummer confluent hypergeometric functions;
253
Kummer1; 253
Kummer2; 253
N
Next Prime; 109
NextPrime; 109
Non Linear Equation Solving; 238
N-Root; 28
Numbers comparison; 31
L
LCM; 106
Least Common Multiple; 106
Legendre; 78
289
Xnumbers Tutorial
Polynomial shift; 81
Polynomial solving; 86
Polynomial subtraction; 77
Polynomial System of 2nd degree; 87
Polynomial writing; 76
PolyRadius; 82
PolyRem; 77
PolyShift; 81
PolySolve; 86
PolySub; 77
Polyterms; 80
PolyTerms; 75
predictor; 211
Predictor; 212
Predictor; 214
Prime; 109
Prime Numbers Generator; 117
Prime Test; 117
PrimeGenerator; 117
Product; 27
PSLQ; 122
Q
Quadratic Mean; 40
R
Raise to power; 27
Rational Fraction approximation; 107
Rectangular Conversion; 99
RegLinMM; 56
RegLinRM; 55
regression; 272
Relative Rounding; 30
Root Error Estimation; 68
Rounding; 29
S
Scalar Product; 130
Scientific Format; 34
Secant; 232
Second Derivative; 235
Serie_trig; 186
Serie2D_trig; 188
Series acceleration with ^2; 183
Series Evaluation; 182
sign; 31
Significant Digits count; 31
Similarity Transform; 130
Simplex; 268
Sin; 61
Sine Integral Si(x); 249
SinIntegral; 249
Solve Linear Equation System; 132
SortRange; 33
Spherical Bessel functions of integer order; 255
Split scientific format; 34
Square Delta Extrapolation; 133
Square Root; 28
Standard Deviation; 40
Sub-Tabulation; 53
Subtraction; 23
Sum; 27
sumDigits; 33
SYSPOLY2; 87
290
Xnumbers Tutorial
xeu; 60
xeval; 26; 256
xevall; 256
xexp; 58
xfact; 39
xfact2; 39
xFib; 250
xFormat; 32
xfrac; 107
xFractCont; 108
xGammaF; 247
xGammaI; 248
xGammaln; 246
xGammalog; 246
xGammaQ; 246
xGm; 245
xgmean; 40
xint; 29
xinv; 24
xIsInteger; 112
xIsOdd; 112
xIsSquare; 112
xIsXnumber; 32
xLn; 58
xLn10; 59
xLn2; 59
xLog; 58
xLRE; 242
xMatAbs; 130
xMatAdd; 129
xMatBAB; 130
xMatDet; 129
xMatInv; 129
xMatLL; 131
xMatLU; 131
xMatMult; 129
xMatPow; 130
xMatSub; 129
xMCD; 106
xMCM; 106
xmean; 40
xmult; 24
xmultmod; 110
xneg; 23; 28
xpi; 62
xpi2; 62
xpi4; 62
xpow; 27
xpowmod; 110
xProdScal; 130
xProdVect; 132
xqmean; 40
xRegLinCoef; 43
xRegLinCoef; 45
xRegLinEval; 49
xroot; 28
xround; 29
xroundr; 30
xSerie2D; 185
xsin; 61
xsinh; 59
xsplit; 34
xsqr; 28
xstatis; 42
xstdev; 40
xstdevp; 40
Tan; 62
tanh-sinh transformation; 152
Totient; 121
Trigonometric double serie; 188
Trigonometric series; 186
Truncating; 29
U
Univariate Statistic; 42
V
Variance; 41
Vector flip; 33
Vector Product; 132
W
Weight of Orhogonal Polynomials; 95
X
x2pi; 62
xabs; 28
xacos; 62
xacosh; 60
xadd; 23
xaddmod; 110
xanglecompl; 63
xasin; 62
xasinh; 59
xatan; 62
xatanh; 60
xBaseChange; 241
xBeta; 247
xBetai; 248
xCalc; 261
xcdbl; 34
xcomb; 39
xcomb_big; 248
xcomp; 31
xcos; 61
xcosh; 60
xcplxabs; 99
xcplxadd; 98
xcplxconj; 101
xcplxdiv; 98
xcplxExp; 101
xcplxinv; 101
xcplxLn; 101
xcplxmult; 98
xcplxneg; 101
xcplxpolar; 99
xcplxpow; 100
xcplxrect; 99
xcplxroot; 100
xcplxsub; 98
xcvexp; 34
xdec; 29
xDgt; 31
xdiv; 24
xdivint; 24
xdivmod; 110
xdivrem; 25
xe; 59
291
Xnumbers Tutorial
xsub; 23
xsubmod; 110
xsum; 27
xSYSLIN; 132
xtan; 62
xtanh; 60
xtrunc; 29
xUnformat; 32
xvar; 41
xvarp; 41
Z
Zero_bisec; 231
Zero_sec; 232
Zeros of Orthogonal Polynomials; 95
Zeta; 251
Zeta function; 251
292
Xnumbers Tutorial
293