user
|  |
| --- |
| 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 {\displaystyle \mathrm {agm} (a,g)}}
, and is equal to the limit of the sequence:

:   a

    0
    =
    a
    ;


    g

    0
    =
    g
    {\displaystyle {\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 {\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 {\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 {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}}

Also see

* mathworld.wolfram.com/Arithmetic-Geometric Mean
assistant
(formerly Perl 6)

```
sub agm( $a is copy, $g is copy ) {
    ($a, $g) = ($a + $g)/2, sqrt $a * $g until $a ≅ $g;
    return $a;
}
 
say agm 1, 1/sqrt 2;
```

Output:

```
0.84721308479397917
```

It's also possible to write it recursively:

```
sub agm( $a, $g ) {
    $a ≅ $g ?? $a !! agm(|@$_)
        given ($a + $g)/2, sqrt $a * $g;
}

say agm 1, 1/sqrt 2;
```

We can also get a bit fancy and use a converging sequence of complex numbers:

```
sub agm {
  ($^z, {(.re+.im)/2 + (.re*.im).sqrt*1i} ... * ≅ *)
  .tail.re
}
 
say agm 1 + 1i/2.sqrt
```