RPG Arithmetic Limitations
From: George Konley
To: All
Does anyone know if RPG code that handles exponents is available? I have a formula that requires exponents and I would think that others have run into the same problem. COBOL can handle exponents; I would assume some ingenious RPG programmer has developed a subroutine or program that would handle this requirement. Does anyone have any ideas on this?
From: Ernie Malaga
To: George Konley
For integer exponents (such as 4512), you can use the code in 4.
For integer exponents (such as 4512), you can use the code in Figure 4.
NUMBER is the base number (like 45 in this example), EXPON is the exponent (the 12), and POWER holds the result. I've used a 30-digit, 0-decimal Result field, but you can use a different size/precision.
This technique can be coded in a callable program with three parameters: NUMBER, EXPON and POWER, if you prefer to do it like that. Note the Z-ADD 1 to POWER, which initializes POWER so that the repeated MULT multiplies by NUMBER. This is because 1 is the identity value for multiplication.
If EXPON is ever to have fractional values, then you must use an entirely different approach, probably using logarithms. For example: ax = ex.ln(a) = 10x.log(a)
This means that you have to calculate the logarithm of "a" (either natural [ln] or base-10 [log], multiply it by the exponent, and then calculate the antilogarithm of the result. If you used natural logarithms, use natural antilogarithms (ex), etc.
Unfortunately, RPG has no LN or LOG op code or any other simple way of calculating them. You could have a database file with a table of logarithms, or perhaps you can calculate the logarithms indirectly by a series process. I don't know much about the series process since I never went very far in high math, but I know it's possible-although I suspect it's also time-consuming.
TechTalk: RPG Arithmetic Limitations
Figure 4 Raising a number to an integer power
Figure 4: Raising a Number to an Integer Power ....+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 C Z-ADD1 POWER 300 C 1 DO EXPON C MULT NUMBER POWER C ENDDO
LATEST COMMENTS
MC Press Online