sams_teach_yourself_cobol_in_24_hours_-_hour_22_other_intrinsic_functions

Sams Teach Yourself COBOL in 24 Hours - Hour 22 Other Intrinsic Functions

Return to Teach Yourself COBOL in 24 Hours, COBOL bibliography, COBOL, COBOL DevOps, Awesome COBOL, Awesome IBM Mainframe, IBM Mainframe development, IBM Mainframe bibliography, Fortran

“ (TYCb24H 1998)

Hour 22 Other Intrinsic Functions

In Hour 21, “Date Manipulation,” you learned about the Intrinsic Functions associated with date processing. In addition to these functions, COBOL comes equipped with a wealth of additional Intrinsic Functions that fill the need for a variety of items such as

• Mathematical and statistical Functions

• Financial application Functions

• String manipulation Functions

• Miscellaneous Functions such as random number generation

These functions bring features to COBOL that, prior to their introduction in 1989, had to be designed and coded by programmers, sometimes using complex algorithms. Many of these functions can help make programming much easier for the COBOL programmer.

Mathematical Functions The first subset of Functions relates to trigonometric Functions. These Functions can be used for calculations normally reserved for scientific programming languages such as FORTRAN. Many governments and universities rely on COBOL as their main programming language. Having these Functions available from COBOL means that these institutions don’t have to develop these processes in other programming languages.

Image

The trigonometric Functions and the square root Function are approximations. Different compilers can produce different results for these Functions.

Image

Explaining trigonometric Functions is beyond the scope of this book. However, this section does explain the values returned and the methods used to obtain those values.

Each trigonometric Function accepts a single argument, which is specified within parentheses following the Function name. These Functions are

• Cosine

Function Cos

• Sin

Function Sin

• Tangent

Function Tan

• Arcsin

Function Asin

• Arccosine

Function Acos

• Arctangent

Function Atan

The Cosine Function returns a numeric value in the range of plus or minus 1. As with all numeric Intrinsic Functions, the value is returned by using the Function in an arithmetic statement such as Compute. The argument used with the Cos Function must be numeric and is specified in radians. For example, to find the cosine of .785 radians, you code the following:

000100 Compute The-Cosine = Function Cos (.785) The value returned is .707388269.

Because the argument is in radians, you might need to convert an angle to radians. You may approximate the radians with the following Compute statement (pi is approximated and is the value that is divided by 180):

000101 Compute Radians = Angle * (3.14159265358979324 / 180) The Sin Function returns a numeric value in the range of plus or minus 1 that approximates the value of the Sin of the argument. As with Cosine, the argument value is specified in radians. To find the Sin of .875 radians, code the following:

000102 Compute The-Sin = Function Sin (.875) The Tan Function returns a numeric value that approximates the value of the Tangent of the argument. The argument value is specified in radians. To find the Tangent of .785 radians, code the following:

000103 Compute The-Tangent = Function Tan (.785) The Asin and Acos Functions return an approximation of the ArcSin and ArcCosine of the argument. The argument must fall within the range of plus or minus 1. The value returned is in radians. To figure the Acos of .707388269, code the following:

000104 Compute The-Arc-Cosine = Function Acos (.707388269) The Atan Function returns an approximation of the ArcTangent of the specified argument. The value is returned in radians.

Two different logarithm Functions are provided. These numeric Functions accept a single numeric argument. The Log Function returns an approximation of the natural logarithm of the specified argument. The Log10 Function returns an approximation of logarithm to base 10 of the argument. The argument must be a positive number.

You can use the Factorial Function to find the factorial of an argument. The argument specified must be either zero or a positive integer. When the argument specified is zero, a value of 1 is returned from the Function; otherwise, the factorial is returned. Make sure that the numeric field you are computing the result into is large enough to contain the value. To compute the factorial of 7, code the following:

000105 Compute The-Factorial = Function Factorial (7) Image

The examples thus far have used numeric literals as the arguments for the Functions. You may also use any numeric data item defined in the Data Division of your COBOL program.

The Sqrt Function approximates the square root of the argument. For example, if you have a number stored in Numeric-Field and you want to determine its square root, you may code the following:

000106 Compute Square-Root = Function Sqrt (Numeric-Field) COBOL has two Functions that can find the integer portion of a numeric field. The two Functions differ in how they handle negative numbers. The first Function, Integer-Part, returns the integer portion of the argument. For example:

000107 Compute The-Integer-Part = Function Integer-Part (-1.9) returns negative 1 in The-Integer-Part. Any decimal positions are removed.

If the argument were 1.9, the value returned would be 1.

The sister Function, Integer, returns the greatest integer value that is less than or equal to the argument. With Integer, the example

000108 Compute The-Integer-Part = Function Integer (-1.9) returns a value of negative 2. Negative 2 is the greatest integer value that is less than or equal to negative 1.9. For positive numbers, the two Functions, Integer-Part and Integer, return the same result.

In Hour 21, you learned about the Rem Function. This Function returns the remainder of the first argument divided by the second. You may be interested to know that the actual calculation performed to return this value is

000109 Compute Remainder = First-Argument _ 000110 (Second-Argument * 000111 Function Integer-Part (First-Argument/Second-Argument)) A Function that is very similar to Rem, and often used erroneously instead, is Mod. Mod accepts two arguments, and returns an integer that is the value of the first argument using the second argument as the modulus. For positive numbers, the value returned is the same as that of Rem. However, when negative numbers are involved, the values returned by Mod and Rem differ because of the slight variation in the calculation used to arrive at the Mod result. The calculation for Mod uses Integer rather than Integer-Part.

000112 Compute Mod-Value = First-Argument _ 000113 (Second-Argument * 000114 Function Integer (First-Argument/Second-Argument)) To find 14 modulus 7, the statement is coded as follows:

000115 Compute Mod-Value = Function Mod (14 7)

The COBOL Intrinsic Functions are rich in statistical analysis tools. There are Functions for Max, Min, Mean, Median, Midrange, Range, Sum, Variance, and Standard-Deviation. Two related Functions are Ord-Max and Ord-Min.

Statistical Functions The Function Max returns the maximum value from a list of arguments. For example, if you have three numeric fields—Field-1, Field-2, and Field-3—you can determine the minimum value stored in the fields.

Image

For this section, only numeric values are discussed with the statistical Functions. Many of these Functions accept alphanumeric arguments. Alphanumeric argument values are covered in the upcoming “String Functions” section.

000116 Compute Max-Value = Function Max (Field-1 Field-2 Field-3) Similarly, the Min Function returns the minimum value of the arguments specified for the Function.

Ord-Max and Ord-Min are related to Max and Min. Instead of returning the highest or lowest value, Ord-Max and Ord-Min return the relative position of the argument in the list that contains the highest or lowest value. Table 22.1 shows the various values returned from Max, Min, Ord-Max, and Ord-Min when Field-1 is 10, Field-2 is 30, and Field-3 is 15.

Table 22.1 Values Returned by Functions Max, Min, Ord-Max, and Ord-Min

Image

The Functions Mean and Midrange are closely related. Both Functions return numeric values. The Mean Function returns the average value of all of the arguments specified for the Function. The Midrange Function returns the average value of the highest and lowest argument values. Arguments are specified just as for the Max Function.

The Median Function sorts the values of the arguments and returns the value of the argument that is in the middle of the sorted list. If Field-1 has a value of 3, Field-2 has a value of 300 and Field-3 has a value of 10, the following code returns a value of 10:

000117 Compute The-Median = Function Median (Field-1 Field-2 Field-3) If the three fields are arranged in sorted order, the middle value is 10.

The Range Function returns the range of numbers involved in the argument list. The Function returns a number that is the difference between the highest and lowest value in the argument list. If you have arguments where the lowest value is 10 and the highest value is 20, the range is 10.

The Sum Function adds all the arguments specified together and reports that result. The following two lines of code produce identical results:

000118 Compute The-Result = Function Sum (Field-1 Field-2 Field-3) 000119 Add Field-1, Field-2, Field-3 Giving The-Result The Standard-Deviation Function returns an approximation of the standard deviation of the arguments. If all the arguments have the same value, 0 is returned; otherwise, the algorithm is fairly involved. First, the mean of the arguments is calculated. Then the square of the difference between the mean and each argument is summed. This sum is divided by the number of arguments and the absolute value of the square root is the result.

The Variance Function returns a numeric value that approximates the variance between the list of arguments specified. It is simply the square of the standard deviation of the list of arguments.

These Functions can be very useful in statistical calculations. Prior to the introduction of these Functions, the COBOL programmer had to write the lines of code necessary to complete these often-complex calculations. If the number of arguments changed, the program required significant modification. These Intrinsic Functions make for much easier program maintenance.

In addition to accepting a list of data items, you might have a set of items that vary in number. Sometimes you might need to calculate the Min of three numbers and other times the Min of five numbers. Obviously, you don’t want to have to code two different Functions for this purpose.

The statistical Functions, Max, Min, Ord-Max, Ord-Min, Mean, Median, Midrange, Standard-Deviation, Sum, and Variance, accept a table as the argument. The Elementary Level of the table must be specified. If the entire table is to be processed, the subscript specified is the word All. By using a variable-length table defined with the Depending On clause, you can process a variable number of items with these Functions. For example, you might have the following table defined:

000011 01 Work-Table. 000012 03 Work-Entry Pic 9(3) Occurs 1 To 20 Times 000013 Depending On Num-Entries. 000014 01 Num-Entries Pic 9(3) Value 3. Assume that the first element of the table is equal to 5, the second is equal to 20, and the third 10. The following line finds the minimum value in the table:

Compute Result = Function Min (Work-Entry (All)) When a Function Ord-Min or Ord-Max is used with a table, the element that is the Min or the Max is returned. Function Ord-Min provides a simple method to find the element of the table that contains the lowest value.

Financial Functions Financial institutions are heavy users of COBOL. Many different financial algorithms have been coded in COBOL over the years. Two of these are now available as Intrinsic Functions: Annuity and Present-Value.

The Annuity Function returns the approximate value of the ratio of an annuity paid at the end of each period for the number of periods specified to an initial investment of 1. The number of periods is specified in the second argument. The rate of interest is specified by the first argument, and is applied at the end of the period, before payment. The actual calculation is

When Argument-1 (interest rate) is 0, the value is 1/Argument-2.

When Argument-1 is not 0, the value is Argument-1/(1 - (1 + Argument-1) ** (-Argument-2)). (Remember that ** specifies an exponent).

You can use the Annuity Function to calculate a monthly payment on a loan, as shown in Listing 22.1.

Listing 22.1 Demonstrate the Annuity Function

000001 @OPTIONS MAIN,TEST 000002 Identification Division. 000003 Program-Id. Chapt22b. 000004* Annuity Example 000005 Environment Division. 000006 Configuration Section. 000007 Source-Computer. IBM-PC. 000008 Object-Computer. IBM-PC. 000009 Data Division. 000010 Working-Storage Section. 000011 01 Loan-Amt Pic 9(6)v99 Value Zeros. 000012 01 Interest-Rate Pic 9(3)v99 Value Zeros. 000013 01 Loan-Years Pic 9(3) Value Zeros. 000014 01 Payment-Amt Pic 9(6)v99 Value Zeros. 000015 01 Monthly-Interest Pic 9(3)v9(9) Value Zeros. 000016 Screen Section. 000017 01 Data-Entry Blank Screen Auto. 000018 03 Line 01 Column 01 Value “Enter Principal: “. 000019 03 Line 01 Column 18 Pic Z(6).99 Using Loan-Amt. 000020 03 Line 03 Column 1 Value “Enter Interest Rate: “. 000021 03 Line 03 Column 22 Pic Z(2)9.99 Using Interest-Rate. 000022 03 Line 04 Column 1 Value “Number of Years of Loan: “. 000023 03 Line 04 Column 26 Pic ZZ9 Using Loan-Years. 000024 03 Line 06 Column 1 Value “Monthly Payment: “. 000025 03 Line 06 Column 18 Pic Z(3),Z(3).99 From Payment-Amt. 000026 Procedure Division. 000027 Chapt22b-Start. 000028 Display Data-Entry 000029 Accept Data-Entry 000030 Compute Monthly-Interest Rounded = (Interest-Rate / 12) / 100 000031 Compute Payment-Amt Rounded = Loan-Amt * 000032 Function Annuity (Monthly-Interest, Loan-Years * 12) 000033 Display Data-Entry 000034 Stop Run 000035 . Before the calculation can occur, all the variables must have the same relationship. Since the monthly payment is to be determined, all items are changed into their monthly equivalents. In line 30, the interest rate is divided by 12 to give the monthly interest rate. It is again divided by 100 because the Annuity Function accepts the rate as a positive value and actual rate. When someone says the interest rate of 7.25, he or she means 7.25%, which is an actual rate of .0725. To keep data entry simple for the user, the rate is accepted at the percentage level and then changed to an actual rate.

In lines 31 and 32, where the Annuity Function is used, the number of years of the loan is multiplied by 12 to find the number of months of the loan. You do not have to calculate this value outside the Function. The value is determined as part of the Function calculation.

The other financial Function is Present-Value. Present-Value is the number that the principal must be to achieve a certain goal value at the end of the period for the specified interest rate. It is used frequently in bond calculation to determine the initial purchase price of a bond. Generally, bonds return a fixed specified rate of return monthly before paying back a specified principal. When deciding whether a bond is worthwhile, the buyer has to consider what kind of return he or she could make on the investment at a fixed interest rate. Consider the following example: If you give me a certain amount of money now, I will give you $1,000.00 at the end of the year. If you can earn 5% on your money right now, what is the present value of the $1,000.00 I will give you in the future?

The Function to compute this amount is

000100 Compute Result = Function Present-Value (.05 1000) The value returned is $952.38. If I want you to give me any more than this amount, then the deal is not lucrative for you. You could make more money placing the money in a regular certificate of deposit.

Consider a more realistic investment situation. If you were to put $100 a year into an investment fund for 20 years at a rate of return of 4.5%, what is the present value of that money? In other words, what would you have to invest now as a single value to have the same amount of money at the end of 20 years? Considering the $100 every year for 20 years, you would put in a total of $2,000. How much would you have to put in today as a lump sum to achieve the same net value after 20 years?

One way to code the problem is

000017 Compute Result = Function Present-Value (.045, 000018 100, 100, 100, 100, 100 000019 100, 100, 100, 100, 100 000020 100, 100, 100, 100, 100 000021 100, 100, 100, 100, 100) This methods appears cumbersome. The Present-Value Function accepts a table as an argument. Instead of coding the problem as shown, you can create a table and populate it with $100.00 in each element. The Function could then be simplified to

000022 Compute Result = 000023 Function Present-Value (.045, Value-Element (All)) Interestingly, rather than put away $100.00 a year for 20 years, you could start with $1,300.79 and reach the same net value at maturity.

String Functions Several Intrinsic Functions can be used in string processing. Some of these Functions were described for numeric usage, but can also be used with alphanumeric arguments for string processing. The Functions related to working with strings are Length, Min, Max, Ord-Min, Ord-Max, Char, Ord, Upper-Case, Lower-Case, Reverse, Numval, and Numval-C.

The Length Function returns a numeric value that corresponds to the length of the argument. It may seem to have limited value, but actually the Function can be quite valuable. For instance, you might have a routine that centers a field. The method used might count backward from the end until a character greater than spaces is encountered. Then using that count, divide it in half and shift the field over to the right by that amount. Coding the program for a particular field is quite easy. But what if you want to reuse the code in another program with a different field length? You would have to change the routine for that field length. Instead, you could use the Length Function in the routine to determine the field length and never have to change the routine to use it in new programs.

Consider the program in Listing 22.2 for this purpose.

Listing 22.2 Center a Field

000001 @OPTIONS MAIN,TEST 000002 Identification Division. 000003 Program-Id. Chapt22d. 000004* Center A String 000005 Environment Division. 000006 Configuration Section. 000007 Source-Computer. IBM-PC. 000008 Object-Computer. IBM-PC. 000009 Data Division. 000010 Working-Storage Section. 000011 01 String-Length Pic 9(6) Value Zeros. 000012 01 Counter Pic 9(6) Value Zeros. 000013 01 String-To-Center Pic X(60) Value 000014 “Teach Yourself COBOL in 24 Hours”. 000015 01 Centered-String Pic X(60) Value Spaces. 000016 Procedure Division. 000017 Chapt22d-Start. 000018 If String-To-Center > Spaces 000019 Compute String-Length = 000020 Function Length (String-To-Center) 000021 Perform Varying Counter From 000022 String-Length By -1 Until 000023 String-To-Center (Counter:1) > Spaces 000024 Continue 000025 End-Perform 000026 Compute Counter Rounded = (String-Length - Counter) / 2 000027 Move String-To-Center To 000028 Centered-String (Counter:) 000029 End-If 000030 Display “Centered-String=” Centered-String 000031 Stop Run. 000032 . First, notice that the centering attempt is not made unless the field contains some data. Then the length of the field is calculated using the Length Function.

Image

Some people think the Length Function returns the number of characters in a field less the trailing blanks. This is not the case. Even if the field contains spaces, the Length Function returns the full field defined length.

If you need to change the size of the field to be centered, simply modify the two fields in Working-Storage, String-To-Center and Centered-String, to have a new length. Because you are using the Length Function to find this field length, nothing else in the program needs to change.

Another use for the Length Function is to return the actual length of a variable-length table. When you use the Function with a table, the actual used length is returned. For example, if your table is defined as

000011 01 Variable-Table. 000012 03 Table-Items Occurs 1 To 500 Times 000013 Depending On Table-Occurrences. 000014 05 Table-Element Pic 9(3). 000015 01 Table-Occurrences Pic 9(3) Value 237. You can determine the actual utilized length of the table using the Length Function as follows:

000019 Compute Item-Length = Function Length (Variable-Table) The Min, Max, Ord-Min, and Ord-Max Functions work with alphanumeric data items in the same way that they work with numeric items. You can use the Min and Max Functions to find the minimum and maximum values in a series of strings stored in a table. Or you can use Ord-Max and Ord-Min to determine which elements of a table have the greatest and least value.

The Char Function accepts a numeric argument and returns the character that corresponds with that numeric value in the collating sequence in use by the program. For example, if the following statement is executed, the letter “X” is returned.

000016 Move Function Char (89) to Character-Returned The converse Function is the Ord Function. When passed a character, the Ord Function returns the numeric position of the character in the computer’s collating sequence. The following line of code returns the position in the collating sequence of the letter “Q”.

000017 Compute Position-Returned = Function Ord (“Q”) Image

Obviously, these Functions do not have to be used with numeric and alphanumeric literals. You could use these Functions with data items as the arguments of the Functions—for example, Function Ord (Character-Item). However, with the Ord Function only a single character field is valid.

The Upper-Case Function converts an alphanumeric data item to uppercase. The argument can be any Elementary or Group Level alphanumeric data item. Each character within the field is converted to all capital letters.

000018 Move Function Upper-Case (Input-Field) To Output-Field A related Function, Lower-Case, converts a data item to all lowercase characters.

000019 Move Function Lower-Case (Input-Field) To Output-Field A very interesting and useful Function is the Reverse Function. The Reverse Function reverses the order of the characters in the argument. For example, your program might contain the following Working-Storage entries:

000010 01 Input-Field Pic X(15) Value “COBOL”. 000011 01 Output-Field Pic X(15) Value Spaces. If you code the following:

000025 Move Function Reverse (Input-Field) To Output-Field Output-Field will contain “ LOBOC”. You may be asking yourself how you can use this Function. In Hour 7, “Manipulating String Data,” you used the String statement to construct a full name from a first, middle, and last name. A difficulty arose when the first name field had more than one name. Names such as Daisy Mae were not correctly used in the full name, as Delimited By Space was coded with the String statement. One way to correct this problem is to know the name within the name field. For example, the name field might be defined as Pic X(25), and “Daisy Mae” might be the value of the field. In this case, the field length is 25, but the name within the field is 9 characters long.

The Inspect statement enables you to easily determine the number of leading spaces, but determining the number of trailing spaces is not so easy. The Reverse Function allows you to reverse the order of the characters in Input-Field so that what were trailing spaces become leading spaces. You may then use the Inspect statement to count the spaces.

000025 Move Function Reverse (Input-Field) To Output-Field 000026 Inspect Output-Field Tallying 000027 Trailing-Spaces For Leading Spaces The field, Trailing-Spaces, is initialized to Zero in Working-Storage.

You can use this technique, along with the Length Function, to properly assemble names regardless of the various field lengths as shown in Listing 22.3.

Listing 22.3 Assemble First and Last Name Into a Full Name

000001 @OPTIONS MAIN,TEST 000002 Identification Division. 000003 Program-Id. Chapt22h. 000004*Assemble Full Name From First And Last 000005 Environment Division. 000006 Configuration Section. 000007 Source-Computer. IBM-PC. 000008 Object-Computer. IBM-PC. 000009 Data Division. 000010 Working-Storage Section. 000011 01 First-Name Pic X(15) Value Spaces. 000012 01 Last-Name Pic X(25) Value Spaces. 000013 01 Work-Field Pic X(15) Value Spaces. 000014 01 Full-Name Pic X(51) Value Spaces. 000015 01 Trailing-Spaces Pic 9(3) Value Zeros. 000016 01 Field-Length Pic 9(3) Value Zeros. 000017 Screen Section. 000018 01 Data-Entry Blank Screen Auto. 000019 03 Line 01 Column 1 Value “First Name: “. 000020 03 Line 01 Column 13 Pic X(15) Using First-Name. 000021 03 Line 03 Column 1 Value “Last Name: “. 000022 03 Line 03 Column 13 Pic X(25) Using Last-Name. 000023 03 Line 06 Column 1 Value “Full Name: “. 000024 03 Line 06 Column 13 Pic X(51) From Full-Name. 000025 Procedure Division. 000026 Chapt22h-Start. 000027 Display Data-Entry 000028 Accept Data-Entry 000029 Move Function Reverse (First-Name) To Work-Field 000030 Inspect Work-Field Tallying Trailing-Spaces For 000031 Leading Spaces 000032 Compute Field-Length = Function Length (First-Name) 000033 String First-Name (1:Field-Length - Trailing-Spaces) 000034 “ “ 000035 Last-Name 000036 Delimited By Size, Into Full-Name 000037 Display Data-Entry 000038 Stop Run 000039 . Lines 29 through 31 determine the number of trailing spaces. Line 32 determines the full length of the input field. The difference between these two fields is used with the String statement for assembling the name.

On occasion, you may need to read input data prepared by another system or programming language. As is often the case, the numeric fields passed to you by these systems are edited fields. That is, instead of numbers such as 0001000, the numbers are passed as 10.00 or “ 10.00”. You can spend quite some time creating a complex routine using String and Unstring statements, along with Inspect, to return this field to a proper numeric value. Fortunately, COBOL provides a much simpler method of converting these edited fields back into numbers.

Two related Functions handle this type of data conversion. These are Numval and Numval-C. When passed a valid edited numeric field, Numval returns a numeric value that is equal to the numeric value of the input field. Numval cannot handle input with currency symbols, commas, CR, or DB. Numval is simply coded as shown here:

000025 Compute Converted-Value = Function Numval (Field-To-Convert) Numval-C accepts a second argument, which is the currency symbol to expect in the input field. If this argument is omitted, the currency symbol for the current character set is used. In addition to handling the currency, Numval-C handles embedded commas and the CR and DB characters that might appear at the end of a numeric edited field.

000026 Compute Converted-Value = 000027 Function Numval-C (Field-To-Convert “$”) Image

If Numval-C is so much more capable than Numval, you may wonder why you would ever want to use Numval. Because Numval-C can handle many more types of input characters, it has to do more work and is therefore slower. Normally, you want the best performance possible from your programs. If the fields you are converting to numbers do not have commas or currency, you will see faster results by using Numval instead of Numval-C.

Miscellaneous Functions The two remaining Intrinsic Functions are When-Compiled and Random. The When-Compiled Function returns the date and time the program was compiled. The format of the value returned is the same as that of the Current-Date Function. This Function can be useful on a multiuser or complex environment to make sure the version of the program being executed is the one you think it is. The following code displays the compilation date of a program:

000100 Display Function When-Compiled (1:8) The Random Function returns a pseudo-random value that is less than one but greater than or equal to zero. The value is not truly random, but is a good approximation. The Function accepts a single integer argument that is the “seed” value for the random number Function. If you need to reproduce a series of random numbers, simply code the Random Function with the same starting seed value. After the initial execution of the Function, the argument should be omitted. Many programmers use the time as the initial seed value when a random number is desired.

To create a valid, random, whole number from the decimal value returned by the Random Function, you must multiply the value by your maximum value and then add 1. For example, to generate a random number, (Random-Number Pic 9(3)) between 1 and 500, you may code the following:

000100 Compute Random-Generate = Function Random (Seed-Number) 000101 Compute Random-Number = (Random-Generate * 500) + 1 Image

You might be tempted to code a one-step process for random number generation, such as Compute Random-Number = ((Function Random (Seed-Number) * 500) + 1. If you do, the highest random number generated is 451. The reason is that the compiler bases the precision of the random generation on the size of the data items used in the Compute statement. Because Random-Number and all of the other variables used are whole numbers with no decimal positions, the largest number returned from the Random Function is .9. Obviously, .9 times 500 is 450, and 450 plus the 1 yields 451. To avoid this problem, it is best to declare a separate data item with a high level of precision for the Random Function and then do the multiplication in a separate step.

The Random Function is frequently used to generate a data file of random selections from another file. Listing 22.4 uses the time as the seed value and generates a series of random numbers between 1 and 21.

Listing 22.4 Demonstrate Random Function

000001 @OPTIONS MAIN,TEST 000002 Identification Division. 000003 Program-Id. Chapt22j. 000004*Random Function 000005 Environment Division. 000006 Configuration Section. 000007 Source-Computer. IBM-PC. 000008 Object-Computer. IBM-PC. 000009 Data Division. 000010 Working-Storage Section. 000011 01 Random-Seed Pic 9(8) Value Zeros. 000012 01 Random-Number Pic 99 Value Zeros. 000013 01 Random-Generate Pic V9(18) Value Zeros. 000014 Procedure Division. 000015 Chapt22j-Start. 000016 Move Function Current-Date (9:8) To Random-Seed 000017 Compute Random-Generate = Function Random (Random-Seed) 000018 Compute Random-Number = (Random-Generate * 21) + 1 000019 Display Random-Number 000020 Perform 19 Times 000021 Compute Random-Generate = Function Random 000022 Compute Random-Number = (Random-Generate * 21) + 1 000023 Display Random-Number 000024 End-Perform 000025 Stop Run 000026 .

Summary In this hour, you learned the following:

• That numerous useful Intrinsic Functions are available to the COBOL programmer

• How to use advanced mathematical Functions such as Sin, Cos, Tan, Log, and Log10

• How to use the different statistical Intrinsic Functions such as Max, Min, Median, Range, Midrange, and Standard-Deviation

• The purpose and use of the financial Functions, Annuity and Present-Value

• How to handle string data with the following Functions: Length, Reverse, Upper-Case, and Lower-Case

• How to determine when your program was compiled with the When-Compiled Function

• How to generate pseudorandom numbers with the Random Function

Q&A Q How closely do the trigonometric Functions approximate their real values?

A The answer depends on the compiler vendor. The approximations are very good, but may be different and accurate to different numbers of decimal positions with different compilers. You cannot count on identical answers from different compilers.

Q I want to find the standard deviation between a list of values from a data file. I don’t know how many different items there will be. How can I accomplish the task?

A You can define a variable-length table with occurrences depending on a data value that you increment for each item loaded into the table. You need to know the maximum number of items you will be handling. After the table is loaded, you may use it with the subscript (All) as the argument for the Standard-Deviation Function.

Q What can the Annuity Function help me compute?

A One thing that you can compute with the Annuity Function is the monthly payment of a fixed-rate mortgage.

Q Does the Length Function return the number of characters in a field or the field size?

A The Length Function returns the size of the field passed as an argument to the Function. The contents of the field do not figure in the calculation.

Q The Random Function returns an extremely small number. How do I use this number to calculate a larger random number?

A You multiply the small number by the maximum number you want to generate and then add 1 to the result. If Zero is a valid value for your number, instead of adding 1 to the result, simply multiply by 1 more than the highest number you want to generate. Do not round the result.

Workshop To help reinforce your understanding of the material presented in this hour, refer to the section “Quiz and Exercise Questions and Answers” that can be found on the CD. This section contains quiz questions and exercises for you to complete, as well as the corresponding answers.

Fair Use Sources

COBOL: COBOL Fundamentals, COBOL Inventor - COBOL Language Designer: 1959 by Howard Bromberg, Norman Discount, Vernon Reeves, Jean E. Sammet, William Selden, Gertrude Tierney, with indirect influence from Grace Hopper, CODASYL, ANSI COBOL, ISO/IEC COBOL; Modern COBOL - Legacy COBOL, IBM COBOL, COBOL keywords, COBOL data structures - COBOL algorithms, COBOL syntax, Visual COBOL, COBOL on Windows, COBOL on Linux, COBOL on UNIX, COBOL on macOS, Mainframe COBOL, IBM i COBOL, IBM Mainframe DevOps, COBOL Standards, COBOL Paradigms (Imperative COBOL, Procedural COBOL, Object-Oriented COBOL - COBOL OOP, Functional COBOL), COBOL syntax, COBOL installation, COBOL containerization, COBOL configuration, COBOL compilers, COBOL IDEs, COBOL development tools, COBOL DevOps - COBOL SRE, COBOL data science - COBOL DataOps, COBOL machine learning, COBOL deep learning, COBOL concurrency, COBOL history, COBOL bibliography, COBOL glossary, COBOL topics, COBOL courses, COBOL Standard Library, COBOL libraries, COBOL frameworks, COBOL research, Grace Hopper, COBOL GitHub, Written in COBOL, COBOL popularity, COBOL Awesome list, COBOL Versions. (navbar_cobol)


© 1994 - 2024 Cloud Monk Losang Jinpa or Fair Use. Disclaimers

SYI LU SENG E MU CHYWE YE. NAN. WEI LA YE. WEI LA YE. SA WA HE.


sams_teach_yourself_cobol_in_24_hours_-_hour_22_other_intrinsic_functions.txt · Last modified: 2024/04/28 03:37 by 127.0.0.1