Sat, Apr
5 New Articles

RPG Building Blocks

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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 hasn’t 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 didn’t 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 isn’t published here. However, you can download it from MC’s 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. It’s 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, there’s almost no chance to use floating- point variables, so I’ll 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.” Here’s 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 won’t get the original number in most cases. Maybe you’ll get
1.00000000001, or maybe you’ll 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 point’s 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, I’m 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 you’re 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. I’ll 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 statement’s 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 that’s 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. Here’s 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 consistency’s 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:


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.

Figure 1: Functions available from the MATH service program

RPG_Building_Blocks505-00.png 891x954


Support MC Press Online

$0.00 Raised:

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: