02
Sat, Nov
2 New Articles

High School-Level Math in RPG IV

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

Back in the 1980s, I created a program called Partner, a productivity tool that included a calendar, a notepad, an adding machine, a command-line interceptor, and an expression analyzer. These applications popped up in different windows to provide a PC-style windowing environment. As far as I know, Partner was the first commercial 5250 application with pop-up windows.

An interesting application in that package was its expression analyzer. This component allowed users to type in a free-format mathematical expression and receive the result. You could even extend the functions by adding your own. That is, Partner did user-written procedures years before ILE was being considered by Paul Remtema and at least a decade before IBM considered adding subprocedures to RPG IV.

The types of math functions Partner was able to perform included high-level mathematical operations, such as sine, cosine, and arctangent hyperbolic. To perform these math functions in RPG, I called an MI program that used the "compute math function" and "compute math function 2" instructions.

While the Partner software continues to run and work on i5/OS more than 20 years after it was first introduced, the ability to perform high-level math continues to elude the RPG IV language even today. Or has it?

With the integration of RPG IV and ILE and the ability to call subprocedures and functions written in other programming languages, IBM has opened up RPG to extensions beyond what is officially implemented in the language.

While I've written about the C runtime library before, the math portion of the C library is intriguing. It supports a rather complete set of high-level math functions that can be utilities from within RPG IV very effectively.

By creating the prototypes for the C math runtime library and binding with the QC2LE binding directory, any high-level math function can be utilized from within RPG.

For example, to calculate the sine of a number, you could use the following:

     H BNDDIR('QC2LE')
     D sin             PR             8F   extProc('sin') 
     D   radians                      8F   Const 
     D mySine          S             11P 9

      /free
          mySine = sin(.05);
      /end-free

Aside from the lack of a leading percent sign (%), these math functions, like all C runtime library functions, work much like built-in functions.

The C math functions have a more programmer-friendly parameter list than the set of CEExxxx math APIs; however, one or two more math functions are available using the APIs.

To illustrate, I've repeated the call to the sine function below, using the API convention. The API name to calculate a sine is CEESDSIN.

 

    D sin             PR                  extProc('CEESDSIN')
     D  fInput                        8F   Const 
     D  fOutput                       8F
     D  apiErrorDS                         LikeDS(QUSEC)
     D                                     OPTIONS(*VARSIZE:*OMIT)

     D fSine           S              8F
     D mySine          S             11P 9

      /free
          callp sin(.05: mySine : *OMIT );
          mySine = fSine;
      /end-free

 

A few differences exist between the C runtime math library and the i5/OS math APIs.

  • The binding directory QC2LE is not required for the CEExxxx APIs (it is required for the C runtime library functions).
  • The C functions return their results via a return value, whereas the APIs require a second parameter to receive the result of the operation.
  • The APIs accept the standardized API error data structure to trap errors; the C functions do not.

The CEExxxx APIs have more flexibility and more choices than the C math functions library, and certainly those additional features are important to compiler writers. But the C functions are much easier to use and should probably be the choice people make when selecting high-level math functions.

As with all CEExxxx APIs, the math APIs' object code is embedded directly into the generated *MODULE object. That is, although a call to the API is coded by the programmer, the compile "inlines" the object code of the API rather than inserting a subprocedure call. This occurs with any API that is prefixed with the letters "CEE" or an underscore (_) .

In my upcoming book RPG TNT: 101 Dynamite Tips and Techniques for RPG IV Programmers, the prototypes for all CEExxxx math APIs as well as the C math functions are included. For space purposes in this article, I've included only the prototypes for the C runtime library math functions below.

High-level mathematical function prototypes:

      /IF NOT DEFINED(C_MATH_PROTOS)
      /DEFINE C_MATH_PROTOS
      **********************************************
      **  From "RPG TNT: 101 Tips and Techniques"
      **  © 2006 by Robert Cozzi, Jr.
      **********************************************
     D acos            PR             8F   extProc('acos')       
     D   radians                      8F   Const           

     D asin            PR             8F   extProc('asin')        
     D   radians                      8F   Const             

     D atan            PR             8F   extProc('atan')       
     D   radians                      8F   Const
                                
     D atan2           PR             8F   extProc('atan2')    
     D   radians1                     8F   Const       
     D   radians2                     8F   Const        

     D ceil            PR             8F   extProc('ceil')       
     D   radians                      8F   Const       

     D cos             PR             8F   extProc('cos')    
     D   radians                      8F   Const      

     D cosh            PR             8F   extProc('cosh')
     D   radians                      8F   Const               

     D exp             PR             8F   extProc('exp')         
     D   radians                      8F   Const           

     D floor           PR             8F   extProc('floor')    
     D   radians                      8F   Const            

     D fmod            PR             8F   extProc('fmod')      
     D   arg1                         8F   Const       
     D   arg2                         8F   Const       
         
     D log             PR             8F   extProc('log')  
     D   radians                      8F   Const 

     D log10           PR             8F   extProc('log10')       
     D   radians                      8F   Const          

     D pow             PR             8F   extProc('pow')
     D**  pow(x:y) = x**Y
     D   x                            8F   Const        
     D   y                            8F   Const         

     D sin             PR             8F   extProc('sin')  
     D   radians                      8F   Const      

     D sinh            PR             8F   extProc('sinh')  
     D   radians                      8F   Const          

     D sqrt            PR             8F   extProc('sqrt')  
     D   radians                      8F   Const       

     D tan             PR             8F   extProc('tan') 
     D   radians                      8F   Const      

     D tanh            PR             8F   extProc('tanh') 
     D   radians                      8F   Const           

     D erf             PR             8F   extProc('erf')
     D   radians                      8F   Const       

     D erfc            PR             8F   extProc('erfc')
     D   radians                      8F   Const       

     D gamma           PR             8F   extProc('gamma')
     D   radians                      8F   Const        

     D hypot           PR             8F   extProc('hypot')
     D   side1                        8F   Const    
     D   side2                        8F   Const    

      /IF DEFINED(BESSEL_FUNC)
      /IF NOT DEFINED(BESSEL_MATH)
      /DEFINE BESSEL_MATH
      **  Bessel functions, first order
     D j0              PR             8F   extProc('j0')      
     D   x                            8F   Const        
     D j1              PR             8F   extProc('j1')       
     D   x                            8F   Const      
     D jn              PR             8F   extProc('jn')        
     D   n                           10I 0 Const       
     D   x                            8F   Const        

      **  Bessel functions, second order
     D y0              PR             8F   extProc('y0')      
     D   x                            8F   Const     
     D y1              PR             8F   extProc('y1')        
     D   x                            8F   Const     
     D yn              PR             8F   extProc('yn')      
     D   n                           10I 0 Const      
     D   x                            8F   Const     
      /ENDIF
      /ENDIF

      /ENDIF      

 

 

 

Bob Cozzi is a programmer/consultant, writer/author, and software developer of the RPG xTools, a popular add-on subprocedure library for RPG IV. His book The Modern RPG Language has been the most widely used RPG programming book for nearly two decades. He, along with others, speaks at and runs the highly-popular RPG World conference for RPG programmers.

 

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

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: