Beginning with V3R7, RPG IV programs can evaluate complicated mathematical functions by calling bindable APIs. This article presents a service program, MATH, that takes the pain out of this activity.
Since its beginnings, RPG has offered just a few meager mathematical operations and functions. In fact, besides the four arithmetical operations and the square root, there hasnt been anything at all. Some time ago, IBM created bindable math APIs that would enable languages with poor built-in support for math, like RPG, access to such transcendental functions as trigonometric, hyperbolic, and logarithmic. The problem was that, in order to be truly useful, these APIs required floating-point support, and RPG didnt have that either.
With V3R7, floating point finally arrived. As a result, we can use the math APIs when we need their capabilities. Thinking along those lines, I decided to create a service program containing a series of functions. I named this program MATH. (Because of space constraints, this program isnt published here. However, you can download it from MCs Web site at http://www.midrangecomputing.com/code.)
RPG Is Function Rich!
The table in Figure 1 lists all the functions I have made available to RPG IV. The table shows the name and a brief description of the function as well as the necessary syntax and the name of the API that I used to perform it.
As you can see in the third column, virtually all functions use floating-point arguments and return floating-point results. The reason for this is simple: Most math functions are meant to return a result that may be very small in some cases and very large in other cases. If I had designed the functions with a packed-decimal format in mind, the functions would have been of limited value.
For instance, consider the FACT (factorial) function. FACT is meant to compute probability and return numbers that escalate in magnitude exponentially. FACT(3), for instance, is only 6, but FACT(4) is already 24. And FACT(150) is approximately equal to the digit 5 followed by 262 zeros. RPG supports packed-decimal variables of up to 30 digits, but FACT(150) has 263 of them.
Consider, too, the EXP (exponentiation, base e) function. EXP yields very large results as its argument increases and yields results very close to zero as its argument decreases toward negative infinity. The 30 digits available in packed-decimal variables would not have been enough to hold a number such as the result of EXP(-100). That result is 0.000...00372, with 43 zeros between the decimal point and the digit 3.
Floating point solves this problem. Its not 100 percent accurate, like packed decimal, but, on the other hand, it copes quite well with numbers of a wide range of magnitudes.
Dealing with Floating Point
In day-to-day business data processing, theres almost no chance to use floating- point variables, so Ill assume you know little or nothing about them. This section will explain the basics you need to know without delving into the internal-bit representation of such variables.
Floating-point variables consist of two numbers: a mantissa and an exponent. The mantissa is a number with one digit to the left of the decimal point and a string of digits to the right. A number such as p (pi), which is approximately 3.14159265358979, is a good example of what the mantissa of a floating-point variable looks like. The exponent is a whole number that indicates to which power of 10 one must multiply the mantissa in order to get the value of the floating-point number. The two pieces of the floating-point number are separated by the letter E, which stands for exponent. Heres an example:
1.77607 E 3 = 1.77607 x 103 = 1.77607 x 1,000 = 1,776.07
Both the mantissa and the exponent can be negative. If the mantissa is negative, the entire floating-point number is negative. If the exponent is negative, you get to divide by a power of 10 instead of multiplying. For example:
2.5 E-6 = 2.5
÷ 106 = 2.5
÷ 1,000,000 = 0.0000025
However, floating point has two disadvantages: It is somewhat slower than packed decimal (especially on CISC machines), and it is not as accurate. If you divide 1 by 10 using packed-decimal variables, you get a precise answer, 0.1. You can then multiply this answer by 10 and get back your original number, 1. If you perform this sort of thing using floating point, you wont get the original number in most cases. Maybe youll get
1.00000000001, or maybe youll get 0.999999999. This inexactitude brings back memories of the early Pentium chips, except that the bug in those chips delivered errors several orders of magnitude greater than AS/400 floating point does. Also, you should know that floating points inaccuracy is inherent, not the result of any design flaws on the AS/400 or its programming languages. If you perform the same operations on other machines, you are likely to get slightly inaccurate results there, too.
You can declare floating-point variables in your RPG IV programs using the D- specs and a data type of F. The length of the variable must be either 4 or 8 (4 for single precision, 8 for double precision). The number of decimals must be left blank since it has no meaning. In this article, Im using double-precision floating-point variables throughout. Double-precision variables have a wider range of valid values and deliver more accurate answers. You can also declare floating-point fields in the DDS of a file.
You can convert between packed decimal and floating point by way of the %FLOAT and %DEC built-in functions. %FLOAT takes a numeric value of any kind
(integer, zoned, packed, whatever) and delivers a floating-point result. %DEC delivers a packed-decimal result.
Using the Functions
These functions are meant to be used within EVAL statements. To that end, you must code a /COPY directive in your program in order to copy the prototypes for all the functions into your program. The source member name for the prototype definitions is MATH_CPY. Place this member in a source file of your choice, and then code your /COPY directive in such a way that it references the proper file and library name.
When you compile your RPG IV program, you must include BNDSRVPGM(MATH) in the Create Program (CRTPGM) command. This parameter causes service program MATH to be bound to the program youre creating, thereby making it possible for the program to employ all of its functions.
In the EVALs that use the functions, code a syntax that matches the pattern found in the third column of the table in Figure 1. For example, to use the EXP function, code:
EVAL result = EXP(argument)
The argument may be given either as a literal or as a variable name. You do not have to worry about matching data types when using the functions. Both variables (one for the argument, the other for the result) can be of any type that can hold the values being used.
Three functions (FACT, RANDOM, and ROUND) use integer arguments. FACT does so because the factorial can be computed for whole numbers only.
RANDOM also uses an integer argument. ROUND has two arguments: one in floating point, the other integer. Ill explain the last two functions since they are likely to be confusing.
RANDOM produces a random number between 0 and 1, expressed in floating point. The argument (usually called the seed) can be any whole number. If you supply an argument of zero, RANDOM will use the Coordinated Universal Time (UTC) to generate a seed and then the random number.
ROUND takes a floating-point argument and rounds it to the position indicated by the second argument. The second argument is the position in which rounding is to occur. For instance, if the position is zero, rounding will occur in the units position (i.e., ROUND will yield a whole number). If the position is +3, rounding occurs in the thousands position (10+3), so a number like 42,891 is rounded to 43,000. If the position is -3, rounding occurs in the thousandths position (10-3); a number like p would be rounded to 3.142.
Finally, function XOR uses indicator arguments and delivers an indicator result. With it, you can augment the IF statements logic manipulations. IF already gives you AND, NOT, and OR. XOR (exclusive OR) is sometimes needed, however, so this function should prove useful.
You can use XOR only in V4R2 or above because it uses variables declared as type N (indicator). If your system has a version earlier than V4R2, you need to change the prototype and the procedure interface from data type N to A (character); failure to do so will prevent module MATH from compiling. You can pass character values to XOR, even if it is defined with indicator arguments.
APIs Can Have Bugs, Too
You should know that function FACT has a problem and is likely to yield nothing but error messages. The problem is not in the code of the MATH service program, but, apparently, in API CEE4SIFAC. For example, if you code an EVAL to compute FACT(6), you should get 720; instead, you get an escape message informing you that there has been a floating-point underflow, and thats that.
As this article goes to press, I am checking on this problem with IBM. I will keep you posted about its resolution, which is likely to be in the form of a PTF.
Add Your Own Functions
You can add to MATH your own functions if you need some math functions that I have not covered. For instance, I have not provided for trigonometric function cotangent, but it can be calculated using TAN. Heres what you would have to do to add cotangent:
1. Come up with a meaningful function name. If mathematicians already have a usable name, by all means employ that one. Cotangent is usually abbreviated to cot in math books, so name your function COT.
2. Determine what arguments are needed and what result the function is to yield. For consistencys sake, assume COT is to accept a floating-point argument and deliver a floating-point result.
3. Add a prototype to MATH_CPY. Using the prototype for TAN as the model, replace TAN with COT.
4. Add the function itself to MATH. Using the subprocedure TAN as the model, replace TAN with COT and replace all C-specs with an EVAL that goes like this:
EVAL result = 1 / tan(arg1)
The reason for this line is that the cotangent of an angle is equal to the reciprocal of the tangent.
5. Recompile module MATH with the Create RPG Module (CRTRPGMOD) command.
6. Refresh service program MATH with the Update Service Program (UPDSRVPGM) command:
UPDSRVPGM PGM(xxx/MATH) MODULE(xxx/MATH) EXPORT(*ALL)
So, there you have it. If your AS/400 is at V3R7 or higher, you can perform all sorts of mathematical functions in an RPG IV program. You can keep adding functions to MATH as IBM adds new math APIs.
LATEST COMMENTS
MC Press Online