# Arithmetic-geometric mean

Arithmetic-geometric mean
You are encouraged to solve this task according to the task description, using any language you may know.
 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)

Write a function to compute the arithmetic-geometric mean of two numbers. [1] The arithmetic-geometric mean of two numbers can be (usefully) denoted as ${\displaystyle \mathrm {agm} (a,g)}$, and is equal to the limit of the sequence:

${\displaystyle a_{0}=a;\qquad g_{0}=g}$
${\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}$

Since the limit of ${\displaystyle a_{n}-g_{n}}$ tends (rapidly) to zero with iterations, this is an efficient method.

Demonstrate the function by calculating:

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

Also see

## 11l

Translation of: Python
F agm(a0, g0, tolerance = 1e-10)   V an = (a0 + g0) / 2.0   V gn = sqrt(a0 * g0)   L abs(an - gn) > tolerance      (an, gn) = ((an + gn) / 2.0, sqrt(an * gn))   R an print(agm(1, 1 / sqrt(2)))
Output:
0.847213

## 360 Assembly

For maximum compatibility, this program uses only the basic instruction set.

AGM      CSECT           USING  AGM,R13SAVEAREA B      STM-SAVEAREA(R15)         DC     17F'0'         DC     CL8'AGM'STM      STM    R14,R12,12(R13)         ST     R13,4(R15)         ST     R15,8(R13)         LR     R13,R15         ZAP    A,K                a=1         ZAP    PWL8,K         MP     PWL8,K         DP     PWL8,=P'2'         ZAP    PWL8,PWL8(7)         BAL    R14,SQRT         ZAP    G,PWL8             g=sqrt(1/2)WHILE1   EQU    *                  while a!=g         ZAP    PWL8,A         SP     PWL8,G         CP     PWL8,=P'0'         (a-g)!=0         BE     EWHILE1         ZAP    PWL8,A         AP     PWL8,G         DP     PWL8,=P'2'         ZAP    AN,PWL8(7)         an=(a+g)/2         ZAP    PWL8,A         MP     PWL8,G         BAL    R14,SQRT         ZAP    G,PWL8             g=sqrt(a*g)         ZAP    A,AN               a=an         B      WHILE1EWHILE1  EQU    *         ZAP    PWL8,A         UNPK   ZWL16,PWL8         MVC    CWL16,ZWL16         OI     CWL16+15,X'F0'         MVI    CWL16,C'+'         CP     PWL8,=P'0'         BNM    *+8         MVI    CWL16,C'-'         MVC    CWL80+0(15),CWL16         MVC    CWL80+9(1),=C'.'   /k  (15-6=9)         XPRNT  CWL80,80           display a         L      R13,4(0,R13)         LM     R14,R12,12(R13)         XR     R15,R15         BR     R14         DS     0FK        DC     PL8'1000000'       10^6 A        DS     PL8G        DS     PL8AN       DS     PL8* ****** SQRT   *******************SQRT     CNOP   0,4                function sqrt(x)         ZAP    X,PWL8         ZAP    X0,=P'0'           x0=0         ZAP    X1,=P'1'           x1=1WHILE2   EQU    *                  while x0!=x1         ZAP    PWL8,X0         SP     PWL8,X1         CP     PWL8,=P'0'         (x0-x1)!=0         BE     EWHILE2         ZAP    X0,X1              x0=x1         ZAP    PWL16,X         DP     PWL16,X1         ZAP    XW,PWL16(8)        xw=x/x1         ZAP    PWL8,X1         AP     PWL8,XW         DP     PWL8,=P'2'         ZAP    PWL8,PWL8(7)         ZAP    X2,PWL8            x2=(x1+xw)/2         ZAP    X1,X2              x1=x2         B      WHILE2EWHILE2  EQU    *         ZAP    PWL8,X1            return x1         BR     R14         DS     0FX        DS     PL8X0       DS     PL8X1       DS     PL8X2       DS     PL8XW       DS     PL8* end SQRTPWL8     DC     PL8'0'PWL16    DC     PL16'0'CWL80    DC     CL80' 'CWL16    DS     CL16ZWL16    DS     ZL16         LTORG           YREGS           END    AGM
Output:
+00000000.84721


## 8th

: epsilon  1.0e-12 ; with: n : iter  \ n1 n2 -- n1 n2    2dup * sqrt >r + 2 / r> ; : agn  \ n1 n2 -- n    repeat  iter  2dup epsilon ~= not while!  drop ; "agn(1, 1/sqrt(2)) = " .  1  1 2 sqrt /  agn  "%.10f" s:strfmt . cr ;withbye
Output:
agn(1, 1/sqrt(2)) = 0.8472130848


with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; procedure Arith_Geom_Mean is    type Num is digits 18; -- the largest value gnat/gcc allows   package N_IO is new Ada.Text_IO.Float_IO(Num);   package Math is new Ada.Numerics.Generic_Elementary_Functions(Num);    function AGM(A, G: Num) return Num is      Old_G: Num;      New_G: Num := G;      New_A: Num := A;   begin      loop         Old_G := New_G;         New_G := Math.Sqrt(New_A*New_G);         New_A := (Old_G + New_A) * 0.5;         exit when (New_A - New_G) <= Num'Epsilon;         -- Num'Epsilon denotes the relative error when performing arithmetic over Num      end loop;      return New_G;   end AGM; begin   N_IO.Put(AGM(1.0, 1.0/Math.Sqrt(2.0)), Fore => 1, Aft => 17, Exp => 0);end Arith_Geom_Mean;
Output:
0.84721308479397909

## ALGOL 68

Algol 68 Genie gives IEEE double precision for REAL quantities, 28 decimal digits for LONG REALs and, by default, 63 decimal digits for LONG LONG REAL though this can be made arbitrarily greater with a pragmat.

Printing out the difference between the means at each iteration nicely demonstrates the quadratic convergence.

 BEGIN   PROC agm = (LONG REAL x, y) LONG REAL :   BEGIN      IF x < LONG 0.0 OR y < LONG 0.0 THEN -LONG 1.0      ELIF x + y = LONG 0.0 THEN LONG 0.0		CO Edge cases CO      ELSE	 LONG REAL a := x, g := y;	 LONG REAL epsilon := a + g;	 LONG REAL next a := (a + g) / LONG 2.0, next g := long sqrt (a * g);	 LONG REAL next epsilon := ABS (a - g);	 WHILE next epsilon < epsilon	 DO	    print ((epsilon, "   ", next epsilon, newline));	    epsilon := next epsilon;	    a := next a; g := next g;	    next a := (a + g) / LONG 2.0; next g := long sqrt (a * g);	    next epsilon := ABS (a - g)	 OD;	 a      FI   END;   printf (($l(-35,33)l$, agm (LONG 1.0, LONG 1.0 / long sqrt (LONG 2.0))))END
Output:
+1.707106781186547524400844362e  +0   +2.928932188134524755991556379e  -1
+2.928932188134524755991556379e  -1   +1.265697533955921916929670477e  -2
+1.265697533955921916929670477e  -2   +2.363617660269221214237489508e  -5
+2.363617660269221214237489508e  -5   +8.242743980540458935740117000e -11
+8.242743980540458935740117000e -11   +1.002445937606580000000000000e -21
+1.002445937606580000000000000e -21   +4.595001000000000000000000000e -29
+4.595001000000000000000000000e -29   +4.595000000000000000000000000e -29

0.847213084793979086606499123550000


## APL

 agd←{(⍺-⍵)<10*¯8:⍺⋄((⍺+⍵)÷2)∇(⍺×⍵)*÷2}1 agd ÷2*÷2
Output:
0.8472130848

## AppleScript

By functional composition:

-- ARITHMETIC GEOMETRIC MEAN ------------------------------------------------- property tolerance : 1.0E-5 -- agm :: Num a => a -> a -> aon agm(a, g)    script withinTolerance        on |λ|(m)            tell m to ((its an) - (its gn)) < tolerance        end |λ|    end script     script nextRefinement        on |λ|(m)            tell m                set {an, gn} to {its an, its gn}                {an:(an + gn) / 2, gn:(an * gn) ^ 0.5}            end tell        end |λ|    end script     an of |until|(withinTolerance, ¬        nextRefinement, {an:(a + g) / 2, gn:(a * g) ^ 0.5})end agm -- TEST ----------------------------------------------------------------------on run     agm(1, 1 / (2 ^ 0.5))     --> 0.847213084835 end run -- GENERIC FUNCTIONS --------------------------------------------------------- -- until :: (a -> Bool) -> (a -> a) -> a -> aon |until|(p, f, x)    set mp to mReturn(p)    set v to x    tell mReturn(f)        repeat until mp's |λ|(v)            set v to |λ|(v)        end repeat    end tell    return vend |until| -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Scripton mReturn(f)    if class of f is script then        f    else        script            property |λ| : f        end script    end ifend mReturn
Output:
0.847213084835

## AutoHotkey

agm(a, g, tolerance=1.0e-15){	While abs(a-g) > tolerance	{		an := .5 * (a + g)		g  := sqrt(a*g)		a  := an	}	return a}SetFormat, FloatFast, 0.15MsgBox % agm(1, 1/sqrt(2))

Output:

0.847213084793979

## AWK

#!/usr/bin/awk -fBEGIN {	printf "%.16g\n", agm(1.0,sqrt(0.5))}function agm(a,g) {	while (1) {		a0=a		a=(a0+g)/2		g=sqrt(a0*g)		if (abs(a0-a) < abs(a)*1e-15) break	}	return a}function abs(x) {	return (x<0 ? -x : x)}

Output

0.8472130847939792

## BASIC

### Commodore BASIC

10 A = 120 G = 1/SQR(2)30 GOSUB 10040 PRINT A50 END100 TA = A110 A = (A+G)/2120 G = SQR(TA*G)130 IF A<TA THEN 100140 RETURN

### BBC BASIC

      *FLOAT 64      @% = &1010      PRINT FNagm(1, 1/SQR(2))      END       DEF FNagm(a,g)      LOCAL ta      REPEAT        ta = a        a = (a+g)/2        g = SQR(ta*g)      UNTIL a = ta      = a

Produces this output:

0.8472130847939792


### IS-BASIC

100 PRINT AGM(1,1/SQR(2))110 DEF AGM(A,G)120   DO130     LET TA=A140     LET A=(A+G)/2:LET G=SQR(TA*G)150   LOOP UNTIL A=TA160   LET AGM=A170 END DEF

## bc

/* Calculate the arithmethic-geometric mean of two positive * numbers x and y. * Result will have d digits after the decimal point. */define m(x, y, d) {    auto a, g, o     o = scale    scale = d    d = 1 / 10 ^ d     a = (x + y) / 2    g = sqrt(x * y)    while ((a - g) > d) {        x = (a + g) / 2        g = sqrt(a * g)        a = x    }     scale = o    return(a)}     scale = 20m(1, 1 / sqrt(2), 20)
Output:
.84721308479397908659

## C

### Basic

#include<math.h>#include<stdio.h>#include<stdlib.h> double agm( double a, double g ) {   /* arithmetic-geometric mean */   double iota = 1.0E-16;   double a1, g1;    if( a*g < 0.0 ) {      printf( "arithmetic-geometric mean undefined when x*y<0\n" );      exit(1);   }    while( fabs(a-g)>iota ) {      a1 = (a + g) / 2.0;      g1 = sqrt(a * g);       a = a1;      g = g1;   }    return a;} int main( void ) {   double x, y;   printf( "Enter two numbers: " );   scanf( "%lf%lf", &x, &y );   printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) );   return 0;}

Original output:

Enter two numbers: 1.0 2.0
The arithmetic-geometric mean is 1.456791


Task output, the second input (0.707) is 1/sqrt(2) correct to 3 decimal places:

Enter two numbers: 1 0.707
The arithmetic-geometric mean is 0.847155


### GMP

/*Arithmetic Geometric Mean of 1 and 1/sqrt(2)   Nigel_Galloway  February 7th., 2012.*/ #include "gmp.h" void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {	mpf_add (out1, in1, in2);	mpf_div_ui (out1, out1, 2);	mpf_mul (out2, in1, in2);	mpf_sqrt (out2, out2);} int main (void) {	mpf_set_default_prec (65568);	mpf_t x0, y0, resA, resB; 	mpf_init_set_ui (y0, 1);	mpf_init_set_d (x0, 0.5);	mpf_sqrt (x0, x0);	mpf_init (resA);	mpf_init (resB); 	for(int i=0; i<7; i++){		agm(x0, y0, resA, resB);		agm(resA, resB, x0, y0);	}	gmp_printf ("%.20000Ff\n", x0);	gmp_printf ("%.20000Ff\n\n", y0); 	return 0;}

The first couple of iterations produces:

0.853
0.840


Then 7 iterations produces:

0.84721308479397908660649912348219163648144591032694218506057937265973400483413475972320029399461122994212228562523341096309796266583087105969971363598338425117632681428906038970676860161665004828118872189771330941176746201994439296290216728919449950723167789734686394760667105798055785217314034939830420042211921603983955359509819364129371634064602959996797059943435160203184264875695024217486385540598195458160174241788785419275880416271901208558768564832683414043121840080403580920455949431387781512092652225457439712428682076634095473367459962179266553534862568611854330862628728728756301083556319357066871478563908898211510883635214769697961262183294322841786811376844517001814602191369402702094599668351359632788080427434548174458736322002515395293626580661419836561649162625960743472370661690235308001737531284785255843063190745427493415268579065526940600314759102033274671968612479632551055464890282085529743965124994009662552866067580448735389218570140116771697653501408495247684899325732133702898466893919466586187375296638756226604591477704420468108925658440838032040910619003153706734119594101007474331059905505820524326009951692792417478216976781061683697714110739273343921550143022007087367365962272149258776192851052380367026890463909621907663644235538085902945234065190013342345105838341712180514255003923701111325411144612628906254133550526643653595824552156293397518251470650134641047056979355681306606329373345038710977097294875917179015817320281578288487149931340815493342367797044712785937618595085146677364554679201615934223997142984070788882279032656751596528435817795727284808356489963504404140734226110183383546975962663330422084999852300742703930277243474979717973264552546543019831694968461098690743905068013766119252919770938441299707015889493166661161994592265011311183966352502530561646431587208454522988775475177272747656721648982918239238895207207642839710884705960356921992921831901548141280766592698294464457149239666329973075813904957622438962423175209507319018424462442370986427281149511180822826053862484617675180140983127497257651983756492356902800216174905531427208153439540595563576371127281657059737337442970039056040156388663072225700389230159112376960121580081779077863351240862431073571583765926504546652787337874444834406310244757039681255453982266430353416413035613801634165575265589752944521166873451220191227466733191571240763753821106968141076926390074833175743396752319660330864973571383874196098983832202882694882191302819366949954422240697276168621369511657838885012199096160655454611543253148164249332694797004159491476323112920593516518997943350045976288217292625918089405508431466393782548335139550190653370872062064024077056075848796499843651592728264534428636615419142585777106756185017278033287175195189305031805505245426022335522900771418128798654351187918006356279593624768267786412249460338126082628254098895312527677534656243279214511229555516031818433133692961723041783855157125567404983416665926969580008953724573057694542275372160209687191470398878466367243262706191127071716590824640041679941120405657103640830002419294398553073994656539677810492701055410359513339432199925066676202078394695553760551796401009749218856311301017813888578793813172095948062539201300983650287917695827985905279947721941797997024943062158419468885328115497721579960194409623477686144085075739284298823759396823223670580334134774623112897625859324376631778974911077261909704489522204509630725515590093824904021364807792034767215048568446022554409992826163174312642285787628983380650722023010371753149263504631060188573772567006618381290580638954508127031311371043716135833488065833955431217901348398833216413057635244712511539472066670330101348716516324113828817639839629526121141263219795965098656786755250760760424095907517523021946104532564333249614901253533329223723868948127885020135966305376055849358928391630469403887854960027471487197801457659579049585802260066099524967364324966833461760106608156706975142381866503610838852209761655002516073114992161294775790199729248689638220603808760276281672370166819106633585775154650381334236722347642026558565588464160102105404898556187114735884976378406486426798186504486319077470382286711435151123003607086574298864771466747337501143458188527970060562117246921748471806948662511994728934442703783046207073549380528727206215606307188286858056452111069670802856990698257691772209986719599685077906814434949328049768115436804632599386930762350709995182951295811212357072453833548261907523951582730982481805496658979091688679840717077937059590457758409104734131096041941113577566207273377978332037973011376726585357477102797814097213096121423938547374627696150413079528373728820506587191522597650840277969917611753930067254924912298450823629755687227110658494355338504945326387364898046066559799543601695030927900924500578564772358761988489860344121953407953690029964119745490607416009788595376607229051607724285900709011566391383642990412208267696297978676490323564999819907659974398705486487690910249119270999682756970113687622440464029603837000662127345776647097113263746568115029858630322603373834213584239378961146171920830719539156437820936414967803341524645073966831731983633627433925553117120194541468448808956224178980318943412312840278583782890096242095413450021010727363232852725762096468519944682405506293917420533017064619172151788442967053143355037723107097160802851453141441061050231173108777799332489320877272298978213301208340743056049981599632026877933071569403024391561189267675172495117665262485470960419914731136579206973309960888972867897807355875785006235751571237716530420636310027031292966940254219678771688466557275808983064676620070146795856930822206209053308277822265031125202787335125191599188939002843192181666865484348796219722117639049598957936073309436974576289432003841175529415947547471839363811441256103510234595810807685589856570074453089094286692511901017181228266893492695282610525185567360458777022881478214469685009183472197414205461280723479500598117663645261501907885454711938035571459307446356562607527875188243864095069646498151311705914579906193765608586501756168645019240983272357243336888130800221863687002096411197243036035586497937733149167495931511886735350255059823030470602847404584566768496209345063963029094416325164086928898145072478777276733780338289295049783843429437665667372975874305751410364174768616396241989419047309961002284280794449200269048452541391882460015590891319432556103657693623641617846466931414561099840383122655041152514944453800420904287181824684316246105526376775209701040639446878373750174360897516934868876512834536775527865470902315420294538730761411966497675219198089021057726334723979589687229233577690412444586822978062098870898160181795214549203709562528507330232550600966113294791484434166874298726542040835520564564044211741240650419323628312966431263307687154504449507335544182007936697013312446388243600624398167124093468063221697717015635904176098412619778010525869566346541447025111353828410102785795430618023572755009305139556377710439227995971141182782033581183989523387201196266668287812153433311933530198006525119241035943150724272515897742269014313251497752206211486532095282917841726788527918259501894283066454533808294385484913906600901526463156669408130516898577384457161101347735284395586639180314771289972489772326950830959208603163908601794221468048925371471356694906475975663504050761059303001534536134468346141362848404730639095800648624822113995399621221079927740532030597569871315014292389418219892184458614968453063460782870588642625603497671133853907530473607475205697255326635179640594881381276485191302328261295517207475944988639251110497859774101046472588317449694892733322810684089494759787067690122169518696581944061366943103234116196131605543816087283055435048190711597527426659173636930019809887976272186626285433119060860342806191518452978237036398984494144178890086027822209983902274728379674114295789243465456404028551674783725388313861547805080352368935833328873558797948868049809714068689367194167115043074025751022690817073859285358373909764249759224210618323725170214283209867537445071332189636669085656349633060774556830118371494002584049977661135255328476656188705929782127298997295927947818204287198071022786461838070064010831389756771127541362211274445345355849597692525757583129990395369598932499513241067842656115567436600887374842740382348117849110021235371080153344077081752815794229285487316898639800718962686849857790619425820001731784737979758156092690872878502700244147412819535788739647458594598995355434128016535530490585287946743982206062303866888527005052189049277821975141155954355491253261150874322804356095631761163218117941648842069284743156991336777879569137055927049598939111007862241124499317195398903082153071269718073528142944373740581805897842871015663258737266000122961804037804290931751604739799312368824663145245907925120889169747654302457053206386704684110540342014376644422132127507998462991570101471065529461467463922495745306196822034254448162475459772696534302506868242052880996924489236521714038177492829359173154812849196214333040809043068672336820607162912893985174062559042822475581595091023242061608163635114409532679679744662146581218973837257052018318006785051812332707432360517602365653046059197282467620464979507571243323062106152366172293244682862511105778328547123718579064823024291991297534773406188123932244051237932292486982393020946057994685022093564580188647372057989508199682850879081206451754647928466570299934961463545338169898790120739595342994580518846829188356311361388796313161734422075062182129450475034337306401403566141064033208676214431839284389699942682868360825355912427514883833922646682229633236574889815991049023745712780770628532368956900284697429547742484223355238590492992254533182706939660886035184911668751085520062653409664126112200692905563690527440648936400870151716629293565299214744207938737106473991364534021859315182015761100594055566001663181909163482128186430684182569911943162667158985886736504889805808329721451958115258329743580644326982892093642849596169753399275023838326958011096089547864572561097853782973070749181687447357311890498494907816322101271109193983576388927531317499783213682809328943493309300878688841270920763590076480651183013174408131381707764785620869834568499576963332415566990859371495284373037821741667810126247377548449594082775980428578137754484461929295371533597418713555566780286064849179748275590223773761897037703324897743492353765235571390764314889671441330995396798710462847477217721858658519859712821657391485744943283203084641639560963010473704739884503079369569286834641137642263085686956881520537491962945628810859870159107649550192726673782765172374500136624210511467091848989522697276562069762630550949389320992163775294153350600271094300189773392218453903373510079427646652325090453779404782123556204886389696402910291826730243688880139827500496556889555403627397541183592770090942918399583962985359521234655737077516804320238724010087862923625584849202212960559482323176352142071176504276997478012902491509148733472049812083534865212462335388584717004701205923945825415223129676013072682802320446336442341000264743415683991238810480498194912009402448957203018812206409969973408437360958124499459132317933593338191973602488533756410304356437323020013283599906152983949167106879976939266990335220640837295869943043576709171697966984423326568307325500003213129027067191063424283113900494781793073045562199439120722094954719165471096054049199441860517249814718129940631192901737381011766173569764956366756202788955920995046861634403052506586817358402694287366334311678329038374756580509907839853849260647212465651306604876736085857902183866432416271982103787727963377367426929456639854705293777458546922070020463303573435055175370140503103555265780827298970492305475455890092754109445040141571253576828010749151746279285337830995706319528768382378063681778416611863347477894201661901861433888045148841743616814548103623210376432745956533646293972952940499526616911816577400181161464976544075891509125575991008552731077337032136035056194073504052234145332243066047436002572125901272025171469526054624392158151517326614548122436198603573869224654036885597877500832683869306742537593493769726913825327805701356834418623150103189551287054940385947609492785905200098814477158397147139718137205549603311916422391953132302138759927174019046224139259148006201715618158893529451219781937047457085386954279002330804105880072509475123189307968446372241711705946061976147519773238961013155564063723093102794769739382294763468939337559468936650940499102526121635380720056442410264711646398004909985355702820593960545544792555586249187092321801304541029363328936193265963508514136372072931427677632678178400667800895586548777826308228184465081585096256950206977978896641405511014211855334440159488802847016579044649263092161202380685664726316113269955335854143205474428967281732917140106437305939602224827339697208658091942888039633443448764675833855973513333306284397863570621963822177055006726076075702023055483284393359373696240854049573444151418891438122060768323290633843326859359282266483616228768156709313037896783277414878452878382324740383408934494278060455890181836731336022711672853044271945073157409136000663560891812190403050193190281639721357906960252119295624559528358504426277879932144682210413256122712903024696103748551345991066626060821435461264637908469523386805592378228286103613864160137539204268883711926027420874745077827301808826482979914892334346533639303279918164769955294688929040603354702651883178258213919150731170223368395649453356304141924428385039542090733375111170537908197680613788461570042923922647881382284866725434155806944211935068360004884655615990833391847242631836989281306956549491531650103132163612240182987115172224015233681014762461698964172597488387271895987656023503248287097414687934153787088145731903279204532192316858527351083720559424566015456479446754495668591429979882331798190595741253686810321947980826038762410448487302089050658719342641740920079366698836014623097627598441130715257589162880105817093530725888876543862532018486249319236385682165626031104345283130307049722913348730332409337369563479748898249300174158056591821232883438581012501715373053984620434324557214820885475234947304677614292829153914858526885054230744505481926191669759750315034472082118453139076834860069087727520772464857065976367409361731434369903994989083757102465456508149620159888052044833794917070408483039094175124262758698686686442934982424196674036270760323992014071830712707598371320007124471595236427821624884729339137136340461389740888941783993200900515436084216188913289577403543844561076450160104627095790986524953420147660163304582935376534545234386674137987312550170295545828095478975424973671090385982646068956222412573032081408906070252061404578152823685045057657100438042285920327207291902221346518359302559429408753069947011011534164767856235435750239937364145328957734998761675022409197941218931880590179774443294036240385510824919547518411770141508205549991488032865000650690301650284556165335148907119741941723100296632479366408253645421048976404451080811239063681885949086604183400256315626612115063653092972195806871776320514613555813095008145638261124165214871635936435536462688727462766803686306800882312499705727064962653352854242737234497574827760613008180634196390830978822494789229495258916657826100444244401103267485396201200233971298346242423632837110742673099021260291100381090507518405232662739050319348560154855106326243187789708788951981680730963542230960055362677359050994734087443710248167279700094945897076301853449526801067309842468288488837600166958871373559692445552385363961787881342093093764848484068429404997314946635784558266882458253566353932897293167000662381283685196706276978897699290095978380695574407690809500695946595783253660660602130005250129981452150996293071107006157960047599188298274727518774924726747707554136792657750601495283368598380853534208742156827588012599928559034100979630199437410013949755918229188467057410106349315945279547420320572953565968695868630973284883811742438270584417356596674853152028861911921252863987395609281275132232141197542293430923755693396146727405175695293766990610523654483440786104255766945418734863793560708612404736883567734371401263501208237651763905620506040768947294002931620797603428968468976398678305539415152307137255605029146711751234519321319625717919409117289511239481135988605880624240378357519964870883301506792101754290605314188369786110278968306896668518684104701823647807006155298831498831116019499658150386743904671052471759937267092033810519847770061227523026980385376199177319071331058167790086514801724404464037647206737845833953828893809029412739879104752542584865616980485432967822810404539976611651232907291616199926287510865193417311165133056591829817625847694287084548190293442221860279774055192912661889487080105159228601492383934908897821669651094997616731795835221057913587243550297821114252805843809597704721778938273829164718826714378658214613260112635165542805164184221882641418906866191864927517189847350374966026860336719613049159226094421467730920744767947119178202099132268721849475483780038487261488727428812655791747946341514445451055994645676144782933879680154128864180982848855259596173991776576352670819899854089307445641992969024592754051436475256486619329599030683238667575184797410153429114165087535728924796842802484402202118983902434301907465924705639919100242258143990683914578574580953440968261584897316158220398376910051716543905900933268275864197534394837719059730794650292103636419726159238721878760956871976819344819558525670241414336715908896942047817989365563517751015910050265859472794486423173118927271535250460340818962273831146005468524063988554718596840882777221622505863684193799641126463210706398187737943696502521044386223206715172284114754334828030417076754385554475843212718463962813919258849725090510409441344504298453460718488756542407096901385926116455196765637084297106764946357662012853819267912041109778058573520627375104669435915920749043789661298087162743223850390320074778542110638995449541859976414281163951972397080789860487582641265448251499232272861765713896973345378359636039627090380026689213243891590093752250336511719377706572262953412570689809077931988799970767832633036706673426579253958499505823639986104928784799761858913840247447907423559817960132549606526849887335183972871912518993883243416026083561644966709023900422732162219315679399440012151599100543810845200811331032075534924844873692683144444666107802758917774683693445850459499632371560438002582276189086030745508199318928997032855495073302401217663495153158278308977864322545562217443057528251437080871843144708110045101086121226999313969693610665236087211263590123448282622844271912819731872697619747403980717783781881605198018622572329702247624947679129326840201880617952362291746013985766042335790944077230173530153379744356437385842482505380615471930752244293091172074476771495221419193909742017160269705578258369237072978115455525707880049556669154779018307195916635166870579843369516111891537519123967141163781970007849531153863267663692691720169784090403969698048618284364177768040884492084399010959512057513408610603753534081557370871883138983376563225336509460103086861119012415417949006598353669263835150584020260982595703854291458650256921579873098070645970823263771382355857377042256281442627934977694293588040208827420282637864436159358179308178583062657122634794521740652164107980293335739611374043019282943678846268324324490788126847872819886762029310625102649485865494639647891543662406355703466884777848152714124704306460406156142773201070035758550339952793775297161566283811185180855234141875772560252179951036627714775522910368395398000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000


The limit (19,740) is imposed by the accuracy (65568). Using 6 iterations would produce a less accurate result. At 7 iterations increasing the 65568 would mean we already have 38,000 or so digits accurate.

## C++

 #include<bits/stdc++.h>using namespace std;#define _cin	ios_base::sync_with_stdio(0);	cin.tie(0);#define rep(a, b)	for(ll i =a;i<=b;++i) double agm(double a, double g)		//ARITHMETIC GEOMETRIC MEAN{	double epsilon = 1.0E-16,a1,g1;	if(a*g<0.0)	{	cout<<"Couldn't find arithmetic-geometric mean of these numbers\n";		exit(1);	}	while(fabs(a-g)>epsilon)	{	a1 = (a+g)/2.0;		g1 = sqrt(a*g);		a = a1;		g = g1;	}	return a;} int main(){	_cin;    //fast input-output	double x, y;	cout<<"Enter X and Y: ";	//Enter two numbers	cin>>x>>y;	cout<<"\nThe Arithmetic-Geometric Mean of "<<x<<" and "<<y<<" is "<<agm(x, y);return 0;}

Enter X and Y: 1.0 2.0
The Arithmetic-Geometric Mean of 1.0 and 2.0 is 1.45679103104690677028543177584651857614517211914062


## C#

namespace RosettaCode.ArithmeticGeometricMean{    using System;    using System.Collections.Generic;    using System.Globalization;     internal static class Program    {        private static double ArithmeticGeometricMean(double number,                                                      double otherNumber,                                                      IEqualityComparer<double>                                                          comparer)        {            return comparer.Equals(number, otherNumber)                       ? number                       : ArithmeticGeometricMean(                           ArithmeticMean(number, otherNumber),                           GeometricMean(number, otherNumber), comparer);        }         private static double ArithmeticMean(double number, double otherNumber)        {            return 0.5 * (number + otherNumber);        }         private static double GeometricMean(double number, double otherNumber)        {            return Math.Sqrt(number * otherNumber);        }         private static void Main()        {            Console.WriteLine(                ArithmeticGeometricMean(1, 0.5 * Math.Sqrt(2),                                        new RelativeDifferenceComparer(1e-5)).                    ToString(CultureInfo.InvariantCulture));        }         private class RelativeDifferenceComparer : IEqualityComparer<double>        {            private readonly double _maximumRelativeDifference;             internal RelativeDifferenceComparer(double maximumRelativeDifference)            {                _maximumRelativeDifference = maximumRelativeDifference;            }             public bool Equals(double number, double otherNumber)            {                return RelativeDifference(number, otherNumber) <=                       _maximumRelativeDifference;            }             public int GetHashCode(double number)            {                return number.GetHashCode();            }             private static double RelativeDifference(double number,                                                     double otherNumber)            {                return AbsoluteDifference(number, otherNumber) /                       Norm(number, otherNumber);            }             private static double AbsoluteDifference(double number,                                                     double otherNumber)            {                return Math.Abs(number - otherNumber);            }             private static double Norm(double number, double otherNumber)            {                return 0.5 * (Math.Abs(number) + Math.Abs(otherNumber));            }        }    }}

Output:

0.847213084835193

### C# with System.Numerics

Even though the System.Numerics library directly supports only BigInteger (and not big rationals or big floating point numbers), it can be coerced into making this calculation. One just has to keep track of the decimal place and multiply by a very large constant.

using System;using System.Numerics; namespace agm{    class Program    {        static BigInteger BIP(char leadDig, int numDigs)        {            return BigInteger.Parse(leadDig + new string('0', numDigs));        }         static BigInteger IntSqRoot(BigInteger v)        {            int digs = Math.Max(0, v.ToString().Length / 2);            BigInteger res = BIP('3', digs), term;             while (true) {                term = v / res; if (Math.Abs((double)(term - res)) < 2) break;                res = (res + term) / 2; } return res;        }         static BigInteger CalcByAGM(int digits)        {            int digs = digits + (int)(Math.Log(digits) / 2), d2 = digs * 2;            BigInteger a = BIP('1', digs),              // initial value = 1                       b = IntSqRoot(BIP('5', d2 - 1)), // initial value = square root of 0.5                       c;            while (true) {                c = a; a = ((a + b) / 2); b = IntSqRoot(c * b);                if (Math.Abs((double)(a - b)) <= 1) break;            }            return b;        }         static void Main(string[] args)        {            int digits = 25000;            if (args.Length > 0)            {                int.TryParse(args[0], out digits);                if (digits < 1 || digits > 999999) digits = 25000;            }            Console.WriteLine("0.{0}", CalcByAGM(digits).ToString());            if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();        }    }}
Output:
0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723200293994611229942122285625233410963097962665830871059699713635983384251176326814289060389706768601616650048281188721897713309411767462019944392962902167289194499507231677897346863947606671057980557852173140349398304200422119216039839553595098193641293716340646029599967970599434351602031842648756950242174863855405981954581601742417887854192758804162719012085587685648326834140431218400804035809204559494313877815120926522254574397124286820766340954733674599621792665535348625686118543308626287287287563010835563193570668714785639088982115108836352147696979612621832943228417868113768445170018146021913694027020945996683513596327880804274345481744587363220025153952936265806614198365616491626259607434723706616902353080017375312847852558430631907454274934152685790655269406003147591020332746719686124796325510554648902820855297439651249940096625528660675804487353892185701401167716976535014084952476848993257321337028984668939194665861873752966387562266045914777044204681089256584408380320409106190031537067341195941010074743310599055058205243260099516927924174782169767810616836977141107392733439215501430220070873673659622721492587761928510523803670268904639096219076636442355380859029452340651900133423451058383417121805142550039237011113254111446126289062541335505266436535958245521562933975182514706501346410470569793556813066063293733450387109770972948759171790158173202815782884871499313408154933423677970447127859376185950851466773645546792016159342239971429840707888822790326567515965284358177957272848083564899635044041407342261101833835469759626633304220849998523007427039302772434749797179732645525465430198316949684610986907439050680137661192529197709384412997070158894931666611619945922650113111839663525025305616464315872084545229887754751772727476567216489829182392388952072076428397108847059603569219929218319015481412807665926982944644571492396663299730758139049576224389624231752095073190184244624423709864272811495111808228260538624846176751801409831274972576519837564923569028002161749055314272081534395405955635763711272816570597373374429700390560401563886630722257003892301591123769601215800817790778633512408624310735715837659265045466527873378744448344063102447570396812554539822664303534164130356138016341655752655897529445211668734512201912274667331915712407637538211069681410769263900748331757433967523196603308649735713838741960989838322028826948821913028193669499544222406972761686213695116578388850121990961606554546115432531481642493326947970041594914763231129205935165189979433500459762882172926259180894055084314663937825483351395501906533708720620640240770560758487964998436515927282645344286366154191425857771067561850172780332871751951893050318055052454260223355229007714181287986543511879180063562795936247682677864122494603381260826282540988953125276775346562432792145112295555160318184331336929617230417838551571255674049834166659269695800089537245730576945422753721602096871914703988784663672432627061911270717165908246400416799411204056571036408300024192943985530739946565396778104927010554103595133394321999250666762020783946955537605517964010097492188563113010178138885787938131720959480625392013009836502879176958279859052799477219417979970249430621584194688853281154977215799601944096234776861440850757392842988237593968232236705803341347746231128976258593243766317789749110772619097044895222045096307255155900938249040213648077920347672150485684460225544099928261631743126422857876289833806507220230103717531492635046310601885737725670066183812905806389545081270313113710437161358334880658339554312179013483988332164130576352447125115394720666703301013487165163241138288176398396295261211412632197959650986567867552507607604240959075175230219461045325643332496149012535333292237238689481278850201359663053760558493589283916304694038878549600274714871978014576595790495858022600660995249673643249668334617601066081567069751423818665036108388522097616550025160731149921612947757901997292486896382206038087602762816723701668191066335857751546503813342367223476420265585655884641601021054048985561871147358849763784064864267981865044863190774703822867114351511230036070865742988647714667473375011434581885279700605621172469217484718069486625119947289344427037830462070735493805287272062156063071882868580564521110696708028569906982576917722099867195996850779068144349493280497681154368046325993869307623507099951829512958112123570724538335482619075239515827309824818054966589790916886798407170779370595904577584091047341310960419411135775662072733779783320379730113767265853574771027978140972130961214239385473746276961504130795283737288205065871915225976508402779699176117539300672549249122984508236297556872271106584943553385049453263873648980460665597995436016950309279009245005785647723587619884898603441219534079536900299641197454906074160097885953766072290516077242859007090115663913836429904122082676962979786764903235649998199076599743987054864876909102491192709996827569701136876224404640296038370006621273457766470971132637465681150298586303226033738342135842393789611461719208307195391564378209364149678033415246450739668317319836336274339255531171201945414684488089562241789803189434123128402785837828900962420954134500210107273632328527257620964685199446824055062939174205330170646191721517884429670531433550377231070971608028514531414410610502311731087777993324893208772722989782133012083407430560499815996320268779330715694030243915611892676751724951176652624854709604199147311365792069733099608889728678978073558757850062357515712377165304206363100270312929669402542196787716884665572758089830646766200701467958569308222062090533082778222650311252027873351251915991889390028431921816668654843487962197221176390495989579360733094369745762894320038411755294159475474718393638114412561035102345958108076855898565700744530890942866925119010171812282668934926952826105251855673604587770228814782144696850091834721974142054612807234795005981176636452615019078854547119380355714593074463565626075278751882438640950696464981513117059145799061937656085865017561686450192409832723572433368881308002218636870020964111972430360355864979377331491674959315118867353502550598230304706028474045845667684962093450639630290944163251640869288981450724787772767337803382892950497838434294376656673729758743057514103641747686163962419894190473099610022842807944492002690484525413918824600155908913194325561036576936236416178464669314145610998403831226550411525149444538004209042871818246843162461055263767752097010406394468783737501743608975169348688765128345367755278654709023154202945387307614119664976752191980890210577263347239795896872292335776904124445868229780620988708981601817952145492037095625285073302325506009661132947914844341668742987265420408355205645640442117412406504193236283129664312633076871545044495073355441820079366970133124463882436006243981671240934680632216977170156359041760984126197780105258695663465414470251113538284101027857954306180235727550093051395563777104392279959711411827820335811839895233872011962666682878121534333119335301980065251192410359431507242725158977422690143132514977522062114865320952829178417267885279182595018942830664545338082943854849139066009015264631566694081305168985773844571611013477352843955866391803147712899724897723269508309592086031639086017942214680489253714713566949064759756635040507610593030015345361344683461413628484047306390958006486248221139953996212210799277405320305975698713150142923894182198921844586149684530634607828705886426256034976711338539075304736074752056972553266351796405948813812764851913023282612955172074759449886392511104978597741010464725883174496948927333228106840894947597870676901221695186965819440613669431032341161961316055438160872830554350481907115975274266591736369300198098879762721866262854331190608603428061915184529782370363989844941441788900860278222099839022747283796741142957892434654564040285516747837253883138615478050803523689358333288735587979488680498097140686893671941671150430740257510226908170738592853583739097642497592242106183237251702142832098675374450713321896366690856563496330607745568301183714940025840499776611352553284766561887059297821272989972959279478182042871980710227864618380700640108313897567711275413622112744453453558495976925257575831299903953695989324995132410678426561155674366008873748427403823481178491100212353710801533440770817528157942292854873168986398007189626868498577906194258200017317847379797581560926908728785027002441474128195357887396474585945989953554341280165355304905852879467439822060623038668885270050521890492778219751411559543554912532611508743228043560956317611632181179416488420692847431569913367778795691370559270495989391110078622411244993171953989030821530712697180735281429443737405818058978428710156632587372660001229618040378042909317516047397993123688246631452459079251208891697476543024570532063867046841105403420143766444221321275079984629915701014710655294614674639224957453061968220342544481624754597726965343025068682420528809969244892365217140381774928293591731548128491962143330408090430686723368206071629128939851740625590428224755815950910232420616081636351144095326796797446621465812189738372570520183180067850518123327074323605176023656530460591972824676204649795075712433230621061523661722932446828625111057783285471237185790648230242919912975347734061881239322440512379322924869823930209460579946850220935645801886473720579895081996828508790812064517546479284665702999349614635453381698987901207395953429945805188468291883563113613887963131617344220750621821294504750343373064014035661410640332086762144318392843896999426828683608253559124275148838339226466822296332365748898159910490237457127807706285323689569002846974295477424842233552385904929922545331827069396608860351849116687510855200626534096641261122006929055636905274406489364008701517166292935652992147442079387371064739913645340218593151820157611005940555660016631819091634821281864306841825699119431626671589858867365048898058083297214519581152583297435806443269828920936428495961697533992750238383269580110960895478645725610978537829730707491816874473573118904984949078163221012711091939835763889275313174997832136828093289434933093008786888412709207635900764806511830131744081313817077647856208698345684995769633324155669908593714952843730378217416678101262473775484495940827759804285781377544844619292953715335974187135555667802860648491797482755902237737618970377033248977434923537652355713907643148896714413309953967987104628474772177218586585198597128216573914857449432832030846416395609630104737047398845030793695692868346411376422630856869568815205374919629456288108598701591076495501927266737827651723745001366242105114670918489895226972765620697626305509493893209921637752941533506002710943001897733922184539033735100794276466523250904537794047821235562048863896964029102918267302436888801398275004965568895554036273975411835927700909429183995839629853595212346557370775168043202387240100878629236255848492022129605594823231763521420711765042769974780129024915091487334720498120835348652124623353885847170047012059239458254152231296760130726828023204463364423410002647434156839912388104804981949120094024489572030188122064099699734084373609581244994591323179335933381919736024885337564103043564373230200132835999061529839491671068799769392669903352206408372958699430435767091716979669844233265683073255000032131290270671910634242831139004947817930730455621994391207220949547191654710960540491994418605172498147181299406311929017373810117661735697649563667562027889559209950468616344030525065868173584026942873663343116783290383747565805099078398538492606472124656513066048767360858579021838664324162719821037877279633773674269294566398547052937774585469220700204633035734350551753701405031035552657808272989704923054754558900927541094450401415712535768280107491517462792853378309957063195287683823780636817784166118633474778942016619018614338880451488417436168145481036232103764327459565336462939729529404995266169118165774001811614649765440758915091255759910085527310773370321360350561940735040522341453322430660474360025721259012720251714695260546243921581515173266145481224361986035738692246540368855978775008326838693067425375934937697269138253278057013568344186231501031895512870549403859476094927859052000988144771583971471397181372055496033119164223919531323021387599271740190462241392591480062017156181588935294512197819370474570853869542790023308041058800725094751231893079684463722417117059460619761475197732389610131555640637230931027947697393822947634689393375594689366509404991025261216353807200564424102647116463980049099853557028205939605455447925555862491870923218013045410293633289361932659635085141363720729314276776326781784006678008955865487778263082281844650815850962569502069779788966414055110142118553344401594888028470165790446492630921612023806856647263161132699553358541432054744289672817329171401064373059396022248273396972086580919428880396334434487646758338559735133333062843978635706219638221770550067260760757020230554832843933593736962408540495734441514188914381220607683232906338433268593592822664836162287681567093130378967832774148784528783823247403834089344942780604558901818367313360227116728530442719450731574091360006635608918121904030501931902816397213579069602521192956245595283585044262778799321446822104132561227129030246961037485513459910666260608214354612646379084695233868055923782282861036138641601375392042688837119260274208747450778273018088264829799148923343465336393032799181647699552946889290406033547026518831782582139191507311702233683956494533563041419244283850395420907333751111705379081976806137884615700429239226478813822848667254341558069442119350683600048846556159908333918472426318369892813069565494915316501031321636122401829871151722240152336810147624616989641725974883872718959876560235032482870974146879341537870881457319032792045321923168585273510837205594245660154564794467544956685914299798823317981905957412536868103219479808260387624104484873020890506587193426417409200793666988360146230976275984411307152575891628801058170935307258888765438625320184862493192363856821656260311043452831303070497229133487303324093373695634797488982493001741580565918212328834385810125017153730539846204343245572148208854752349473046776142928291539148585268850542307445054819261916697597503150344720821184531390768348600690877275207724648570659763674093617314343699039949890837571024654565081496201598880520448337949170704084830390941751242627586986866864429349824241966740362707603239920140718307127075983713200071244715952364278216248847293391371363404613897408889417839932009005154360842161889132895774035438445610764501601046270957909865249534201476601633045829353765345452343866741379873125501702955458280954789754249736710903859826460689562224125730320814089060702520614045781528236850450576571004380422859203272072919022213465183593025594294087530699470110115341647678562354357502399373641453289577349987616750224091979412189318805901797744432940362403855108249195475184117701415082055499914880328650006506903016502845561653351489071197419417231002966324793664082536454210489764044510808112390636818859490866041834002563156266121150636530929721958068717763205146135558130950081456382611241652148716359364355364626887274627668036863068008823124997057270649626533528542427372344975748277606130081806341963908309788224947892294952589166578261004442444011032674853962012002339712983462424236328371107426730990212602911003810905075184052326627390503193485601548551063262431877897087889519816807309635422309600553626773590509947340874437102481672797000949458970763018534495268010673098424682884888376001669588713735596924455523853639617878813420930937648484840684294049973149466357845582668824582535663539328972931670006623812836851967062769788976992900959783806955744076908095006959465957832536606606021300052501299814521509962930711070061579600475991882982747275187749247267477075541367926577506014952833685983808535342087421568275880125999285590341009796301994374100139497559182291884670574101063493159452795474203205729535659686958686309732848838117424382705844173565966748531520288619119212528639873956092812751322321411975422934309237556933961467274051756952937669906105236544834407861042557669454187348637935607086124047368835677343714012635012082376517639056205060407689472940029316207976034289684689763986783055394151523071372556050291467117512345193213196257179194091172895112394811359886058806242403783575199648708833015067921017542906053141883697861102789683068966685186841047018236478070061552988314988311160194996581503867439046710524717599372670920338105198477700612275230269803853761991773190713310581677900865148017244044640376472067378458339538288938090294127398791047525425848656169804854329678228104045399766116512329072916161999262875108651934173111651330565918298176258476942870845481902934422218602797740551929126618894870801051592286014923839349088978216696510949976167317958352210579135872435502978211142528058438095977047217789382738291647188267143786582146132601126351655428051641842218826414189068661918649275171898473503749660268603367196130491592260944214677309207447679471191782020991322687218494754837800384872614887274288126557917479463415144454510559946456761447829338796801541288641809828488552595961739917765763526708198998540893074456419929690245927540514364752564866193295990306832386675751847974101534291141650875357289247968428024844022021189839024343019074659247056399191002422581439906839145785745809534409682615848973161582203983769100517165439059009332682758641975343948377190597307946502921036364197261592387218787609568719768193448195585256702414143367159088969420478179893655635177510159100502658594727944864231731189272715352504603408189622738311460054685240639885547185968408827772216225058636841937996411264632107063981877379436965025210443862232067151722841147543348280304170767543855544758432127184639628139192588497250905104094413445042984534607184887565424070969013859261164551967656370842971067649463576620128538192679120411097780585735206273751046694359159207490437896612980871627432238503903200747785421106389954495418599764142811639519723970807898604875826412654482514992322728617657138969733453783596360396270903800266892132438915900937522503365117193777065722629534125706898090779319887999707678326330367066734265792539584995058236399861049287847997618589138402474479074235598179601325496065268498873351839728719125189938832434160260835616449667090239004227321622193156793994400121515991005438108452008113310320755349248448736926831444446661078027589177746836934458504594996323715604380025822761890860307455081993189289970328554950733024012176634951531582783089778643225455622174430575282514370808718431447081100451010861212269993139696936106652360872112635901234482826228442719128197318726976197474039807177837818816051980186225723297022476249476791293268402018806179523622917460139857660423357909440772301735301533797443564373858424825053806154719307522442930911720744767714952214191939097420171602697055782583692370729781154555257078800495566691547790183071959166351668705798433695161118915375191239671411637819700078495311538632676636926917201697840904039696980486182843641777680408844920843990109595120575134086106037535340815573708718831389833765632253365094601030868611190124154179490065983536692638351505840202609825957038542914586502569215798730980706459708232637713823558573770422562814426279349776942935880402088274202826378644361593581793081785830626571226347945217406521641079802933357396113740430192829436788462683243244907881268478728198867620293106251026494858654946396478915436624063557034668847778481527141247043064604061561427732010700357585503399527937752971615662838111851808552341418757725602521799510366277147755229103683953979232937518470013121542865246411152629783074232865118948197892092468274639225034617981978102131340002227230322223473152101603382614564581647211034088319720710942284963700609051026094304473012680179534915289461304610103306181131482136614187498546662880958567829930882499396665549962438001582108241078119032818950685505758199090884859709549457317667220141776418725381686242629385297409262655153675815553768336845182015479396486281053385781097943479307795612554124082856308964707635482727658604790077918304180657432085530277668689997889793948698795072965297144805088951766068438667305666291192985791320659875276209719727939020847384621027715209421238626693025626045120911740207923365815759327469684190635418736609252913811657435704572829041743383259688439135695644261782300694911815699429429552917021135384246870489057231300564610620202965324662847784390202519471581513379117489825704011553285862497369071484480074718471929067100213319127483431066220187414184132870892070927586674503766416928012111286705783213258594853998713287909847264055001397204315347093043650971808407085372331611111161163260026217174881373762104601360054405185063317524523198978529106564646603827874887033113430762004135651429548284350224545440057139238649252628342390795170536664048382687501346985026376797452892628528836654431486803662832963891225420709468733559766951200768750729294062317643560479665180784709540899106851499800335873538798942202890154280071790648227618529868307928613720439699372650361028546335215771836457184338195003192627235229365434338752280951415249805257748636604861358053916266218347510582564726031163344200237752714062511207533229490952552233074466411557226024243589526948292743584402262200146624709386653387904839232051622427643333928264264095396434182241670565846124476044881773770578266908088083441882262261134263272741924841565112103504713196158309499443877943907838066465620714318730989528087415316762165760222799085019961558757833239388336516947814207753326228369452661200546582077140082606039883925515094886155317733344750682267921184969044888047907010204328820587467236167297124606234197336970480786776860998946471237909752570649804238181586539943498303594116225834772902048935683847719780497321491144874874991561667925385743801086450022013484371960972791276113692503512315528253574165582610726609946765701611185568425782687842219783399432914873489392389215329896629423270313584561580472399362482740937396676156325798199403600665503961394188118316426714448566487446834858709943474371012885926755247383146218143432123212475861847692580312891323387866452752520432448479653277627332017135197984953014247380597643031865581040360989753746922633601559652565228488816703746005423504365581343832987087273414206285914784700727499941488512944165791821238387605657254567179408563728927700279021860478842351992457305181197637773159441299439386053455915965812712386295531591818284192388135724500924623850709774189143757567688620693643360826366037435517318502695423976617303882627504383896524716042868973954806164066460656537905053942279570880184082966495697819240673730707625301425754222176386023043180947705675890568172303332631140880288609288015177746908237506313775092527533163800983678664599194988101810822244685844398486597244962109799933160526858781006192712588969440066997975564880094089562624291753183438892003566311336876393146384781276313023782556219831179106178085668790330978953974750523954531663063816955977765334765594990877920235971866662357248705555821648403608492521780343110435664741760019363161347419611312665720606428221769042854124656020456145948431774468321390602126772741118944367580444291158375742357250021419146749334287116084058263947048563637037567960479707349081368108383856211384139158705255361507399198312547343452740459654792697253954244755599033280971664357803964694574981336862115241049028858177920631820825506916645550784089962833317474487395160722939925885469418863797824014463529526498257285663210305355089105717174867411521849477407758915111581948906885197195976812921402351145438273886755728832042660833803075951572754557763972623847067463401162634695323181522954971899690647043890353657443064443647271644955086851987181709281406874644947080685617457088510506476649433220539108509753998789798067227886994313463279903237260493315016338677403943051949329714250532111766901182029360448269416630130980111122744365495327124238853493997327774999933529666713830796944113571907996950609982192320687889262441611017590925490461028655351203248828567373514842932400983163321126446037617204620938427052890377225105764396893898372277964046845270569432108545527382946271102273724329060629460165173265459446356986135096609520996203850801089967366647007391870576067980133705834704656750336937959892815443738076551103171908198590137108863960070070563187309925148094798923861905247923098330971793822624572560011957113072238679043125574217913563311114664608326838259676235601847277220919801312198322417907947613497742174816883393427887640301433431879849341771661325650642266826463838842978687544381098675438645949184608207863334604646941842977881383385775551967000566984045658764213085205705014831456825938770242861922467117318737082222462753831336593786820143553512660014624624943588080657269357308448561507390184276116721516220484045991383967425164850842

## Clojure

(ns agmcompute  (:gen-class)) ; Java Arbitray Precision Library(import '(org.apfloat Apfloat ApfloatMath)) (def precision 70)(def one (Apfloat. 1M precision))(def two (Apfloat. 2M precision))(def half (Apfloat. 0.5M precision))(def isqrt2 (.divide one  (ApfloatMath/pow two half)))(def TOLERANCE (Apfloat. 0.000000M precision)) (defn agm [a g]  " Simple AGM Loop calculation "       (let [THRESH 1e-65                 ; done when error less than threshold or we exceed max loops             MAX-LOOPS 1000000]        (loop [[an gn] [a g], cnt 0]            (if (or (< (ApfloatMath/abs (.subtract an gn)) THRESH)                    (> cnt MAX-LOOPS))              an              (recur [(.multiply (.add an gn) half) (ApfloatMath/pow (.multiply an gn) half)]                     (inc cnt)))))) (println  (agm one isqrt2))
Output:
8.47213084793979086606499123482191636481445910326942185060579372659734e-1


## COBOL

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).
Output:
0.8472130847939792

## Common Lisp

(defun agm (a0 g0 &optional (tolerance 1d-8))  (loop for a = a0 then (* (+ a g) 5d-1)     and g = g0 then (sqrt (* a g))     until (< (abs (- a g)) tolerance)     finally (return a)))
Output:
CL-USER> (agm 1d0 (/ 1d0 (sqrt 2d0)))
0.8472130848351929d0
CL-USER> (agm 1d0 (/ 1d0 (sqrt 2d0)) 1d-10)
0.8472130848351929d0
CL-USER> (agm 1d0 (/ 1d0 (sqrt 2d0)) 1d-12)
0.8472130847939792d0

## D

import std.stdio, std.math, std.meta, std.typecons; real agm(real a, real g, in int bitPrecision=60) pure nothrow @nogc @safe {    do {        //{a, g} = {(a + g) / 2.0, sqrt(a * g)};        AliasSeq!(a, g) = tuple((a + g) / 2.0, sqrt(a * g));    } while (feqrel(a, g) < bitPrecision);    return a;} void main() @safe {    writefln("%0.19f", agm(1, 1 / sqrt(2.0)));}
Output:
0.8472130847939790866

All the digits shown are exact.

## EchoLisp

We use the (~= a b) operator which tests for |a - b| < ε = (math-precision).

 (lib 'math) (define (agm a g)     (if (~= a g) a        (agm (// (+ a g ) 2) (sqrt (* a g))))) (math-precision)    → 0.000001 ;; default(agm 1 (/ 1 (sqrt 2)))    → 0.8472130848351929(math-precision 1.e-15)    → 1e-15(agm 1 (/ 1 (sqrt 2)))    → 0.8472130847939792

## Elixir

defmodule ArithhGeom do  def mean(a,g,tol) when abs(a-g) <= tol, do: a  def mean(a,g,tol) do    mean((a+g)/2,:math.pow(a*g, 0.5),tol)  endend IO.puts ArithhGeom.mean(1,1/:math.sqrt(2),0.0000000001)
Output:
0.8472130848351929


## Erlang

%% Arithmetic Geometric Mean of 1 and 1 / sqrt(2)%% Author: Abhay Jain -module(agm_calculator).-export([find_agm/0]).-define(TOLERANCE, 0.0000000001). find_agm() ->    A = 1,    B = 1 / (math:pow(2, 0.5)),    AGM = agm(A, B),    io:format("AGM = ~p", [AGM]). agm (A, B) when abs(A-B) =< ?TOLERANCE ->    A;agm (A, B) ->    A1 = (A+B) / 2,    B1 = math:pow(A*B, 0.5),    agm(A1, B1).

Output:

AGM = 0.8472130848351929

## ERRE

 PROGRAM AGM !! for rosettacode.org! !$DOUBLE PROCEDURE AGM(A,G->A) LOCAL TA REPEAT TA=A A=(A+G)/2 G=SQR(TA*G) UNTIL A=TAEND PROCEDURE BEGIN AGM(1.0,1/SQR(2)->A) PRINT(A)END PROGRAM  ## F# Translation of: OCaml let rec agm a g precision = if precision > abs(a - g) then a else agm (0.5 * (a + g)) (sqrt (a * g)) precision printfn "%g" (agm 1. (sqrt(0.5)) 1e-15) Output 0.847213 ## Factor USING: kernel math math.functions prettyprint ;IN: rosetta-code.arithmetic-geometric-mean : agm ( a g -- a' g' ) 2dup [ + 0.5 * ] 2dip * sqrt ; 1 1 2 sqrt / [ 2dup - 1e-15 > ] [ agm ] while drop . Output: 0.8472130847939792  ## Forth : agm ( a g -- m ) begin fover fover f+ 2e f/ frot frot f* fsqrt fover fover 1e-15 f~ until fdrop ; 1e 2e -0.5e f** agm f. \ 0.847213084793979 ## Fortran A Fortran 77 implementation  function agm(a,b) implicit none double precision agm,a,b,eps,c parameter(eps=1.0d-15) 10 c=0.5d0*(a+b) b=sqrt(a*b) a=c if(a-b.gt.eps*a) go to 10 agm=0.5d0*(a+b) end program test implicit none double precision agm print*,agm(1.0d0,1.0d0/sqrt(2.0d0)) end ## FreeBASIC ' version 16-09-2015' compile with: fbc -s console Function agm(a As Double, g As Double) As Double Dim As Double t_a Do t_a = (a + g) / 2 g = Sqr(a * g) Swap a, t_a Loop Until a = t_a Return a End Function ' ------=< MAIN >=------ Print agm(1, 1 / Sqr(2) ) ' empty keyboard buffer While InKey <> "" : WendPrint : Print "hit any key to end program"SleepEnd Output:  0.8472130847939792 ## Futhark  This example is incorrect. Please fix the code and remove this message.Details: Futhark's syntax has changed, so this example will not compile  import "futlib/math" fun agm(a: f64, g: f64): f64 = let eps = 1.0E-16 loop ((a,g)) = while f64.abs(a-g) > eps do ((a+g) / 2.0, f64.sqrt (a*g)) in a fun main(x: f64, y: f64): f64 = agm(x,y)  ## Go package main import ( "fmt" "math") const ε = 1e-14 func agm(a, g float64) float64 { for math.Abs(a-g) > math.Abs(a)*ε { a, g = (a+g)*.5, math.Sqrt(a*g) } return a} func main() { fmt.Println(agm(1, 1/math.Sqrt2))} Output: 0.8472130847939792  ## Groovy Translation of: Java Solution: double agm (double a, double g) { double an = a, gn = g while ((an-gn).abs() >= 10.0**-14) { (an, gn) = [(an+gn)*0.5, (an*gn)**0.5] } an} Test: println "agm(1, 0.5**0.5) = agm(1,${0.5**0.5}) = ${agm(1, 0.5**0.5)}"assert (0.8472130847939792 - agm(1, 0.5**0.5)).abs() <= 10.0**-14 Output: agm(1, 0.5**0.5) = agm(1, 0.7071067811865476) = 0.8472130847939792 ## Haskell -- Return an approximation to the arithmetic-geometric mean of two numbers.-- The result is considered accurate when two successive approximations are-- sufficiently close, as determined by "eq".agm :: (Floating a) => a -> a -> ((a, a) -> Bool) -> aagm a g eq = snd . head . dropWhile (not . eq)$ iterate step (a, g)  where step (a, g) = ((a + g) / 2, sqrt (a * g)) -- Return the relative difference of the pair.  We assume that at least one of-- the values is far enough from 0 to not cause problems.relDiff :: (Fractional a) => (a, a) -> arelDiff (x, y) = let n = abs (x - y)                      d = ((abs x) + (abs y)) / 2                 in n / d main = do  let equal = (< 0.000000001) . relDiff  print $agm 1 (1 / sqrt 2) equal Output: 0.8472130847527654 ## Icon and Unicon procedure main(A) a := real(A[1]) | 1.0 g := real(A[2]) | (1 / 2^0.5) epsilon := real(A[3]) write("agm(",a,",",g,") = ",agm(a,g,epsilon))end procedure agm(an, gn, e) /e := 1e-15 while abs(an-gn) > e do { ap := (an+gn)/2.0 gn := (an*gn)^0.5 an := ap } return anend Output: ->agm agm(1.0,0.7071067811865475) = 0.8472130847939792 ->  ## J This one is probably worth not naming, in J, because there are so many interesting variations. First, the basic approach (with display precision set to 16 digits, which slightly exceeds the accuracy of 64 bit IEEE floating point arithmetic): mean=: +/ % # (mean , */ %:~ #)^:_] 1,%%:20.8472130847939792 0.8472130847939791 This is the limit -- it stops when values are within a small epsilon of previous calculations. We can ask J for unique values (which also means -- unless we specify otherwise -- values within a small epsilon of each other, for floating point values):  ~.(mean , */ %:~ #)^:_] 1,%%:20.8472130847939792 Another variation would be to show intermediate values, in the limit process:  (mean, */ %:~ #)^:a: 1,%%:2 1 0.70710678118654750.8535533905932737 0.84089641525371450.8472249029234942 0.84720126674689150.8472130848351929 0.84721308475276540.8472130847939792 0.8472130847939791 ### Arbitrary Precision Another variation would be to use arbitrary precision arithmetic in place of floating point arithmetic. Borrowing routines from that page, but going with a default of approximately 100 digits of precision: DP=:101 round=: DP&$: : (4 : 0) b %~ <.1r2+y*b=. 10x^x) sqrt=: DP&$: : (4 : 0) " 0 assert. 0<:y %/ <[email protected]%: (2 x: (2*x) round y)*10x^2*x+0>.>.10^.y) ln=: DP&$: : (4 : 0) " 0 assert. 0<y m=. <.0.5+2^.y t=. (<:%>:) (x:!.0 y)%2x^m if. x<-:#":t do. t=. (1+x) round t end. ln2=. 2*+/1r3 (^%]) 1+2*i.>.0.5*(%3)^.0.5*0.1^x+>.10^.1>.m lnr=. 2*+/t   (^%]) 1+2*i.>.0.5*(|t)^.0.5*0.1^x lnr + m * ln2) exp=: DP&$: : (4 : 0) " 0 m=. <.0.5+y%^.2 xm=. x+>.m*10^.2 d=. (x:!.0 y)-m*xm ln 2 if. xm<-:#":d do. d=. xm round d end. e=. 0.1^xm n=. e (>i.1:) a (^%[email protected]]) i.>.a^.e [ a=. |y-m*^.2 (2x^m) * 1++/*/\d%1+i.n) We are also going to want a routine to display numbers with this precision, and we are going to need to manage epsilon manually, and we are going to need an arbitrary root routine: fmt=:[: ;:inv DP&$: : (4 :0)&.>  x{.deb (x*2j1)":y) root=: [email protected]] [email protected]% [ epsilon=: 1r9^DP

Some example uses:

   fmt sqrt 21.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572   fmt *~sqrt 22.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000   fmt epsilon0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000418   fmt 2 root 21.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572

Note that 2 root 2 is considerably slower than sqrt 2. The price of generality. So, while we could define geometric mean generally, a desire for good performance pushes us to use a routine specialized for two numbers:

geomean=: */ root~ #geomean2=: [: sqrt */

A quick test to make sure these can be equivalent:

   fmt geomean 3 53.872983346207416885179265399782399610832921705291590826587573766113483091936979033519287376858673517   fmt geomean2 3 53.872983346207416885179265399782399610832921705291590826587573766113483091936979033519287376858673517

   fmt (mean, geomean2)^:(epsilon <&| -/)^:a: 1,%sqrt 21.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0.7071067811865475244008443621048490392848359376884740365883398689953662392310535194251937671638207860.853553390593273762200422181052424519642417968844237018294169934497683119615526759712596883581910393 0.8408964152537145430311254762332148950400342623567845108132260859749247549539022398143240041992925360.847224902923494152615773828642819707341226115600510764553698010236303937284714499763460443890601464 0.8472012667468914604036314536933523979639810136120005008232957479234881918713276681075814345423535360.847213084835192806509702641168086052652603564606255632688496879079896064578021083935520939216477500 0.8472130847527653667042980517799020703921106560594525833177762276594388966885185567535692987624493810.847213084793979086607000346473994061522357110332854108003136553369667480633269820344545118989463440 0.8472130847939790866059979004903892114405348585862613004614139299713992816190686666825691081412247100.847213084793979086606499123482191636481445984459557704232275241670533381126169243513557113565344075 0.8472130847939790866064991234821916364814458361943266658888835036489346285421002759328467177901473610.847213084793979086606499123482191636481445910326942185060579372659734004834134759723201915677745718 0.8472130847939790866064991234821916364814459103269421850605793726597340048341347597231986723114767410.847213084793979086606499123482191636481445910326942185060579372659734004834134759723200293994611229 0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723200293994611229

We could of course extract out only a representative final value, but it's obvious enough, and showing how rapidly this converges is fun.

## Java

/* * Arithmetic-Geometric Mean of 1 & 1/sqrt(2) * Brendan Shaklovitz * 5/29/12 */public class ArithmeticGeometricMean {     public static double agm(double a, double g) {        double a1 = a;        double g1 = g;        while (Math.abs(a1 - g1) >= 1.0e-14) {            double arith = (a1 + g1) / 2.0;            double geom = Math.sqrt(a1 * g1);            a1 = arith;            g1 = geom;        }        return a1;    }     public static void main(String[] args) {        System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0)));    }}
Output:
0.8472130847939792

## JavaScript

### ES5

function agm(a0, g0) {    var an = (a0 + g0) / 2,        gn = Math.sqrt(a0 * g0);    while (Math.abs(an - gn) > tolerance) {        an = (an + gn) / 2, gn = Math.sqrt(an * gn)    }    return an;} agm(1, 1 / Math.sqrt(2));

### ES6

(() => {    'use strict';     // ARITHMETIC-GEOMETRIC MEAN     // agm :: Num a => a -> a -> a    let agm = (a, g) => {            let abs = Math.abs,                sqrt = Math.sqrt;             return until(                    m => abs(m.an - m.gn) < tolerance,                    m => {                        return {                            an: (m.an + m.gn) / 2,                            gn: sqrt(m.an * m.gn)                        };                    }, {                        an: (a + g) / 2,                        gn: sqrt(a * g)                    }                )                .an;        },         // GENERIC         // until :: (a -> Bool) -> (a -> a) -> a -> a        until = (p, f, x) => {            let v = x;            while (!p(v)) v = f(v);            return v;        };      // TEST     let tolerance = 0.000001;      return agm(1, 1 / Math.sqrt(2)); })();
Output:
0.8472130848351929

## jq

Works with: jq version 1.4

Naive version that assumes tolerance is appropriately specified:

def naive_agm(a; g; tolerance):  def abs: if . < 0 then -. else . end;  def _agm:     # state [an,gn]     if ((.[0] - .[1])|abs) > tolerance      then [add/2, ((.[0] * .[1])|sqrt)] | _agm      else .     end;  [a, g] | _agm | .[0] ;

This version avoids an infinite loop if the requested tolerance is too small:

def agm(a; g; tolerance):  def abs: if . < 0 then -. else . end;  def _agm:     # state [an,gn, delta]     ((.[0] - .[1])|abs) as $delta | if$delta == .[2] and $delta < 10e-16 then . elif$delta > tolerance       then [ .[0:2]|add / 2, ((.[0] * .[1])|sqrt), $delta] | _agm else . end; if tolerance <= 0 then error("specified tolerance must be > 0") else [a, g, 0] | _agm | .[0] end ; # Example:agm(1; 1/(2|sqrt); 1e-100) Output: $ jq -n -f Arithmetic-geometric_mean.jq
0.8472130847939792


## Julia

function agm(x::T, y::T, e::Real = 5) where T<:AbstractFloat    if x ≤ 0 || y ≤ 0 || e ≤ 0 throw(DomainError("x, y must be strictly positive")) end    err = e * eps(x)    g, a = minmax(x, y)    while err < (a - g)        a, g = (a + g) / 2, sqrt(a * g)    end    return aend x = 1.0y = 1 / √2 println("# Using literal-precision float numbers:")@show agm(x, y)println("# Using half-precision float numbers:")x, y = Float32(x), Float32(y)@show agm(x, y)println("# Using ", precision(BigFloat), "-bit float numbers:")x, y = big(1.0), 1 / √big(2.0)@show agm(x, y)

This version of agm accepts only x and y of matching floating point types. A more permissive version could be created by removing the type parametrization or by creating mixed type versions of the function. The ε for this calculation is given as a positive integer multiple of the machine ε for x.

Output:
# Using literal-precision float numbers:
agm(x, y) = 0.8472130847939792
# Using half-precision float numbers:
agm(x, y) = 0.84721315f0
# Using 256-bit float numbers:
agm(x, y) = 8.472130847939790866064991234821916364814459103269421850605793726597340048341323e-01

## Kotlin

// version 1.0.5-2 fun agm(a: Double, g: Double): Double {    var aa = a             // mutable 'a'    var gg = g             // mutable 'g'    var ta: Double         // temporary variable to hold next iteration of 'aa'    val epsilon = 1.0e-16  // tolerance for checking if limit has been reached     while (true) {        ta = (aa + gg) / 2.0        if (Math.abs(aa - ta) <= epsilon) return ta        gg = Math.sqrt(aa * gg)        aa = ta    }} fun main(args: Array<String>) {    println(agm(1.0, 1.0 / Math.sqrt(2.0)))}
Output:
0.8472130847939792


## LFE

 (defun agm (a g)  (agm a g 1.0e-15)) (defun agm (a g tol)  (if (=< (- a g) tol)    a    (agm (next-a a g)         (next-g a g)         tol))) (defun next-a (a g)  (/ (+ a g) 2)) (defun next-g (a g)  (math:sqrt (* a g)))

Usage:

> (agm 1 (/ 1 (math:sqrt 2)))
0.8472130847939792


## Liberty BASIC

 print agm(1, 1/sqr(2))print using("#.#################",agm(1, 1/sqr(2))) function agm(a,g)    do        absdiff = abs(a-g)        an=(a+g)/2        gn=sqr(a*g)        a=an        g=gn    loop while abs(an-gn)< absdiff    agm = aend function

## LiveCode

function agm aa,g    put abs(aa-g) into absdiff     put (aa+g)/2 into aan    put sqrt(aa*g) into gn    repeat while abs(aan - gn) < absdiff        put abs(aa-g) into absdiff         put (aa+g)/2 into aan        put sqrt(aa*g) into gn        put aan into aa        put gn into g    end repeat    return aaend agm

Example

put agm(1, 1/sqrt(2))-- ouput-- 0.847213

## LLVM

; This is not strictly LLVM, as it uses the C library function "printf".; LLVM does not provide a way to print values, so the alternative would be; to just load the string into memory, and that would be boring. ; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps $"ASSERTION" = comdat any$"OUTPUT" = comdat any @"ASSERTION" = linkonce_odr unnamed_addr constant [48 x i8] c"arithmetic-geometric mean undefined when x*y<0\0A\00", comdat, align 1@"OUTPUT" = linkonce_odr unnamed_addr constant [42 x i8] c"The arithmetic-geometric mean is %0.19lf\0A\00", comdat, align 1 ;--- The declarations for the external C functionsdeclare i32 @printf(i8*, ...)declare void @exit(i32) #1declare double @sqrt(double) #1 declare double @llvm.fabs.f64(double) #2 ;----------------------------------------------------------------;-- arithmetic geometric meandefine double @agm(double, double) #0 {    %3 = alloca double, align 8                     ; allocate local g    %4 = alloca double, align 8                     ; allocate local a    %5 = alloca double, align 8                     ; allocate iota    %6 = alloca double, align 8                     ; allocate a1    %7 = alloca double, align 8                     ; allocate g1    store double %1, double* %3, align 8            ; store param g in local g    store double %0, double* %4, align 8            ; store param a in local a    store double 1.000000e-15, double* %5, align 8  ; store 1.0e-15 in iota (1.0e-16 was causing the program to hang)     %8 = load double, double* %4, align 8           ; load a    %9 = load double, double* %3, align 8           ; load g    %10 = fmul double %8, %9                        ; a * g    %11 = fcmp olt double %10, 0.000000e+00         ; a * g < 0.0    br i1 %11, label %enforce, label %loop enforce:    %12 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([48 x i8], [48 x i8]* @"ASSERTION", i32 0, i32 0))    call void @exit(i32 1) #6    unreachable loop:    %13 = load double, double* %4, align 8          ; load a    %14 = load double, double* %3, align 8          ; load g    %15 = fsub double %13, %14                      ; a - g    %16 = call double @llvm.fabs.f64(double %15)    ; fabs(a - g)    %17 = load double, double* %5, align 8          ; load iota    %18 = fcmp ogt double %16, %17                  ; fabs(a - g) > iota    br i1 %18, label %loop_body, label %eom loop_body:    %19 = load double, double* %4, align 8          ; load a    %20 = load double, double* %3, align 8          ; load g    %21 = fadd double %19, %20                      ; a + g    %22 = fdiv double %21, 2.000000e+00             ; (a + g) / 2.0    store double %22, double* %6, align 8           ; store %22 in a1     %23 = load double, double* %4, align 8          ; load a    %24 = load double, double* %3, align 8          ; load g    %25 = fmul double %23, %24                      ; a * g    %26 = call double @sqrt(double %25) #4          ; sqrt(a * g)    store double %26, double* %7, align 8           ; store %26 in g1     %27 = load double, double* %6, align 8          ; load a1    store double %27, double* %4, align 8           ; store a1 in a     %28 = load double, double* %7, align 8          ; load g1    store double %28, double* %3, align 8           ; store g1 in g     br label %loop eom:    %29 = load double, double* %4, align 8          ; load a    ret double %29                                  ; return a} ;----------------------------------------------------------------;-- maindefine i32 @main() #0 {    %1 = alloca double, align 8                     ; allocate x    %2 = alloca double, align 8                     ; allocate y     store double 1.000000e+00, double* %1, align 8  ; store 1.0 in x     %3 = call double @sqrt(double 2.000000e+00) #4  ; calculate the square root of two    %4 = fdiv double 1.000000e+00, %3               ; divide 1.0 by %3    store double %4, double* %2, align 8            ; store %4 in y     %5 = load double, double* %2, align 8           ; reload y    %6 = load double, double* %1, align 8           ; reload x    %7 = call double @agm(double %6, double %5)     ; agm(x, y)     %8 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([42 x i8], [42 x i8]* @"OUTPUT", i32 0, i32 0), double %7)     ret i32 0                                       ; finished} attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }attributes #1 = { noreturn "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }attributes #2 = { nounwind readnone speculatable }attributes #4 = { nounwind }attributes #6 = { noreturn }
Output:
The arithmetic-geometric mean is 0.8472130847939791654

## Logo

to about :a :b  output and [:a - :b < 1e-15] [:a - :b > -1e-15]endto agm :arith :geom  if about :arith :geom [output :arith]  output agm (:arith + :geom)/2  sqrt (:arith * :geom)end show agm 1 1/sqrt 2

## Lua

function agm(a, b, tolerance)    if not tolerance or tolerance < 1e-15 then        tolerance = 1e-15    end    repeat        a, b = (a + b) / 2, math.sqrt(a * b)    until math.abs(a-b) < tolerance    return aend print(string.format("%.15f", agm(1, 1 / math.sqrt(2))))

Output:

   0.847213084793979


## M2000 Interpreter

 Module Checkit {      Function Agm {      \\ new stack constructed at calling the Agm() with two values            Repeat {                  Read a0, b0                  Push  Sqrt(a0*b0), (a0+b0)/2                  ' last pushed first read             } Until Stackitem(1)==Stackitem(2)            =Stackitem(1)            \\ stack deconstructed at exit of function      }       Print Agm(1,1/Sqrt(2))}Checkit

## Maple

Maple provides this function under the name GaussAGM. To compute a floating point approximation, use evalf.

 > evalf( GaussAGM( 1, 1 / sqrt( 2 ) ) ); # default precision is 10 digits                              0.8472130847 > evalf[100]( GaussAGM( 1, 1 / sqrt( 2 ) ) ); # to 100 digits0.847213084793979086606499123482191636481445910326942185060579372659\    7340048341347597232002939946112300

Alternatively, if one or both arguments is already a float, Maple will compute a floating point approximation automatically.

 > GaussAGM( 1.0, 1 / sqrt( 2 ) );                                          0.8472130847

## Mathematica

To any arbitrary precision, just increase PrecisionDigits

PrecisionDigits = 85;AGMean[a_, b_] := FixedPoint[{ [email protected]#/2, Sqrt[[email protected]@#] }&, N[{a,b}, PrecisionDigits]]〚1〛
AGMean[1, 1/Sqrt[2]]
0.8472130847939790866064991234821916364814459103269421850605793726597340048341347597232

## MATLAB / Octave

function [a,g]=agm(a,g)%%arithmetic_geometric_mean(a,g)	while (1)		a0=a;		a=(a0+g)/2;		g=sqrt(a0*g);	if (abs(a0-a) < a*eps) break; end; 	end;end
octave:26> agm(1,1/sqrt(2))
ans =  0.84721


agm(a, b) := %pi/4*(a + b)/elliptic_kc(((a - b)/(a + b))^2)$agm(1, 1/sqrt(2)), bfloat, fpprec: 85;/* 8.472130847939790866064991234821916364814459103269421850605793726597340048341347597232b-1 */ ## МК-61/52 П1 <-> П0 1 ВП 8 /-/ П2 ИП0 ИП1- ИП2 - /-/ x<0 31 ИП1 П3 ИП0 ИП1* КвКор П1 ИП0 ИП3 + 2 / П0 БП08 ИП0 С/П ## Modula-2 Translation of: C MODULE AGM;FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;FROM LongConv IMPORT ValueReal;FROM LongMath IMPORT sqrt;FROM LongStr IMPORT RealToStr;FROM Terminal IMPORT ReadChar,Write,WriteString,WriteLn; VAR TextWinExSrc : ExceptionSource; PROCEDURE ReadReal() : LONGREAL;VAR buffer : ARRAY[0..63] OF CHAR; i : CARDINAL; c : CHAR;BEGIN i := 0; LOOP c := ReadChar(); IF ((c >= '0') AND (c <= '9')) OR (c = '.') THEN buffer[i] := c; Write(c); INC(i) ELSE WriteLn; EXIT END END; buffer[i] := 0C; RETURN ValueReal(buffer)END ReadReal; PROCEDURE WriteReal(r : LONGREAL);VAR buffer : ARRAY[0..63] OF CHAR;BEGIN RealToStr(r, buffer); WriteString(buffer)END WriteReal; PROCEDURE AGM(a,g : LONGREAL) : LONGREAL;CONST iota = 1.0E-16;VAR a1, g1 : LONGREAL;BEGIN IF a * g < 0.0 THEN RAISE(TextWinExSrc, 0, "arithmetic-geometric mean undefined when x*y<0") END; WHILE ABS(a - g) > iota DO a1 := (a + g) / 2.0; g1 := sqrt(a * g); a := a1; g := g1 END; RETURN aEND AGM; VAR x, y, z: LONGREAL;BEGIN WriteString("Enter two numbers: "); x := ReadReal(); y := ReadReal(); WriteReal(AGM(x, y)); WriteLnEND AGM. Output: Enter two numbers: 1.0 2.0 1.456791031046900 Enter two numbers: 1.0 0.707 0.847154622368330 ## NetRexx Translation of: Java /* NetRexx */options replace format comments java crossref symbols nobinary numeric digits 18parse arg a_ g_ .if a_ = '' | a_ = '.' then a0 = 1 else a0 = a_if g_ = '' | g_ = '.' then g0 = 1 / Math.sqrt(2) else g0 = g_ say agm(a0, g0) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~method agm(a0, g0) public static returns Rexx a1 = a0 g1 = g0 loop while (a1 - g1).abs() >= Math.pow(10, -14) temp = (a1 + g1) / 2 g1 = Math.sqrt(a1 * g1) a1 = temp end return a1 + 0  Output: 0.8472130847939792  ## NewLISP  (define (a-next a g) (mul 0.5 (add a g))) (define (g-next a g) (sqrt (mul a g))) (define (amg a g tolerance) (if (<= (sub a g) tolerance) a (amg (a-next a g) (g-next a g) tolerance) )) (define quadrillionth 0.000000000000001) (define root-reciprocal-2 (div 1.0 (sqrt 2.0))) (println "To the nearest one-quadrillionth, " "the arithmetic-geometric mean of " "1 and the reciprocal of the square root of 2 is " (amg 1.0 root-reciprocal-2 quadrillionth)) =={{header|Nim}}==<lang nim>import math proc agm(a, g: float,delta: float = 1.0e-15): float = var aNew: float = 0 aOld: float = a gOld: float = g while (abs(aOld - gOld) > delta): aNew = 0.5 * (aOld + gOld) gOld = sqrt(aOld * gOld) aOld = aNew result = aOld echo$agm(1.0,1.0/sqrt(2.0))

Output:

8.4721308479397917e-01


See first 24 iterations:

from math import sqrtfrom strutils import parseFloat, formatFloat, ffDecimal proc agm(x,y: float): tuple[resA,resG: float] =  var    a,g: array[0 .. 23,float]   a[0] = x  g[0] = y   for n in 1 .. 23:    a[n] = 0.5 * (a[n - 1] + g[n - 1])    g[n] = sqrt(a[n - 1] * g[n - 1])   (a[23], g[23]) var t = agm(1, 1/sqrt(2.0)) echo("Result A: " & formatFloat(t.resA, ffDecimal, 24))echo("Result G: " & formatFloat(t.resG, ffDecimal, 24))

## Oberon-2

Works with: oo2c
 MODULE Agm;IMPORT  Math := LRealMath,  Out; CONST  epsilon = 1.0E-15; PROCEDURE Of*(a,g: LONGREAL): LONGREAL;VAR  na,ng,og: LONGREAL;BEGIN  na := a; ng := g;  LOOP    og := ng;    ng := Math.sqrt(na * ng);     na := (na + og) * 0.5;    IF na - ng <= epsilon THEN EXIT END  END;  RETURN ng;END Of; BEGIN   Out.LongReal(Of(1,1 / Math.sqrt(2)),0,0);Out.LnEND Agm.
Output:
8.4721308479397905E-1


## Objeck

Translation of: Java
 class ArithmeticMean {  function : Amg(a : Float, g : Float) ~ Nil {    a1 := a;    g1 := g;    while((a1-g1)->Abs() >= Float->Power(10, -14)) {        tmp := (a1+g1)/2.0;        g1 := Float->SquareRoot(a1*g1);        a1 := tmp;    };    a1->PrintLine();  }   function : Main(args : String[]) ~ Nil {    Amg(1,1/Float->SquareRoot(2));  }}

Output:

0.847213085

## OCaml

let rec agm a g tol =  if tol > abs_float (a -. g) then a else  agm (0.5*.(a+.g)) (sqrt (a*.g)) tol let _ = Printf.printf "%.16f\n" (agm 1.0 (sqrt 0.5) 1e-15)

Output

0.8472130847939792

## Oforth

: agm   \ a b -- m   while( 2dup <> ) [ 2dup + 2 / -rot * sqrt ] drop ;

Usage :

1 2 sqrt inv agm
Output:
0.847213084793979


## OOC

 import math // import for sqrt() function amean: func (x: Double, y: Double) -> Double {  (x + y) / 2.}gmean: func (x: Double, y: Double) -> Double {  sqrt(x * y)}agm: func (a: Double, g: Double) -> Double {  while ((a - g) abs() > pow(10, -12)) {    (a1, g1) := (amean(a, g), gmean(a, g))    (a, g) = (a1, g1)  }  a} main: func {  "%.16f" printfln(agm(1., sqrt(0.5)))}

Output

0.8472130847939792

## ooRexx

numeric digits 20say agm(1, 1/rxcalcsqrt(2,16)) ::routine agm  use strict arg a, g  numeric digits 20   a1 = a  g1 = g   loop while abs(a1 - g1) >= 1e-14      temp = (a1 + g1)/2      g1 = rxcalcsqrt(a1*g1,16)      a1 = temp  end  return a1+0 ::requires rxmath LIBRARY
Output:
0.8472130847939791968

## PARI/GP

Built-in:

agm(1,1/sqrt(2))

Iteration:

agm2(x,y)=if(x==y,x,agm2((x+y)/2,sqrt(x*y))

## Pascal

Works with: Free_Pascal
Library: GMP

Port of the C example:

Program ArithmeticGeometricMean; uses  gmp; procedure agm (in1, in2: mpf_t; var out1, out2: mpf_t);begin  mpf_add (out1, in1, in2);  mpf_div_ui (out1, out1, 2);  mpf_mul (out2, in1, in2);  mpf_sqrt (out2, out2);end; const  nl = chr(13)+chr(10);var  x0, y0, resA, resB: mpf_t;  i: integer;begin  mpf_set_default_prec (65568);   mpf_init_set_ui (y0, 1);  mpf_init_set_d (x0, 0.5);  mpf_sqrt (x0, x0);  mpf_init (resA);  mpf_init (resB);   for i := 0 to 6 do  begin    agm(x0, y0, resA, resB);    agm(resA, resB, x0, y0);  end;  mp_printf ('%.20000Ff'+nl, @x0);  mp_printf ('%.20000Ff'+nl+nl, @y0);end.

Output is as long as the C example.

#!/usr/bin/perl -w my ($a0,$g0, $a1,$g1); sub agm() {    $a0 = shift;$g0 = shift;    do {         $a1 = ($a0 + $g0)/2;$g1 = sqrt($a0 *$g0);         $a0 = ($a1 + $g1)/2;$g0 = sqrt($a1 *$g1);     } while ($a0 !=$a1);     return $a0;} print agm(1, 1/sqrt(2))."\n"; Output: 0.847213084793979 ## 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;

## Phix

function agm(atom a, atom g, atom tolerance=1.0e-15)    while abs(a-g)>tolerance do        {a,g} = {(a + g)/2,sqrt(a*g)}        printf(1,"%0.15g\n",a)    end while    return aend function?agm(1,1/sqrt(2))   -- (rounds to 10 d.p.)
Output:
0.853553390593274
0.847224902923494
0.847213084835193
0.847213084793979
0.8472130848


## PHP

 define('PRECISION', 13); function agm($a0,$g0, $tolerance = 1e-10) { // the bc extension deals in strings and cannot convert // floats in scientific notation by itself - hence // this manual conversion to a string$limit = number_format($tolerance, PRECISION, '.', '');$an    = $a0;$gn    = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn),$limit) > 0);      return $an;} bcscale(PRECISION);echo agm(1, 1 / bcsqrt(2));  Output: 0.8472130848350  ## PicoLisp (scl 80) (de agm (A G) (do 7 (prog1 (/ (+ A G) 2) (setq G (sqrt A G) A @) ) ) ) (round (agm 1.0 (*/ 1.0 1.0 (sqrt 2.0 1.0))) 70 ) Output: -> "0.8472130847939790866064991234821916364814459103269421850605793726597340" ## PL/I  arithmetic_geometric_mean: /* 31 August 2012 */ procedure options (main); declare (a, g, t) float (18); a = 1; g = 1/sqrt(2.0q0); put skip list ('The arithmetic-geometric mean of ' || a || ' and ' || g || ':'); do until (abs(a-g) < 1e-15*a); t = (a + g)/2; g = sqrt(a*g); a = t; put skip data (a, g); end; put skip list ('The result is:', a);end arithmetic_geometric_mean;  Results: The arithmetic-geometric mean of 1.00000000000000000E+0000 and 7.07106781186547524E-0001: A= 8.53553390593273762E-0001 G= 8.40896415253714543E-0001; A= 8.47224902923494153E-0001 G= 8.47201266746891460E-0001; A= 8.47213084835192807E-0001 G= 8.47213084752765367E-0001; A= 8.47213084793979087E-0001 G= 8.47213084793979087E-0001; The result is: 8.47213084793979087E-0001  ## Potion Input values should be floating point sqrt = (x) : xi = 1 7 times : xi = (xi + x / xi) / 2 . xi. agm = (x, y) : 7 times : a = (x + y) / 2 g = sqrt(x * y) x = a y = g . x. ## PowerShell  function agm ([Double]$a, [Double]$g) { [Double]$eps = 1E-15    [Double]$a1 = [Double]$g1 = 0    while([Math]::Abs($a -$g) -gt $eps) {$a1, $g1 =$a, $g$a = ($a1 +$g1)/2        $g = [Math]::Sqrt($a1*$g1) } [pscustomobject]@{ a = "$a"        g = "$g" }}agm 1 (1/[Math]::Sqrt(2))  Output: a g - - 0.847213084793979 0.847213084793979  ## Prolog  agm(A,G,A) :- abs(A-G) < 1.0e-15, !.agm(A,G,Res) :- A1 is (A+G)/2.0, G1 is sqrt(A*G),!, agm(A1,G1,Res). ?- agm(1,1/sqrt(2),Res).Res = 0.8472130847939792.  ## PureBasic Procedure.d AGM(a.d, g.d, ErrLim.d=1e-15) Protected.d ta=a+1, tg While ta <> a ta=a: tg=g a=(ta+tg)*0.5 g=Sqr(ta*tg) Wend ProcedureReturn aEndProcedure If OpenConsole() PrintN(StrD(AGM(1, 1/Sqr(2)), 16)) Input() CloseConsole()EndIf 0.8472130847939792  ## Python The calculation generates two new values from two existing values which is the classic example for the use of assignment to a list of values in the one statement, so ensuring an gn are only calculated from an-1 gn-1. ### Basic Version from math import sqrt def agm(a0, g0, tolerance=1e-10): """ Calculating the arithmetic-geometric mean of two numbers a0, g0. tolerance the tolerance for the converged value of the arithmetic-geometric mean (default value = 1e-10) """ an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0) while abs(an - gn) > tolerance: an, gn = (an + gn) / 2.0, sqrt(an * gn) return an print agm(1, 1 / sqrt(2)) Output:  0.847213084835 ### Multi-Precision Version from decimal import Decimal, getcontext def agm(a, g, tolerance=Decimal("1e-65")): while True: a, g = (a + g) / 2, (a * g).sqrt() if abs(a - g) < tolerance: return a getcontext().prec = 70print agm(Decimal(1), 1 / Decimal(2).sqrt()) Output: 0.847213084793979086606499123482191636481445910326942185060579372659734 All the digits shown are correct. ## R arithmeticMean <- function(a, b) { (a + b)/2 }geometricMean <- function(a, b) { sqrt(a * b) } arithmeticGeometricMean <- function(a, b) { rel_error <- abs(a - b) / pmax(a, b) if (all(rel_error < .Machine$double.eps, na.rm=TRUE)) {    agm <- a    return(data.frame(agm, rel_error));  }  Recall(arithmeticMean(a, b), geometricMean(a, b))  } agm <- arithmeticGeometricMean(1, 1/sqrt(2))print(format(agm, digits=16))
Output:
                 agm             rel_error
1 0.8472130847939792 1.310441309927519e-16

This function also works on vectors a and b (following the spirit of R):

a <- c(1, 1, 1)b <- c(1/sqrt(2), 1/sqrt(3), 1/2)agm <- arithmeticGeometricMean(a, b)print(format(agm, digits=16))
Output:
                 agm             rel_error
1 0.8472130847939792 1.310441309927519e-16
2 0.7741882646460426 0.000000000000000e+00
3 0.7283955155234534 0.000000000000000e+00

## Racket

This version uses Racket's normal numbers:

 #lang racket(define (agm a g [ε 1e-15])  (if (<= (- a g) ε)      a      (agm (/ (+ a g) 2) (sqrt (* a g)) ε))) (agm 1 (/ 1 (sqrt 2)))

Output:

0.8472130847939792


This alternative version uses arbitrary precision floats:

 #lang racket(require math/bigfloat)(bf-precision 200)(bfagm 1.bf (bf/ (bfsqrt 2.bf)))

Output:

(bf #e0.84721308479397908660649912348219163648144591032694218506057918)


## Raven

define agm  use  $a,$g, $errlim #$errlim $g$a "%d %g %d\n" print    $a 1.0 + as$t    repeat $a 1.0 *$g - abs -15 exp10 $a * > while$a $g + 2 / as$t        $a$g * sqrt  as $g$t as $a$g $a$t  "t: %g a: %g g: %g\n" print    $a 16 1 2 sqrt / 1 agm "agm: %.15g\n" print Output: t: 0.853553 a: 0.853553 g: 0.840896 t: 0.847225 a: 0.847225 g: 0.847201 t: 0.847213 a: 0.847213 g: 0.847213 t: 0.847213 a: 0.847213 g: 0.847213 agm: 0.847213084793979 ## REXX Also, this version of the AGM REXX program has three short circuits within it for an equality case and for two zero cases. REXX supports arbitrary precision, so the default digits can be changed if desired. /*REXX program calculates the AGM (arithmetic─geometric mean) of two (real) numbers. */parse arg a b digs . /*obtain optional numbers from the C.L.*/if digs=='' | digs=="," then digs=110 /*No DIGS specified? Then use default.*/numeric digits digs /*REXX will use lots of decimal digits.*/if a=='' | a=="," then a=1 /*No A specified? Then use the default*/if b=='' | b=="," then b=1 / sqrt(2) /* " B " " " " " */call AGM a,b /*invoke the AGM function. */say '1st # =' a /*display the A value. */say '2nd # =' b /* " " B " */say ' AGM =' agm(a, b) /* " " AGM " */exit /*stick a fork in it, we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/agm: procedure: parse arg x,y; if x=y then return x /*is this an equality case?*/ if y=0 then return 0 /*is Y equal to zero ? */ if x=0 then return y/2 /* " X " " " */ d= digits() /*obtain the current decimal digits. */ numeric digits d + 5 /*add 5 more digs to ensure convergence*/ tiny= '1e-' || (digits() - 1) /*construct a pretty tiny REXX number. */ ox= x + 1 /*ensure that the old X ¬= new X. */ do while ox\=x & abs(ox)>tiny /*compute until the old X ≡ new X. */ ox= x /*save the old value of X. */ oy= y /* " " " " " Y. */ x= (ox + oy) * .5 /*compute " new " " X. */ y= sqrt(ox * oy) /* " " " " " Y. */ end /*while*/ numeric digits d /*restore the original decimal digits. */ return x / 1 /*normalize X to new " " *//*──────────────────────────────────────────────────────────────────────────────────────*/sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2 do j=0 while h>9; m.j=h; h=h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g output when using the default input: 1st # = 1 2nd # = 0.70710678118654752440084436210484903928483593768847403658833986899536623923105351942519376716382078636750692312 AGM = 0.84721308479397908660649912348219163648144591032694218506057937265973400483413475972320029399461122994212228563  ## Ring  decimals(9)see agm(1, 1/sqrt(2)) + nlsee agm(1,1/pow(2,0.5)) + nl func agm agm,g while agm an = (agm + g)/2 gn = sqrt(agm*g) if fabs(agm-g) <= fabs(an-gn) exit ok agm = an g = gn end return gn  ## Ruby ### Flt Version The thing to note about this implementation is that it uses the Flt library for high-precision math. This lets you adapt context (including precision and epsilon) to a ridiculous-in-real-life degree. # The flt package (http://flt.rubyforge.org/) is useful for high-precision floating-point math.# It lets us control 'context' of numbers, individually or collectively -- including precision# (which adjusts the context's value of epsilon accordingly). require 'flt'include Flt BinNum.Context.precision = 512 # default 53 (bits) def agm(a,g) new_a = BinNum a new_g = BinNum g while new_a - new_g > new_a.class.Context.epsilon do old_g = new_g new_g = (new_a * new_g).sqrt new_a = (old_g + new_a) * 0.5 end new_gend puts agm(1, 1 / BinNum(2).sqrt) Output: 0.84721308479397908660649912348219163648144591032694218506057937265973400483413475972320029399461122994212228562523341096309796266583087105969971363598338426 Adjusting the precision setting (at about line 9) will of course affect this. :-) ### BigDecimal Version Ruby has a BigDecimal class in standard library require 'bigdecimal' PRECISION = 100EPSILON = 0.1 ** (PRECISION/2)BigDecimal::limit(PRECISION) def agm(a,g) while a - g > EPSILON a, g = (a+g)/2, (a*g).sqrt(PRECISION) end [a, g]end a = BigDecimal(1)g = 1 / BigDecimal(2).sqrt(PRECISION)puts agm(a, g) Output: 0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723201915677745718E0 0.8472130847939790866064991234821916364814459103269421850605793726597340048341347597231986723114767413E0  ## Run BASIC print agm(1, 1/sqr(2))print agm(1,1/2^.5)print using("#.############################",agm(1, 1/sqr(2))) function agm(agm,g) while agm an = (agm + g)/2 gn = sqr(agm*g) if abs(agm-g) <= abs(an-gn) then exit while agm = an g = gn wendend function Output: 0.847213085 0.847213085 0.8472130847939791165772005376 ## Rust // Accepts two command line arguments// cargo run --name agm arg1 arg2 fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result);} fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } }} Output: Output of running with arguments 1, 0.70710678: The arithmetic-geometric mean is 1.456791  ## Scala  def agm(a: Double, g: Double, eps: Double): Double = { if (math.abs(a - g) < eps) (a + g) / 2 else agm((a + g) / 2, math.sqrt(a * g), eps) } agm(1, math.sqrt(2)/2, 1e-15)  ## Scheme  (define agm (case-lambda ((a0 g0) ; call again with default value for tolerance (agm a0 g0 1e-8)) ((a0 g0 tolerance) ; called with three arguments (do ((a a0 (* (+ a g) 1/2)) (g g0 (sqrt (* a g)))) ((< (abs (- a g)) tolerance) a))))) (display (agm 1 (/ 1 (sqrt 2)))) (newline)  Output: 0.8472130848351929  ## Seed7 $ include "seed7_05.s7i";  include "float.s7i";  include "math.s7i"; const func float: agm (in var float: a, in var float: g) is func  result    var float: agm is 0.0;  local    const float: iota is 1.0E-7;    var float: a1 is 0.0;    var float: g1 is 0.0;  begin    if a * g < 0.0 then      raise RANGE_ERROR;    else      while abs(a - g) > iota do        a1 := (a + g) / 2.0;        g1 := sqrt(a * g);        a := a1;        g := g1;      end while;      agm := a;    end if;  end func; const proc: main is func  begin    writeln(agm(1.0, 2.0) digits 6);    writeln(agm(1.0, 1.0 / sqrt(2.0)) digits 6);  end func;
Output:
1.456791
0.847213


## SequenceL

import <Utilities/Math.sl>; agm(a, g) :=    let        iota := 1.0e-15;        arithmeticMean := 0.5 * (a + g);        geometricMean := sqrt(a * g);    in        a when abs(a-g) < iota    else        agm(arithmeticMean, geometricMean); main := agm(1.0, 1.0 / sqrt(2));
Output:
0.847213


## Sidef

func agm(a, g) {    loop {        var (a1, g1) = ((a+g)/2, sqrt(a*g))        [a1,g1] == [a,g] && return a        (a, g) = (a1, g1)    }} say agm(1, 1/sqrt(2))
Output:
0.8472130847939790866064991234821916364814

## Sinclair ZX81 BASIC

Translation of: COBOL

Works with 1k of RAM.

The specification calls for a function. Sadly that is not available to us, so this program uses a subroutine: pass the arguments in the global variables A and G, and the result will be returned in AGM. The performance is quite acceptable. Note that the subroutine clobbers A and G, so you should save them if you want to use them again.

Better precision than this is not easily obtainable on the ZX81, unfortunately.

 10 LET A=1 20 LET G=1/SQR 2 30 GOSUB 100 40 PRINT AGM 50 STOP100 LET A0=A110 LET A=(A+G)/2120 LET G=SQR (A0*G)130 IF ABS(A-G)>.00000001 THEN GOTO 100140 LET AGM=A150 RETURN
Output:
0.84721309

## SQL

Works with: oracle version 11.2 and higher

The solution uses recursive WITH clause (aka recursive CTE, recursive query, recursive factored subquery). Some, perhaps many, but not all SQL dialects support recursive WITH clause. The solution below was written and tested in Oracle SQL - Oracle has supported recursive WITH clause since version 11.2.

WITH  rec (rn, a, g, diff) AS (    SELECT  1, 1, 1/SQRT(2), 1 - 1/SQRT(2)      FROM  dual    UNION ALL    SELECT  rn + 1, (a + g)/2, SQRT(a * g), (a + g)/2 - SQRT(a * g)      FROM  rec      WHERE diff > 1e-38  )SELECT *FROM   recWHERE  diff <= 1e-38;

Output:
RN                                         A                                          G                                       DIFF
-- ----------------------------------------- ------------------------------------------ ------------------------------------------
6 0.847213084793979086606499123482191636480 0.8472130847939790866064991234821916364792 0.0000000000000000000000000000000000000008

## Stata

mata  real scalar agm(real scalar a, real scalar b) {	real scalar c	do {		c=0.5*(a+b)		b=sqrt(a*b)		a=c	} while (a-b>1e-15*a)	return(0.5*(a+b))} agm(1,1/sqrt(2))end
Output:
.8472130848

## Swift

import Darwin enum AGRError : Error {	case undefined} func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double {	var a = a	var g = g	var a1: Double = 0	var g1: Double = 0 	guard a * g >= 0 else {		throw AGRError.undefined	} 	while abs(a - g) > iota {		a1 = (a + g) / 2		g1 = sqrt(a * g)		a = a1		g = g1	} 	return a} do {	try print(agm(1, 1 / sqrt(2)))} catch {	print("agr is undefined when a * g < 0")}
Output:
0.847213084835193

## Tcl

The tricky thing about this implementation is that despite the finite precision available to IEEE doubles (which Tcl uses in its implementation of floating point arithmetic, in common with many other languages) the sequence of values does not quite converge to a single value; it gets to within a ULP and then errors prevent it from getting closer. This means that an additional termination condition is required: once a value does not change (hence the old_b variable) we have got as close as we can. Note also that we are using exact equality with floating point; this is reasonable because this is a rapidly converging sequence (it only takes 4 iterations in this case).

## VBA

Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double    Do While Abs(a - g) > tolerance        tmp = a        a = (a + g) / 2        g = Sqr(tmp * g)        Debug.Print a    Loop    agm = aEnd FunctionPublic Sub main()    Debug.Print agm(1, 1 / Sqr(2))End Sub
Output:
 0,853553390593274
0,847224902923494
0,847213084835193
0,847213084793979
0,847213084793979 

## VBScript

Translation of: BBC BASIC
 Function agm(a,g)	Do Until a = tmp_a		tmp_a = a		a = (a + g)/2		g = Sqr(tmp_a * g)	Loop	agm = aEnd Function WScript.Echo agm(1,1/Sqr(2))
Output:
0.847213084793979

## Visual Basic .NET

Translation of: C#
Imports SystemImports System.Numerics Module Module1        Function BIP(ByVal leadDig As Char, ByVal numDigs As Integer) As BigInteger            Return BigInteger.Parse(leadDig & New String("0", numDigs))        End Function         Function IntSqRoot(ByVal v As BigInteger) As BigInteger            Dim digs As Integer = Math.Max(0, v.ToString().Length / 2)            Dim term As BigInteger : IntSqRoot = BIP("3", digs)            While True                term = v / IntSqRoot                If Math.Abs(CDbl((term - IntSqRoot))) < 2 Then Exit While                IntSqRoot = (IntSqRoot + term) / 2            End While        End Function         Function CalcByAGM(ByVal digits As Integer) As BigInteger            Dim digs As Integer = digits + CInt((Math.Log(digits) / 2)), c As BigInteger,                d2 As Integer = digs * 2,                 a As BigInteger = BIP("1", digs) ' initial value = 1            CalcByAGM = IntSqRoot(BIP("5", d2 - 1)) ' initial value = square root of 0.5            While True                c = a : a = ((a + CalcByAGM) / 2) : CalcByAGM = IntSqRoot(c * CalcByAGM)                If Math.Abs(CDbl((a - CalcByAGM))) <= 1 Then Exit While            End While         End Function         Sub Main(ByVal args As String())            Dim digits As Integer = 25000            If args.Length > 0 Then                Integer.TryParse(args(0), digits)                If digits < 1 OrElse digits > 999999 Then digits = 25000            End If            Console.WriteLine("0.{0}", CalcByAGM(digits).ToString())            If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()        End SubEnd Module
Output:
0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723200293994611229942122285625233410963097962665830871059699713635983384251176326814289060389706768601616650048281188721897713309411767462019944392962902167289194499507231677897346863947606671057980557852173140349398304200422119216039839553595098193641293716340646029599967970599434351602031842648756950242174863855405981954581601742417887854192758804162719012085587685648326834140431218400804035809204559494313877815120926522254574397124286820766340954733674599621792665535348625686118543308626287287287563010835563193570668714785639088982115108836352147696979612621832943228417868113768445170018146021913694027020945996683513596327880804274345481744587363220025153952936265806614198365616491626259607434723706616902353080017375312847852558430631907454274934152685790655269406003147591020332746719686124796325510554648902820855297439651249940096625528660675804487353892185701401167716976535014084952476848993257321337028984668939194665861873752966387562266045914777044204681089256584408380320409106190031537067341195941010074743310599055058205243260099516927924174782169767810616836977141107392733439215501430220070873673659622721492587761928510523803670268904639096219076636442355380859029452340651900133423451058383417121805142550039237011113254111446126289062541335505266436535958245521562933975182514706501346410470569793556813066063293733450387109770972948759171790158173202815782884871499313408154933423677970447127859376185950851466773645546792016159342239971429840707888822790326567515965284358177957272848083564899635044041407342261101833835469759626633304220849998523007427039302772434749797179732645525465430198316949684610986907439050680137661192529197709384412997070158894931666611619945922650113111839663525025305616464315872084545229887754751772727476567216489829182392388952072076428397108847059603569219929218319015481412807665926982944644571492396663299730758139049576224389624231752095073190184244624423709864272811495111808228260538624846176751801409831274972576519837564923569028002161749055314272081534395405955635763711272816570597373374429700390560401563886630722257003892301591123769601215800817790778633512408624310735715837659265045466527873378744448344063102447570396812554539822664303534164130356138016341655752655897529445211668734512201912274667331915712407637538211069681410769263900748331757433967523196603308649735713838741960989838322028826948821913028193669499544222406972761686213695116578388850121990961606554546115432531481642493326947970041594914763231129205935165189979433500459762882172926259180894055084314663937825483351395501906533708720620640240770560758487964998436515927282645344286366154191425857771067561850172780332871751951893050318055052454260223355229007714181287986543511879180063562795936247682677864122494603381260826282540988953125276775346562432792145112295555160318184331336929617230417838551571255674049834166659269695800089537245730576945422753721602096871914703988784663672432627061911270717165908246400416799411204056571036408300024192943985530739946565396778104927010554103595133394321999250666762020783946955537605517964010097492188563113010178138885787938131720959480625392013009836502879176958279859052799477219417979970249430621584194688853281154977215799601944096234776861440850757392842988237593968232236705803341347746231128976258593243766317789749110772619097044895222045096307255155900938249040213648077920347672150485684460225544099928261631743126422857876289833806507220230103717531492635046310601885737725670066183812905806389545081270313113710437161358334880658339554312179013483988332164130576352447125115394720666703301013487165163241138288176398396295261211412632197959650986567867552507607604240959075175230219461045325643332496149012535333292237238689481278850201359663053760558493589283916304694038878549600274714871978014576595790495858022600660995249673643249668334617601066081567069751423818665036108388522097616550025160731149921612947757901997292486896382206038087602762816723701668191066335857751546503813342367223476420265585655884641601021054048985561871147358849763784064864267981865044863190774703822867114351511230036070865742988647714667473375011434581885279700605621172469217484718069486625119947289344427037830462070735493805287272062156063071882868580564521110696708028569906982576917722099867195996850779068144349493280497681154368046325993869307623507099951829512958112123570724538335482619075239515827309824818054966589790916886798407170779370595904577584091047341310960419411135775662072733779783320379730113767265853574771027978140972130961214239385473746276961504130795283737288205065871915225976508402779699176117539300672549249122984508236297556872271106584943553385049453263873648980460665597995436016950309279009245005785647723587619884898603441219534079536900299641197454906074160097885953766072290516077242859007090115663913836429904122082676962979786764903235649998199076599743987054864876909102491192709996827569701136876224404640296038370006621273457766470971132637465681150298586303226033738342135842393789611461719208307195391564378209364149678033415246450739668317319836336274339255531171201945414684488089562241789803189434123128402785837828900962420954134500210107273632328527257620964685199446824055062939174205330170646191721517884429670531433550377231070971608028514531414410610502311731087777993324893208772722989782133012083407430560499815996320268779330715694030243915611892676751724951176652624854709604199147311365792069733099608889728678978073558757850062357515712377165304206363100270312929669402542196787716884665572758089830646766200701467958569308222062090533082778222650311252027873351251915991889390028431921816668654843487962197221176390495989579360733094369745762894320038411755294159475474718393638114412561035102345958108076855898565700744530890942866925119010171812282668934926952826105251855673604587770228814782144696850091834721974142054612807234795005981176636452615019078854547119380355714593074463565626075278751882438640950696464981513117059145799061937656085865017561686450192409832723572433368881308002218636870020964111972430360355864979377331491674959315118867353502550598230304706028474045845667684962093450639630290944163251640869288981450724787772767337803382892950497838434294376656673729758743057514103641747686163962419894190473099610022842807944492002690484525413918824600155908913194325561036576936236416178464669314145610998403831226550411525149444538004209042871818246843162461055263767752097010406394468783737501743608975169348688765128345367755278654709023154202945387307614119664976752191980890210577263347239795896872292335776904124445868229780620988708981601817952145492037095625285073302325506009661132947914844341668742987265420408355205645640442117412406504193236283129664312633076871545044495073355441820079366970133124463882436006243981671240934680632216977170156359041760984126197780105258695663465414470251113538284101027857954306180235727550093051395563777104392279959711411827820335811839895233872011962666682878121534333119335301980065251192410359431507242725158977422690143132514977522062114865320952829178417267885279182595018942830664545338082943854849139066009015264631566694081305168985773844571611013477352843955866391803147712899724897723269508309592086031639086017942214680489253714713566949064759756635040507610593030015345361344683461413628484047306390958006486248221139953996212210799277405320305975698713150142923894182198921844586149684530634607828705886426256034976711338539075304736074752056972553266351796405948813812764851913023282612955172074759449886392511104978597741010464725883174496948927333228106840894947597870676901221695186965819440613669431032341161961316055438160872830554350481907115975274266591736369300198098879762721866262854331190608603428061915184529782370363989844941441788900860278222099839022747283796741142957892434654564040285516747837253883138615478050803523689358333288735587979488680498097140686893671941671150430740257510226908170738592853583739097642497592242106183237251702142832098675374450713321896366690856563496330607745568301183714940025840499776611352553284766561887059297821272989972959279478182042871980710227864618380700640108313897567711275413622112744453453558495976925257575831299903953695989324995132410678426561155674366008873748427403823481178491100212353710801533440770817528157942292854873168986398007189626868498577906194258200017317847379797581560926908728785027002441474128195357887396474585945989953554341280165355304905852879467439822060623038668885270050521890492778219751411559543554912532611508743228043560956317611632181179416488420692847431569913367778795691370559270495989391110078622411244993171953989030821530712697180735281429443737405818058978428710156632587372660001229618040378042909317516047397993123688246631452459079251208891697476543024570532063867046841105403420143766444221321275079984629915701014710655294614674639224957453061968220342544481624754597726965343025068682420528809969244892365217140381774928293591731548128491962143330408090430686723368206071629128939851740625590428224755815950910232420616081636351144095326796797446621465812189738372570520183180067850518123327074323605176023656530460591972824676204649795075712433230621061523661722932446828625111057783285471237185790648230242919912975347734061881239322440512379322924869823930209460579946850220935645801886473720579895081996828508790812064517546479284665702999349614635453381698987901207395953429945805188468291883563113613887963131617344220750621821294504750343373064014035661410640332086762144318392843896999426828683608253559124275148838339226466822296332365748898159910490237457127807706285323689569002846974295477424842233552385904929922545331827069396608860351849116687510855200626534096641261122006929055636905274406489364008701517166292935652992147442079387371064739913645340218593151820157611005940555660016631819091634821281864306841825699119431626671589858867365048898058083297214519581152583297435806443269828920936428495961697533992750238383269580110960895478645725610978537829730707491816874473573118904984949078163221012711091939835763889275313174997832136828093289434933093008786888412709207635900764806511830131744081313817077647856208698345684995769633324155669908593714952843730378217416678101262473775484495940827759804285781377544844619292953715335974187135555667802860648491797482755902237737618970377033248977434923537652355713907643148896714413309953967987104628474772177218586585198597128216573914857449432832030846416395609630104737047398845030793695692868346411376422630856869568815205374919629456288108598701591076495501927266737827651723745001366242105114670918489895226972765620697626305509493893209921637752941533506002710943001897733922184539033735100794276466523250904537794047821235562048863896964029102918267302436888801398275004965568895554036273975411835927700909429183995839629853595212346557370775168043202387240100878629236255848492022129605594823231763521420711765042769974780129024915091487334720498120835348652124623353885847170047012059239458254152231296760130726828023204463364423410002647434156839912388104804981949120094024489572030188122064099699734084373609581244994591323179335933381919736024885337564103043564373230200132835999061529839491671068799769392669903352206408372958699430435767091716979669844233265683073255000032131290270671910634242831139004947817930730455621994391207220949547191654710960540491994418605172498147181299406311929017373810117661735697649563667562027889559209950468616344030525065868173584026942873663343116783290383747565805099078398538492606472124656513066048767360858579021838664324162719821037877279633773674269294566398547052937774585469220700204633035734350551753701405031035552657808272989704923054754558900927541094450401415712535768280107491517462792853378309957063195287683823780636817784166118633474778942016619018614338880451488417436168145481036232103764327459565336462939729529404995266169118165774001811614649765440758915091255759910085527310773370321360350561940735040522341453322430660474360025721259012720251714695260546243921581515173266145481224361986035738692246540368855978775008326838693067425375934937697269138253278057013568344186231501031895512870549403859476094927859052000988144771583971471397181372055496033119164223919531323021387599271740190462241392591480062017156181588935294512197819370474570853869542790023308041058800725094751231893079684463722417117059460619761475197732389610131555640637230931027947697393822947634689393375594689366509404991025261216353807200564424102647116463980049099853557028205939605455447925555862491870923218013045410293633289361932659635085141363720729314276776326781784006678008955865487778263082281844650815850962569502069779788966414055110142118553344401594888028470165790446492630921612023806856647263161132699553358541432054744289672817329171401064373059396022248273396972086580919428880396334434487646758338559735133333062843978635706219638221770550067260760757020230554832843933593736962408540495734441514188914381220607683232906338433268593592822664836162287681567093130378967832774148784528783823247403834089344942780604558901818367313360227116728530442719450731574091360006635608918121904030501931902816397213579069602521192956245595283585044262778799321446822104132561227129030246961037485513459910666260608214354612646379084695233868055923782282861036138641601375392042688837119260274208747450778273018088264829799148923343465336393032799181647699552946889290406033547026518831782582139191507311702233683956494533563041419244283850395420907333751111705379081976806137884615700429239226478813822848667254341558069442119350683600048846556159908333918472426318369892813069565494915316501031321636122401829871151722240152336810147624616989641725974883872718959876560235032482870974146879341537870881457319032792045321923168585273510837205594245660154564794467544956685914299798823317981905957412536868103219479808260387624104484873020890506587193426417409200793666988360146230976275984411307152575891628801058170935307258888765438625320184862493192363856821656260311043452831303070497229133487303324093373695634797488982493001741580565918212328834385810125017153730539846204343245572148208854752349473046776142928291539148585268850542307445054819261916697597503150344720821184531390768348600690877275207724648570659763674093617314343699039949890837571024654565081496201598880520448337949170704084830390941751242627586986866864429349824241966740362707603239920140718307127075983713200071244715952364278216248847293391371363404613897408889417839932009005154360842161889132895774035438445610764501601046270957909865249534201476601633045829353765345452343866741379873125501702955458280954789754249736710903859826460689562224125730320814089060702520614045781528236850450576571004380422859203272072919022213465183593025594294087530699470110115341647678562354357502399373641453289577349987616750224091979412189318805901797744432940362403855108249195475184117701415082055499914880328650006506903016502845561653351489071197419417231002966324793664082536454210489764044510808112390636818859490866041834002563156266121150636530929721958068717763205146135558130950081456382611241652148716359364355364626887274627668036863068008823124997057270649626533528542427372344975748277606130081806341963908309788224947892294952589166578261004442444011032674853962012002339712983462424236328371107426730990212602911003810905075184052326627390503193485601548551063262431877897087889519816807309635422309600553626773590509947340874437102481672797000949458970763018534495268010673098424682884888376001669588713735596924455523853639617878813420930937648484840684294049973149466357845582668824582535663539328972931670006623812836851967062769788976992900959783806955744076908095006959465957832536606606021300052501299814521509962930711070061579600475991882982747275187749247267477075541367926577506014952833685983808535342087421568275880125999285590341009796301994374100139497559182291884670574101063493159452795474203205729535659686958686309732848838117424382705844173565966748531520288619119212528639873956092812751322321411975422934309237556933961467274051756952937669906105236544834407861042557669454187348637935607086124047368835677343714012635012082376517639056205060407689472940029316207976034289684689763986783055394151523071372556050291467117512345193213196257179194091172895112394811359886058806242403783575199648708833015067921017542906053141883697861102789683068966685186841047018236478070061552988314988311160194996581503867439046710524717599372670920338105198477700612275230269803853761991773190713310581677900865148017244044640376472067378458339538288938090294127398791047525425848656169804854329678228104045399766116512329072916161999262875108651934173111651330565918298176258476942870845481902934422218602797740551929126618894870801051592286014923839349088978216696510949976167317958352210579135872435502978211142528058438095977047217789382738291647188267143786582146132601126351655428051641842218826414189068661918649275171898473503749660268603367196130491592260944214677309207447679471191782020991322687218494754837800384872614887274288126557917479463415144454510559946456761447829338796801541288641809828488552595961739917765763526708198998540893074456419929690245927540514364752564866193295990306832386675751847974101534291141650875357289247968428024844022021189839024343019074659247056399191002422581439906839145785745809534409682615848973161582203983769100517165439059009332682758641975343948377190597307946502921036364197261592387218787609568719768193448195585256702414143367159088969420478179893655635177510159100502658594727944864231731189272715352504603408189622738311460054685240639885547185968408827772216225058636841937996411264632107063981877379436965025210443862232067151722841147543348280304170767543855544758432127184639628139192588497250905104094413445042984534607184887565424070969013859261164551967656370842971067649463576620128538192679120411097780585735206273751046694359159207490437896612980871627432238503903200747785421106389954495418599764142811639519723970807898604875826412654482514992322728617657138969733453783596360396270903800266892132438915900937522503365117193777065722629534125706898090779319887999707678326330367066734265792539584995058236399861049287847997618589138402474479074235598179601325496065268498873351839728719125189938832434160260835616449667090239004227321622193156793994400121515991005438108452008113310320755349248448736926831444446661078027589177746836934458504594996323715604380025822761890860307455081993189289970328554950733024012176634951531582783089778643225455622174430575282514370808718431447081100451010861212269993139696936106652360872112635901234482826228442719128197318726976197474039807177837818816051980186225723297022476249476791293268402018806179523622917460139857660423357909440772301735301533797443564373858424825053806154719307522442930911720744767714952214191939097420171602697055782583692370729781154555257078800495566691547790183071959166351668705798433695161118915375191239671411637819700078495311538632676636926917201697840904039696980486182843641777680408844920843990109595120575134086106037535340815573708718831389833765632253365094601030868611190124154179490065983536692638351505840202609825957038542914586502569215798730980706459708232637713823558573770422562814426279349776942935880402088274202826378644361593581793081785830626571226347945217406521641079802933357396113740430192829436788462683243244907881268478728198867620293106251026494858654946396478915436624063557034668847778481527141247043064604061561427732010700357585503399527937752971615662838111851808552341418757725602521799510366277147755229103683953979232937518470013121542865246411152629783074232865118948197892092468274639225034617981978102131340002227230322223473152101603382614564581647211034088319720710942284963700609051026094304473012680179534915289461304610103306181131482136614187498546662880958567829930882499396665549962438001582108241078119032818950685505758199090884859709549457317667220141776418725381686242629385297409262655153675815553768336845182015479396486281053385781097943479307795612554124082856308964707635482727658604790077918304180657432085530277668689997889793948698795072965297144805088951766068438667305666291192985791320659875276209719727939020847384621027715209421238626693025626045120911740207923365815759327469684190635418736609252913811657435704572829041743383259688439135695644261782300694911815699429429552917021135384246870489057231300564610620202965324662847784390202519471581513379117489825704011553285862497369071484480074718471929067100213319127483431066220187414184132870892070927586674503766416928012111286705783213258594853998713287909847264055001397204315347093043650971808407085372331611111161163260026217174881373762104601360054405185063317524523198978529106564646603827874887033113430762004135651429548284350224545440057139238649252628342390795170536664048382687501346985026376797452892628528836654431486803662832963891225420709468733559766951200768750729294062317643560479665180784709540899106851499800335873538798942202890154280071790648227618529868307928613720439699372650361028546335215771836457184338195003192627235229365434338752280951415249805257748636604861358053916266218347510582564726031163344200237752714062511207533229490952552233074466411557226024243589526948292743584402262200146624709386653387904839232051622427643333928264264095396434182241670565846124476044881773770578266908088083441882262261134263272741924841565112103504713196158309499443877943907838066465620714318730989528087415316762165760222799085019961558757833239388336516947814207753326228369452661200546582077140082606039883925515094886155317733344750682267921184969044888047907010204328820587467236167297124606234197336970480786776860998946471237909752570649804238181586539943498303594116225834772902048935683847719780497321491144874874991561667925385743801086450022013484371960972791276113692503512315528253574165582610726609946765701611185568425782687842219783399432914873489392389215329896629423270313584561580472399362482740937396676156325798199403600665503961394188118316426714448566487446834858709943474371012885926755247383146218143432123212475861847692580312891323387866452752520432448479653277627332017135197984953014247380597643031865581040360989753746922633601559652565228488816703746005423504365581343832987087273414206285914784700727499941488512944165791821238387605657254567179408563728927700279021860478842351992457305181197637773159441299439386053455915965812712386295531591818284192388135724500924623850709774189143757567688620693643360826366037435517318502695423976617303882627504383896524716042868973954806164066460656537905053942279570880184082966495697819240673730707625301425754222176386023043180947705675890568172303332631140880288609288015177746908237506313775092527533163800983678664599194988101810822244685844398486597244962109799933160526858781006192712588969440066997975564880094089562624291753183438892003566311336876393146384781276313023782556219831179106178085668790330978953974750523954531663063816955977765334765594990877920235971866662357248705555821648403608492521780343110435664741760019363161347419611312665720606428221769042854124656020456145948431774468321390602126772741118944367580444291158375742357250021419146749334287116084058263947048563637037567960479707349081368108383856211384139158705255361507399198312547343452740459654792697253954244755599033280971664357803964694574981336862115241049028858177920631820825506916645550784089962833317474487395160722939925885469418863797824014463529526498257285663210305355089105717174867411521849477407758915111581948906885197195976812921402351145438273886755728832042660833803075951572754557763972623847067463401162634695323181522954971899690647043890353657443064443647271644955086851987181709281406874644947080685617457088510506476649433220539108509753998789798067227886994313463279903237260493315016338677403943051949329714250532111766901182029360448269416630130980111122744365495327124238853493997327774999933529666713830796944113571907996950609982192320687889262441611017590925490461028655351203248828567373514842932400983163321126446037617204620938427052890377225105764396893898372277964046845270569432108545527382946271102273724329060629460165173265459446356986135096609520996203850801089967366647007391870576067980133705834704656750336937959892815443738076551103171908198590137108863960070070563187309925148094798923861905247923098330971793822624572560011957113072238679043125574217913563311114664608326838259676235601847277220919801312198322417907947613497742174816883393427887640301433431879849341771661325650642266826463838842978687544381098675438645949184608207863334604646941842977881383385775551967000566984045658764213085205705014831456825938770242861922467117318737082222462753831336593786820143553512660014624624943588080657269357308448561507390184276116721516220484045991383967425164850842

## XPL0

include c:\cxpl\codesi;real A, A1, G;[Format(0, 16);A:= 1.0;  G:= 1.0/sqrt(2.0);repeat	A1:= (A+G)/2.0;	G:= sqrt(A*G);	A:= A1;	RlOut(0, A);  RlOut(0, G);  RlOut(0, A-G);  CrLf(0);until	A=G;]

Output:

 8.5355339059327400E-001 8.4089641525371500E-001 1.2656975339559100E-002
8.4722490292349400E-001 8.4720126674689100E-001 2.3636176602726000E-005
8.4721308483519300E-001 8.4721308475276500E-001 8.2427509262572600E-011
8.4721308479397900E-001 8.4721308479397900E-001 0.0000000000000000E+000


## zkl

Translation of: XPL0
a:=1.0; g:=1.0/(2.0).sqrt();while(not a.closeTo(g,1.0e-15)){   a1:=(a+g)/2.0; g=(a*g).sqrt(); a=a1;    println(a,"  ",g," ",a-g);}
Output:
0.853553  0.840896 0.012657
0.847225  0.847201 2.36362e-05
0.847213  0.847213 8.24275e-11
0.847213  0.847213 1.11022e-16


Or, using tail recursion

fcn(a=1.0, g=1.0/(2.0).sqrt()){ println(a," ",g," ",a-g);   if(a.closeTo(g,1.0e-15)) return(a) else return(self.fcn((a+g)/2.0, (a*g).sqrt()));}()
Output:
1 0.707107 0.292893
0.853553 0.840896 0.012657
0.847225 0.847201 2.36362e-05
0.847213 0.847213 8.24275e-11
0.847213 0.847213 1.11022e-16


## ZX Spectrum Basic

Translation of: ERRE
10 LET a=1: LET g=1/SQR 220 LET ta=a30 LET a=(a+g)/240 LET g=SQR (ta*g)50 IF a<ta THEN GO TO 2060 PRINT a
Output:
0.84721309