

 This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)



Task

Write a function to compute the arithmetic-geometric mean of two numbers.



The arithmetic-geometric mean of two numbers can be (usefully) denoted as 




a
g
m

(
a
,
g
)


{\displaystyle \mathrm {agm} (a,g)}

, and is equal to the limit of the sequence:

 




a

0


=
a
;


g

0


=
g


{\displaystyle a_{0}=a;\qquad g_{0}=g}


 




a

n
+
1


=



1
2



(

a

n


+

g

n


)
;


g

n
+
1


=



a

n



g

n




.


{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}


Since the limit of 




a

n


−

g

n




{\displaystyle a_{n}-g_{n}}

 tends (rapidly) to zero with iterations, this is an efficient method.

Demonstrate the function by calculating:






a
g
m

(
1
,
1

/



2


)


{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}




Also see

   mathworld.wolfram.com/Arithmetic-Geometric Mean


IDENTIFICATION DIVISION.
PROGRAM-ID. ARITHMETIC-GEOMETRIC-MEAN-PROG.
DATA DIVISION.
WORKING-STORAGE SECTION.
01  AGM-VARS.
    05 A       PIC 9V9(16).
    05 A-ZERO  PIC 9V9(16).
    05 G       PIC 9V9(16).
    05 DIFF    PIC 9V9(16) VALUE 1.
* Initialize DIFF with a non-zero value, otherwise AGM-PARAGRAPH
* is never performed at all.
PROCEDURE DIVISION.
TEST-PARAGRAPH.
    MOVE    1 TO A.
    COMPUTE G = 1 / FUNCTION SQRT(2).
* The program will run with the test values. If you would rather
* calculate the AGM of numbers input at the console, comment out
* TEST-PARAGRAPH and un-comment-out INPUT-A-AND-G-PARAGRAPH.
* INPUT-A-AND-G-PARAGRAPH.
*     DISPLAY 'Enter two numbers.'
*     ACCEPT  A.
*     ACCEPT  G.
CONTROL-PARAGRAPH.
    PERFORM AGM-PARAGRAPH UNTIL DIFF IS LESS THAN 0.000000000000001.
    DISPLAY A.
    STOP RUN.
AGM-PARAGRAPH.
    MOVE     A TO A-ZERO.
    COMPUTE  A = (A-ZERO + G) / 2.
    MULTIPLY A-ZERO BY G GIVING G.
    COMPUTE  G = FUNCTION SQRT(G).
    SUBTRACT A FROM G GIVING DIFF.
    COMPUTE  DIFF = FUNCTION ABS(DIFF).