special functions on the 41 using the sandmath …hp41.claughan.com/file/specialfunctions.pdfspecial...

46
Special functions on the 41 - Using the SandMath module. © Ángel Martin – February 2010 - 1 - Special Functions on the 41 Using the SandMath module Written and developed by: Ángel M. Martin February 2010

Upload: lamcong

Post on 21-Apr-2018

218 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 1 -

Special Functions on the 41 Using the SandMath module

Written and developed by: Ángel M. Martin February 2010

Page 2: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 2 -

This compilation, revision A.1.1.

Copyright © 2010 Ángel M. Martin

Published under the GNU software license agreement. SandMath overlay graphics © 2010 by M. Luján Garcia. Screen captures taken from V41, Windows-based emulator developed by Warren Furlow. See http://www.hp41.org/ Original authors retain all copyrights, and should be mentioned in writing by any party utilizing this material. No commercial usage of any kind is allowed.

Page 3: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 3 -

Table of contents.

1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 a. The Function Launchers . . . . . . . . . . . . . . . . . . . . 6

2. Hyperbolic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 7

a. Direct and Inverse . . . . . . . . . . . . . . . . . . . . . . . . 7 b. Program remarks . . . . . . . . . . . . . . . . . . . . . . . . . 8

3. Gamma and associates. . . . . . . . . . . . . . . . . . . . . . . . . 12

a. Stirling method . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 b. Lanczos approximation . . . . . . . . . . . . . . . . . . . . . 13 c. Program remarks . . . . . . . . . . . . . . . . . . . . . . . . . 14 d. Reciprocal Gamma . . . . . . . . . . . . . . . . . . . . . . . . . 19 e. LogGamma function . . . . . . . . . . . . . . . . . . . . . . . 22 f. Digamma function . . . . . . . . . . . . . . . . . . . . . . . . . 27 g. Beta function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4. Riemann’s Zeta . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

a. The intractable convergence . . . . . . . . . . . . . . 34 b. Program remarks . . . . . . . . . . . . . . . . . . . . . . 35

5. Lambert W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

a. Real solution . . . . . . . . . . . . . . . . . . . . . . . . . 38 b. Program remarks . . . . . . . . . . . . . . . . . . . . . . 39

6. Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

a. Hyperbolic Launcher . . . . . . . . . . . . . . . . . . . . . 41 b. Main Launcher . . . . . . . . . . . . . . . . . . . . . . . . . 43

Page 4: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 4 -

Page 5: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 5 -

1. Introduction. This mini-paper describes the special functions implemented on the SandMath Module, either as native MCODE or as user program examples derived from others. They can broadly be grouped into the following logical types:

Bessel Functions (*) Gamma and associates Riemann’s Zeta Lambert W Hyperbolics

(*) The Bessel functions group has been covered in an independent article already, and thus they won’t be included in here. There’s obvious restrictions and design limitations on the 41 platform (CPU speed, 9-digit precision, single-line display, and small numeric range to mention the most important ones) that could make this project somehow questionable. There’s no question that modern-day calculators perform faster and are better design for this – and that’s precisely what makes this project interesting, the challenge that it poses and how to work around those obvious limitations. Using MCODE is a design criterion, in order to speed up as much as possible the execution, and also to provide a cleaner and more usable implementation that doesn’t require stack or data registers, user flags, etc. This has been met in a large extent, and –save some exceptions- user code solutions are only used as specific examples for completion sake. Special functions are particular mathematical functions which have more or less established names and notations due to their importance in mathematical analysis, functional analysis, physics, or other applications. There is no general formal definition, but the list of mathematical functions contains functions which are commonly accepted as special. Some elementary functions are also considered as special functions. With “just” an EE background the author has had his dose of relatively special functions, from college to today. However not being a mathematician doesn’t qualify him as a field expert by any stretch of the imagination. Therefore the descriptions that follow are mainly related to the implementation details, and not to the general character of the functions. This is not a mathematical treatise but just a summary of the important aspects of the project, highlighting their applicability to the 41 platform. The implementations described in this mini-manual do nothing but scratching the surface of the Special Functions field, where one can easily spend several life-times and still be just half-way through. Lastly, this document includes many references taken from open sources on the web, Wikipedia and Wolfram Math being the most typical ones. The author has begged, stolen and borrowed to a large extent to prepare it – with specific references provided as appropriate.

Page 6: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 6 -

1.1.- The Function Launcher. One of the challenges is how to access and logically structure the additional functionality provided by the SandMath module. The 41 very clean user interface provides a very general-purpose USER mode that works very well for its versatile design and numerous additions available – with literally dozens of application modules and its dual-character calculator or HP-IL system controller. Without function menus or the capability to group them by logical similarities it becomes uncomfortable remembering the function names, and having to type their names every single time. Not to mention that with a limited number of keys on the keyboard, soon enough we run into conflicts trying to assign that many functions into the chosen keys – too much competition!

The concept of the function launcher is a way to overcome these deficiencies, and works very well considering its relatively simple implementation requirements. The picture on the left shows the Function Launcher on the SandMath overlay on the topmost left key: this is the “blue gateway” to access any of the 20 special functions available, either by itself or combined with the SHIFT key for the hyperbolics. Not a bad feat for an ancient design that still performs up to today’s needs!

The schematic below shows the possible branching using the function launcher:

1. SF plus blue legends (keys A to M) for the corresponding special functions 2. SF plus SHIF plus green labels (keys HIJ) for the direct Hyperbolics 3. SF plus SHIFT Twice plus green labels (keys HIJ) for the inverse hyperbolics 4. SF Twice to invoke the Fraction Arithmetic launcher, which in turn enables the

bottom part of the special keyboard (keys QUY and bottom row)

For this kind of approach to work there must also be visual feedback in the display to indicate that a special action is being performed, and that further input must be made to complete the action. The 41 platform has a mechanism that suits itself very well for this task, called the Partial Entry Sequence. Using it it’s possible to redefine the keyboard depending on the previous prompt, also ignoring all those inputs not relevant to the occasion. A good example of this is the native function STO, which allows not only for a register number but also for arithmetic operations, indirect addressing, or

stack registers to be used in the input fields of the prompt. This is the basic idea that is used with the Special Function launcher as well. The model is there, it’s just a matter of coding it right. Let’s start with the different special functions to see the role of this interface.

Page 7: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 7 -

2. Hyperbolic Functions.

SINH – Hyperbolic Sine COSH – Hyperbolic Cosine TANH – Hyperbolic Tangent ASINH – Inverse Hyperbolic Sine ACOSH – Inverse Hyperbolic Cosine ATANH – Inverse Hyperbolic Tangent

It goes without saying that the lack of hyperbolic functions on the 41 is barely forgivable, regardless of when it was designed or released. Nowadays there’s nothing “special’ about them, yet back when the 41 was introduced it wasn’t a common occurrence to include them – thus they are part of the SandMath to close such gap. What’s even less understandable is why HP didn’t include proper MCODE implementation in the Math Pack first (which had a FOCAL program version), or in the Advantage Pack later on (which adding insult to injury didn’t even have that!) – And considering its simple character is hard to justify. Only the AECROM module addressed this issue once and for all, and such is the basis of the implementation on the SandMath – using similar but not the same code. The formulas used are well-known and don’t require any special consideration to program:

The direct functions are basically exponentials, whilst the inverses are basically logarithms. Both cases are well covered with the mainframe internal math routines [EXP10] and [LOG10] without any need to worry about singularities or special error handling.

The use of the function launcher permits convenient access to these six functions without having to assign them to any key in USER mode. Efficient usage of the keyboard, which can double up for other launchers or the standard USER mode assignment if that’s also required. Combining the SF and the SHIFT keys does the trick in a clean and logical way.

Page 8: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 8 -

The following is the machine code listing for the direct hyperbolic functions:

Credit is given to Nelson Crowle, who wrote the original AECROM versions – although these listings here are notably different from the original ones. In particular notice the [SHYP] section, specifically prepared for subroutine use. It will be used by the Digamma function code, which uses a hyperbolic sine on its asymptotic expression – to be seen later on.

Page 9: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 9 -

These functions typically start off by calling [CHK_NO_S] to check for valid numeric input (discarding Alpha Data or other error conditions), and finish invoking [NFRX] - the normal function return with one argument in X to store the initial argument in LastX, place the final result in X and check for overflow conditions. Flag F9 controls the Sine or Cosine case, allowing for code share in the main section of the code. The one remark to make is the clearing of the status bits (or CPU flags) with instruction ST=0. This is done repeated times during these listings, and is a good practice to ensure correct calculations during the SST evaluation of a program; which sets F4 and that interferes with the exponential and logarithm routines.

Page 10: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 10 -

The Hyperbolic tangent has a bit of a life of its own. Note the usage in the inverse code of the mainframe routine [XLN1+x], an obscure one which supposedly provides better precision (or is it accuracy?) – A wise thing when there’s only 9 significant digits to ensure the accuracy of the results.

The backwards jump leads to the exit point, and it’s just a matter of saving a couple of bytes. Register 9(Q) is used as scratch for intermediate calculations, mainly due to the fact that the internal mainframe routines already utilize both A and B registers, and very frequently also the M register, leaving just the N register available. Sign changes are done by inverting the mantissa sign field, using the instruction C=-C-1 MS. The only precaution with this method is that it may set the carry flag when changing from positive to negative, so the following instruction can’t be one that uses the carry status as a decision making condition, such as ?C XQ or ?NC GO, etc.

Page 11: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 11 -

Not a difficult task by any means, it really makes you wonder about the reasons not to include them in the infamous Math Pack, or in the Advantage Module. This one in particular is an interesting case: both SINH and COSH are indeed included into the triangle solver program (a copy of the Math Pack version) but their alphabetical names have been removed, making it impossible to access those even in FOCAL version despite free FAT entries are still available. Go and figure! But enough ranting, let’s now prepare for a substantial tone change as we move to more demanding challenges inherent to the implementation of less well-behaved functions (albeit much more interesting).

Page 12: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 12 -

3. Gamma and its associates.

GAMMA – Euler’s Gamma function 1/GM – Reciprocal Gamma PSI – Digamma function LNGM – Logarithm of Gamma BETA – Euler’s Beta function

A Quantum leap from the previous case, both in terms of the mathematical definition and as it refers to the required programming resources and techniques. In mathematics, the Gamma function (represented by the capital Greek letter Γ) is an extension of the factorial function, with its argument shifted down by 1, to real and complex numbers. If n is a positive integer, then

showing the connection to the factorial function. For a complex number z with positive real part, the Gamma function is defined by

Things become much more interesting in the negative semi-plane, as can be seen in the plot on the right. The Gamma function has become standard in pocket calculators, either as extended factorials or as proper gamma definition. It’s already available in the HP-11C and of course on the 15C, and that has continued to today’s models. Implementing it isn’t the issue, but achieving a reasonable accuracy is the challenge. A typical method uses the Stirling approximation to compute Gamma. This is relatively simple to program, but its precision suffers for small values of the argument. A version suitable for calculators is as follows:

Valid for Re(z)>0, and with reasonable precision when Re(z)>8. For values less than that it’s possible to use the recurrence functional equation, taking it to the “safe” region and back-calculating the result with the appropriate adjusting factor:

Page 13: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 13 -

Incidentally, this method can be used for any approximation method, not only for Stirling’s. The method used on the SandMath is the Lanczos approximation, which lends itself better to its implementation and can be adjusted to have better precision with careful selection of the number of coefficients used. For complex numbers on the positive semi-plane [Re(z)>0], the formula used is as follows

Although the formula as stated here is only valid for arguments in the right complex half-plane, it can be extended to the entire complex plane by the reflection formula,

An excellent reference source is found under http://www.rskey.org/gamma.htm, written by Viktor T. Toth. Let’s mention that this method yields good enough a precision that doesn’t require using the functional equation to adjust it for small values of the argument. The obvious advantage is that without the required program loop, the execution time is shorter and constant for any input. This becomes of extreme importance when Gamma is used as a subroutine of more complex cases, like the Bessel J and I functions – where the cumulative additional time is very noticeable.

q0 = 75122.6331530 q1 = 80916.6278952 q2 = 36308.2951477 q3 = 8687.24529705 q4 = 1168.92649479 q5 = 83.8676043424 q6 = 2.5066282

Page 14: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 14 -

3.1. Program remarks. The trivial-looking MCODE listing below shows how Gamma has been written as a subroutine – to be also used by other functions like Euler’s Beta or the Bessel functions of the first kind.

The remaining MCODE listing is very linear in nature, as there are no adjustment for small or negative arguments with loops or conditionals involved. It’s hardly a difficult implementation, but sure enough lengthy and detailed. We begin by making sure the argument isn’t one of the functions poles (those negative integers) and within the numeric range of the calculator.

Next section in the code calculates the product in the denominator of the formula. A total of six factors in the direct loop, controlled by the value of the Q pointer. Note the usage of register 4(L) to save the partial and final result of the multiplications.

Page 15: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 15 -

This is followed by a very long stream to calculate the polynomial sum of factors affected by the Lanczos coefficients q(i), i=1,2..6 We’ll of course use Horner’s method to write the polynomial for a more efficient programming – as much as MCODE can get for these purposes. Notice the direct way to input the constants in the C register using LD&PT. Finally it’ll be the turn for the exponential and power calculations. A bit pedestrian but necessary!

Page 16: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 16 -

Page 17: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 17 -

Page 18: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 18 -

Page 19: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 19 -

hallelujah! 3.2. Reciprocal Gamma function. The reciprocal Gamma function is the function

where Γ(z) denotes the Gamma function. Since the Gamma function is meromorphic and nonzero everywhere in the complex plane, its reciprocal is an entire function. The reciprocal is sometimes used as a starting point for numerical computation of the Gamma function, and a few software libraries provide it separately from the regular Gamma function. Taylor series expansion around 0 gives

Wrench (1968) numerically computed the coefficients for the series expansion about 0 of:

The SandMath uses the expression seen for the Windschitl approximation on page 12, only inverting the formula terms as appropriate. This allows coding both the direct and the reciprocal Gamma with practically the same program, only discriminating for each case using one CPU flag (F9). Comparing the results obtained by GAMMA (using Lanczos) and GM (using Windschit) it appears that the precision is generally better in the Lanczos case – which also happens to be faster due to its polynomial-like form and the absence of loops to adjust the result for smaller arguments. Such adjusting loops have been written as separate subroutines, [DELTAX] and [ADJUST], as they will also be used for the Digamma and LogGamma functions later on. There’s therefore quite significant code reuse amongst all the gamma functions in the SandMath. Note the special case for x=0, which is not a pole for this function but it is a singularity for all the others that used the common subroutines – therefore the dedicated check in the routine listing. The [PRELUDE] subroutine is shared by these two functions and by the LogGamma function as well. It simply performs calculations common to the three of them, namely the expression under the square root in the Windschitl formula – also involving the hyperbolic sine.

Page 20: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 20 -

Page 21: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 21 -

CPU flag F9 controls the execution flow, changing the sign of the exponent in lines A1C0 and A1C1 to either multiply or divide the corresponding term; swapping numerator and denominator in the term SQRT(2 pi / X) in line A1D4; and also to control the final operation to the product adjusting the result (lines A1E5 to A1E7). Also interesting is the use of the mainframe routine [PI_BY_2], which saves code lines and utilizes the 41 OS resources. We’ll see the listing of [DELTAX], [ADJUST] and [PRELUDE] in the following sections.

Page 22: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 22 -

3.2. Log Gamma function. Many times is easier to calculate the Logarithm of the Gamma function instead of the main Gamma value. This could be due to numeric range problems (remember that the 41 won’t support numbers over E100), or due to the poles and singularities of the main definition. The SandMath uses the Stirling approximation to compute LogGamma, as given by the following expression (directly obtained from the formula in page 12):

This approximation is also good to more than 8 decimal digits for z with a real part greater than 8. For smaller values we’ll use the functional equation to extend it to the region where it’s accurate enough and then back-calculate the result as appropriate.

The picture on the left shows the LogGamma function for positive arguments. Interestingly it has a negative results region between 1 and 2 – so it isn’t always positive. Note also the asymptotic behavior near the origin – due to the Gamma function pole.

The implementation on the SandMath uses the analytical continuation to calculate LogGamma for arguments less than 9, including negative values. Obvious problems (like the poles at negative integer) will yield DATA ERROR messages, but outside that the approximation should hold. Notice also that the same error will occur when trying to calculate LogGamma when Gamma is negative, which occurs between even-negative numbers and their immediately lower (inferior) one – see the plot in page 12). See the following link for a detailed description of another implementation (using Lanczos for both cases) to calculate Gamma and LogGamma on the 41 by Steven Thomas Smith: http://www.hpmuseum.org/cgi-sys/cgiwrap/hpmuseum/articles.cgi?read=941 An excellent implementation of Gamma and related functions for the 41 is available on the following link, written by Jean-Marc Baillard (very complete and detailed): http://www.hpmuseum.org/software/41/41gamdgm.htm Let’s study the MCODE listing for this function, which promises to be as exciting as the previous one. It starts off with a call to the [DELTAX] subroutine to offset the argument to the safe region to apply this approximation, with x>8 (more about this later). Notice the use of the hyperbolic sine as subroutine as well.

Page 23: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 23 -

Page 24: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 24 -

Note in lines A154 and following the usage of CPU F8 to interrogate whether we’re in need to adjust the calculated result. This flag is set by [DELTAX] in case the argument is lower than 9, and signals the need to use the recurrence formula – which is done in the [ADJUST] subroutine. The number of iterations of this final loop varies, depending on the distance between the argument and the “border value” x=9 – that’s a dynamic implementation that only applies as much correction as it’s strictly required, and helps reduce the execution time. The same technique will be used in the Digamma code later on. [PRELUDE] simply calculates the expression: [x’ * SINH (1/x’) + 1/(810*x’^6) ] Where x’= (x+d) > 9 ; that is: d = delta to 9 The 4-level subroutine stack limit must be carefully watched – or this scheme will fail. So notice that all these routines are placed within the same ROM quad, and thus the port-dependent calls only use one return stack level.

Page 25: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 25 -

Next comes the [ADJUST] subroutine, that calculates the correction value as the product of distances until the value x=9. This product will be the divisor for GM and LogGamma, and the multiplier for the reciprocal Gamma. Gamma (x+9) = Gamma(x) * PROD{x+k} |k=0,1,2… 8

Page 26: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 26 -

We’ll leave the remaining common subroutine [DELTAX] for the next case, the Digamma function.

Page 27: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 27 -

3.3 Digamma function. In mathematics, the digamma function is defined as the logarithmic derivative of the gamma function:

It is the first of the polygamma functions. It is related to the harmonic numbers in that

where Hn is the n'th harmonic number, and γ is the Euler-Mascheroni constant.

As can be seen in the figure on the left plotting the digamma function, it’s an interesting behavior showing the same poles and other singularities to worry about. It should be possible to find an approximation valid for all the definition range of the function. It has been implemented on the SandMath using the formulas derived from the called Gauss digamma theorem, although further simplified in the following algorithm:

programmed as: u^2{[(u^2/20-1/21)u^2 + 1/10]u^2 –1}/12 – [Ln u + u/2], The implementation also makes use of the analytic continuation to take it to arguments greater than 9 (same as it’s done for LogGamma), using the following recurrence relation to relate it to smaller values:

Which naturally can be applied for negative arguments as well. Let’s see without further ado the detailed MCODE listing for this function. It also starts with a call to the [DELTAX] subroutine for the same reasons explained before (code reuse at last!). It quickly gets straight to business of calculating the terms of the approximation – not rocket science but still necessary enough.

Page 28: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 28 -

Page 29: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 29 -

This would be all if we didn’t have to adjust the result for shifted arguments. Again CPU flag F8 is used to decide it. The technique is similar to the previous one, looping for as many iterations as required depending on the distance to the border value x=9. The recurrence equation is slightly more complex, as it involves a one-over operation instead of just a multiplication like in the LogGamma case. Like any good native function worth its name the initial argument will be placed in the LastX register upon completion, and the final result is checked for OUT OF RANGE condition - which isn’t very likely to occur in this case given the relatively well-behaved behavior of this function.

Page 30: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 30 -

The following page has the [DELTAX] code – including the info message routine to display “RUNNING…” to inform the user that the result is being calculated (it started its life being a ‘Summing’ text message but HP-15C users will recognize this wink). Notice the check for zero – which won’t be allowed by the logarithm or the divisions by x in every term of the approximation. The message “DATA ERROR” is returned in this case – although we could as well have special-conditioned it, returning zero instead (i.e. not doing a thing). Be also in the lookout for the [PI_BY_2] routine from page 21 (you sure missed it, didn’t you?) – never wondered how’s pi programmed on your calculator? Here’s an interesting approach taken by the writers of the 41 OS – and the legacy goes on.

Page 31: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 31 -

And here’s the text message routine:

Page 32: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 32 -

3.4. Euler’s Beta function The beta function, also called the Euler integral of the first kind, is a special function defined by

The beta function was studied by Euler and Legendre and was given its name by Jacques Binet. The most common way to formulate it refers to its relation to the Gamma function, as follows:

As a graphical example, the picture below shows B(X,0.5) for values ox x between –4 and 4. As it’s expected, the same Gamma problem points are inherited by the Beta function.

The implementation on the SandMath makes no attempt to discover new approaches or utilize any numeric equivalence: it simple applies the definition formula using the Gamma subroutine. Obvious disadvantages include the reduced numeric range – aggravated by the multiplication of gamma values in the numerator. Register usage becomes somehow tricky due to the gamma subroutine already using the usual scratch registers N, 4(L), and 9(Q). In order not to use the alpha registers MNOP the choice has been to sacrifice the Z register in the memory stack as the lesser of the evils. Execution time corresponds to three times that of the Gamma function, plus the small overhead to perform the Alpha Data checks and the arithmetic operations between the three gamma values.

Page 33: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 33 -

Here’s a relatively simple implementation of the Beta function, directly applying the function’s definition using the Gamma function. No frills or any tricks at play.

Page 34: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 34 -

4. Riemann Zeta function. Perhaps one of the most-studied functions in mathematics, it owes its popularity to its deep-rooted connections with prime numbers theory. Not having an easy approximation to work with, its implementation on the 41 will be a bit of a challenge – mainly due to the very slow convergence of the series representation used to program it. Be assured that this numeric calculation won’t help you prove the Riemann hypothesis (and collect the $1M prize) – so adjust your expectations accordingly. The Riemann zeta function is a function of complex argument s that analytically continues the sum of the infinite series

or the integral form: The Riemann zeta function satisfies the functional equation

valid for all complex numbers s (excluding 0 and 1), which relates its values at points s and 1−s. The plots below of the real Zeta function show the negative side with some trivial zeros, as well as the pole at x=1.

The implementation in the SandMath module uses the alternative definitions shown below, in a feeble attempt to get a faster convergence (which in theory it does although not very noticeably given the long execution times involved). The summations are called the Dirichlet Lambda and Eta functions respectively.

The following links to the MAA and the (now defunct) Zetagrid make fascinating reading on the Zeta zeros current trends and historic perspective – make sure you don’t miss them! http://www.maa.org/editorial/mathgames/mathgames_10_18_04.html http://www.zetagrid.net/

Page 35: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 35 -

The program checks for X>1 and returns an OUT OF RANGE condition otherwise. Note however that the convergence for X<=2 is extremely slow, which makes it impractical to all accounts (even using the turbo mode in emulators!). Go ahead and try it, fortunately you can press any key during the calculation if you want to abort the process. Here the “RUNNING…” message is put out either during RUN and PRGM modes to indicate (or warn more appropriately) that the calculation is in progress.

Note that we preserve the value en Y because the mainframe routine [XY_TO_X] makes use of both X and Y to calculate the power result. The original content will be restored at the end of the calculation – assuming of course the execution is not aborted. Fortunately there’s no need to have any other temporary values saved, so the scratch register 9(Q) can hold this value until the end of the calculations. Otherwise we would’ve needed to sacrifice part of the Alpha register for this task.

Page 36: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 36 -

The next section deals with the summation loop, carried along until the contribution of the new term is negligible to the partial sum result so far. Here is where the instruction ?KEY has been added as a back-door to terminate things when out of control.

The last part combines the summation result with the Dirichlet term, making the division after calculating the power of two using [XY_TO_X] one more time. Note the use of ST=0 to clear the status flags prior to calling it as a way to ensure correct results when using ZETA in SST-mode (due to the conflicting uses of CPU F4).

Page 37: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 37 -

The simple FOCAL program on the left extends the ZETA function to values in the negative real axis as well, using the analytical continuation. Note the combination of both GAMMA and ZETA functions, synthetic as it gets thanks to the SandMath function collection – yet don’t expect lightening fast performance!

Page 38: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 38 -

5. Lambert W function. The last section in this mini-paper deals with the implementation of the Lambert W function. Oddly enough its definition is typically given as the inverse of another function, as opposed to having a direct expression. This makes it a bit backwards-looking initially but in fact it is significantly easier to implement than the Riemann Zeta seen before. The Lambert W function, named after Johann Heinrich Lambert, also called the Omega function or product log, is the inverse function of f(w) = w exp(w) where exp(w) is the natural exponential function and w is any complex number. The function is denoted here by W.

For every complex number z:

The Lambert W function cannot be expressed in terms of elementary functions. It is useful in combinatory, for instance in the enumeration of trees. It can be used to solve various equations involving exponentials and also occurs in the solution of delay differential equations.

The Taylor series of W0 around 0 can be found using the Lagrange inversion theorem and is given by:

where n! is a factorial. However, this series oscillates between ever larger positive and negative values for real z>~0.4, and so cannot be used for practical numerical computation. The W function may be approximated using Newton's method, with successive approximations to w = W(z) (so z = w ew) being:

The implementation in the SandMath uses the iterative method to solve for W(z) the roots of its functional equation, given the functions argument z. We’ll use SOLVE in the Advantage Pack to obtain the given roots, thus the only consideration to have is the selection of the initial estimations. For that the general practice is to start with Ln(x) as lower limit, and 1+Ln(x) as upper value. In terms of the program listing, it’s a short code that quickly defines the initial guesses and the function to solve for its roots. Very simple indeed, with execution times relatively short given its well-suited character for the Newton method that yields fast convergence.

Page 39: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 39 -

Note the OUT of RANGE check performed, as well as the fact that it’s implemented as a pseudo-MCODE function despite being written in FOCAL.

Page 40: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 40 -

The alternative listing below uses the Taylor expansion, and is given as an example programming exercise but it’s not included in the SandMath module for obvious reasons.

And here’s a glorious plot in the Complex domain to end up with a splash.-

Page 41: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 41 -

Appendix 1.- Hyperbolic Functions Launcher. The following MCODE listing shows how things work behind the scenes:

Page 42: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 42 -

Note the use of CPU F11 to differentiate between the direct and the inverse functions, and the [WAYOUT] section also used by the other launchers within the SandMath to terminate the Partial Entry sequence and transfer the execution to the corresponding function. Note also the use of mainframe routine [NLTST] to check for time-out conditions in case the last input key is kept depressed, when the user has changed his/her mind about executing the action – maybe after seeing the function name shown by the Unlabeled routine used right before!

Page 43: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 43 -

Appendix 2.- Main Functions Launcher.

Page 44: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 44 -

,

Page 45: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 45 -

Somehow a pedestrian implementation, it’ll probably benefit from a well-structure function table and other programming subtleties – yet it does its job very well and there’s so much more to dwell on that it’s hard to spend much time in just embellishing this one. The [NULL] provides feedback to the user when canceling the launcher, in case (s)he’s changed his/her mind about executing the function. It uses the mainframe routine [MSGA], and it’s listed here:

(*) The first three lines belong to the Extended RCL implementation, also covered in another article independently of the Special Functions. The following table shows the detailed key map for all the possible key combinations involving the function launchers, including the extended RCL functionality included in the SandMath.

Page 46: Special Functions on the 41 Using the SandMath …hp41.claughan.com/file/SpecialFunctions.pdfSpecial functions on the 41 - Using the SandMath module. ... The Hyperbolic tangent has

Special functions on the 41 - Using the SandMath module.

© Ángel Martin – February 2010 - 46 -

Function Launchers Key table.