Arithmetic-geometric mean: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 22:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F agm(a0, g0, tolerance = 1e-10)
V an = (a0 + g0) / 2.0
V gn = sqrt(a0 * g0)
Line 35:
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
<syntaxhighlight lang="360asm">AGM CSECT
USING AGM,R13
SAVEAREA B STM-SAVEAREA(R15)
Line 132:
 
=={{header|8th}}==
<syntaxhighlight lang="8th">: epsilon 1.0e-12 ;
 
with: n
Line 155:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang=Action"action!">INCLUDE "H6:REALMATH.ACT"
 
PROC Agm(REAL POINTER a0,g0,result)
Line 199:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
 
procedure Arith_Geom_Mean is
Line 232:
 
Printing out the difference between the means at each iteration nicely demonstrates the quadratic convergence.
<syntaxhighlight lang="algol68">
BEGIN
PROC agm = (LONG REAL x, y) LONG REAL :
Line 269:
 
=={{header|APL}}==
<syntaxhighlight lang=APL"apl">
agd←{(⍺-⍵)<10*¯8:⍺⋄((⍺+⍵)÷2)∇(⍺×⍵)*÷2}
1 agd ÷2*÷2
Line 278:
By functional composition:
 
<syntaxhighlight lang=AppleScript"applescript">-- ARITHMETIC GEOMETRIC MEAN -------------------------------------------------
 
property tolerance : 1.0E-5
Line 341:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AHK"ahk">agm(a, g, tolerance=1.0e-15){
While abs(a-g) > tolerance
{
Line 356:
 
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk">#!/usr/bin/awk -f
BEGIN {
printf "%.16g\n", agm(1.0,sqrt(0.5))
Line 379:
==={{header|BASIC}}===
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">PRINT AGM(1, 1 / SQR(2))
END
 
Line 397:
 
==={{header|BASIC256}}===
<syntaxhighlight lang=BASIC256"basic256">print AGM(1, 1 / sqr(2))
end
 
Line 417:
 
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="commodorebasic">10 A = 1
20 G = 1/SQR(2)
30 GOSUB 100
Line 430:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> *FLOAT 64
@% = &1010
PRINT FNagm(1, 1/SQR(2))
Line 450:
 
==={{header|GW-BASIC}}===
<syntaxhighlight lang="gwbasic">10 A = 1
20 G = 1!/SQR(2!)
30 FOR I=1 TO 20 'twenty iterations is plenty
Line 460:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS"is-BASICbasic">100 PRINT AGM(1,1/SQR(2))
110 DEF AGM(A,G)
120 DO
Line 471:
==={{header|True BASIC}}===
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">FUNCTION AGM (a, g)
DO
LET ta = (a + g) / 2
Line 492:
 
=={{header|bc}}==
<syntaxhighlight lang="bc">/* Calculate the arithmethic-geometric mean of two positive
* numbers x and y.
* Result will have d digits after the decimal point.
Line 522:
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">AGM ← {
(|𝕨-𝕩) ≤ 1e¯15? 𝕨;
(0.5×𝕨+𝕩) 𝕊 √𝕨×𝕩
Line 533:
=={{header|C}}==
===Basic===
<syntaxhighlight lang="c">#include<math.h>
#include<stdio.h>
#include<stdlib.h>
Line 579:
 
===GMP===
<syntaxhighlight lang="cpp">/*Arithmetic Geometric Mean of 1 and 1/sqrt(2)
 
Nigel_Galloway
Line 628:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">namespace RosettaCode.ArithmeticGeometricMean
{
using System;
Line 710:
Note that the last 5 digits are spurious, as ''maximumRelativeDifference'' was only specified to be 1e-5. Using 1e-11 instead will give the result 0.847213084793979, which is as far as ''double'' can take it.
===Using Decimal Type===
<syntaxhighlight lang="csharp">using System;
 
class Program {
Line 734:
{{Libheader|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.
<syntaxhighlight lang="csharp">using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
Line 768:
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include<bits/stdc++.h>
using namespace std;
Line 806:
 
=={{header|Clojure}}==
<syntaxhighlight lang="lisp">(ns agmcompute
(:gen-class))
 
Line 838:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. ARITHMETIC-GEOMETRIC-MEAN-PROG.
DATA DIVISION.
Line 875:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="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))
Line 891:
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio, std.math, std.meta, std.typecons;
 
real agm(real a, real g, in int bitPrecision=60) pure nothrow @nogc @safe {
Line 910:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi"delphi">
program geometric_mean;
 
Line 962:
=={{header|EchoLisp}}==
We use the '''(~= a b)''' operator which tests for |a - b| < ε = (math-precision).
<syntaxhighlight lang="scheme">
(lib 'math)
 
Line 981:
=={{header|Elixir}}==
 
<syntaxhighlight lang=Elixir"elixir">defmodule ArithhGeom do
def mean(a,g,tol) when abs(a-g) <= tol, do: a
def mean(a,g,tol) do
Line 996:
 
=={{header|Erlang}}==
<syntaxhighlight lang=Erlang"erlang">%% Arithmetic Geometric Mean of 1 and 1 / sqrt(2)
%% Author: Abhay Jain
 
Line 1,016:
agm(A1, B1).</syntaxhighlight>
Output:
<syntaxhighlight lang=Erlang"erlang">AGM = 0.8472130848351929</syntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM AGM
 
Line 1,045:
=={{header|F_Sharp|F#}}==
{{trans|OCaml}}
<syntaxhighlight lang="fsharp">let rec agm a g precision =
if precision > abs(a - g) then a else
agm (0.5 * (a + g)) (sqrt (a * g)) precision
Line 1,054:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: kernel math math.functions prettyprint ;
IN: rosetta-code.arithmetic-geometric-mean
 
Line 1,066:
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: agm ( a g -- m )
begin
fover fover f+ 2e f/
Line 1,078:
=={{header|Fortran}}==
A '''Fortran 77''' implementation
<syntaxhighlight lang="fortran"> function agm(a,b)
implicit none
double precision agm,a,b,eps,c
Line 1,095:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 16-09-2015
' compile with: fbc -s console
 
Line 1,127:
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
 
<syntaxhighlight lang=Futhark"futhark">
import "futlib/math"
 
Line 1,142:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 1,169:
{{trans|Java}}
Solution:
<syntaxhighlight lang="groovy">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] }
Line 1,176:
 
Test:
<syntaxhighlight lang="groovy">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</syntaxhighlight>
 
Line 1,183:
 
=={{header|Haskell}}==
<syntaxhighlight lang="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".
Line 1,208:
=={{header|Icon}} and {{header|Unicon}}==
 
<syntaxhighlight lang="text">procedure main(A)
a := real(A[1]) | 1.0
g := real(A[2]) | (1 / 2^0.5)
Line 1,239:
First, the basic approach (with display precision set to 16 digits, which slightly exceeds the accuracy of 64 bit IEEE floating point arithmetic):
 
<syntaxhighlight lang="j">mean=: +/ % #
(mean , */ %:~ #)^:_] 1,%%:2
0.8472130847939792 0.8472130847939791</syntaxhighlight>
Line 1,245:
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):
 
<syntaxhighlight lang="j"> ~.(mean , */ %:~ #)^:_] 1,%%:2
0.8472130847939792</syntaxhighlight>
 
Another variation would be to show intermediate values, in the limit process:
 
<syntaxhighlight lang="j"> (mean, */ %:~ #)^:a: 1,%%:2
1 0.7071067811865475
0.8535533905932737 0.8408964152537145
Line 1,263:
Borrowing routines from that page, but going with a default of approximately 100 digits of precision:
 
<syntaxhighlight lang=J"j">DP=:101
 
round=: DP&$: : (4 : 0)
Line 1,296:
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:
 
<syntaxhighlight lang=J"j">fmt=:[: ;:inv DP&$: : (4 :0)&.>
x{.deb (x*2j1)":y
)
Line 1,306:
Some example uses:
 
<syntaxhighlight lang=J"j"> fmt sqrt 2
1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572
fmt *~sqrt 2
Line 1,317:
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:
 
<syntaxhighlight lang=J"j">geomean=: */ root~ #
geomean2=: [: sqrt */</syntaxhighlight>
 
A quick test to make sure these can be equivalent:
 
<syntaxhighlight lang=J"j"> fmt geomean 3 5
3.872983346207416885179265399782399610832921705291590826587573766113483091936979033519287376858673517
fmt geomean2 3 5
Line 1,329:
Now for our task example:
 
<syntaxhighlight lang=J"j"> fmt (mean, geomean2)^:(epsilon <&| -/)^:a: 1,%sqrt 2
1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0.707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767163820786
0.853553390593273762200422181052424519642417968844237018294169934497683119615526759712596883581910393 0.840896415253714543031125476233214895040034262356784510813226085974924754953902239814324004199292536
Line 1,343:
=={{header|Java}}==
 
<syntaxhighlight lang=Java"java">/*
* Arithmetic-Geometric Mean of 1 & 1/sqrt(2)
* Brendan Shaklovitz
Line 1,372:
 
===ES5===
<syntaxhighlight lang=JavaScript"javascript">function agm(a0, g0) {
var an = (a0 + g0) / 2,
gn = Math.sqrt(a0 * g0);
Line 1,384:
 
===ES6===
<syntaxhighlight lang=JavaScript"javascript">(() => {
'use strict';
 
Line 1,429:
 
{{Out}}
<syntaxhighlight lang=JavaScript"javascript">0.8472130848351929</syntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
Naive version that assumes tolerance is appropriately specified:
<syntaxhighlight lang="jq">def naive_agm(a; g; tolerance):
def abs: if . < 0 then -. else . end;
def _agm:
Line 1,444:
[a, g] | _agm | .[0] ;</syntaxhighlight>
This version avoids an infinite loop if the requested tolerance is too small:
<syntaxhighlight lang="jq">def agm(a; g; tolerance):
def abs: if . < 0 then -. else . end;
def _agm:
Line 1,466:
=={{header|Julia}}==
{{works with|Julia|1.2}}
<syntaxhighlight lang=Julia"julia">function agm(x, y, e::Real = 5)
(x ≤ 0 || y ≤ 0 || e ≤ 0) && throw(DomainError("x, y must be strictly positive"))
g, a = minmax(x, y)
Line 1,498:
=={{header|Klingphix}}==
{{trans|Oforth}}
<syntaxhighlight lang=Klingphix"klingphix">include ..\Utilitys.tlhy
 
:agm [ over over + 2 / rot rot * sqrt ] [ over over tostr swap tostr # ] while drop ;
Line 1,508:
" " input</syntaxhighlight>
{{trans|F#}}
<syntaxhighlight lang=Klingphix"klingphix">include ..\Utilitys.tlhy
 
:agm %a %g %p !p !g !a
Line 1,522:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.5-2
 
fun agm(a: Double, g: Double): Double {
Line 1,549:
=={{header|LFE}}==
 
<syntaxhighlight lang="lisp">
(defun agm (a g)
(agm a g 1.0e-15))
Line 1,575:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
print agm(1, 1/sqr(2))
print using("#.#################",agm(1, 1/sqr(2)))
Line 1,593:
 
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode"livecode">function agm aa,g
put abs(aa-g) into absdiff
put (aa+g)/2 into aan
Line 1,607:
end agm</syntaxhighlight>
Example
<syntaxhighlight lang=LiveCode"livecode">put agm(1, 1/sqrt(2))
-- ouput
-- 0.847213</syntaxhighlight>
 
=={{header|LLVM}}==
<syntaxhighlight lang="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.
Line 1,719:
 
=={{header|Logo}}==
<syntaxhighlight lang="logo">to about :a :b
output and [:a - :b < 1e-15] [:a - :b > -1e-15]
end
Line 1,732:
=={{header|Lua}}==
 
<syntaxhighlight lang="lua">function agm(a, b, tolerance)
if not tolerance or tolerance < 1e-15 then
tolerance = 1e-15
Line 1,749:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Checkit {
Function Agm {
Line 1,768:
=={{header|Maple}}==
Maple provides this function under the name GaussAGM. To compute a floating point approximation, use evalf.
<syntaxhighlight lang=Maple"maple">
> evalf( GaussAGM( 1, 1 / sqrt( 2 ) ) ); # default precision is 10 digits
0.8472130847
Line 1,777:
</syntaxhighlight>
Alternatively, if one or both arguments is already a float, Maple will compute a floating point approximation automatically.
<syntaxhighlight lang=Maple"maple">
> GaussAGM( 1.0, 1 / sqrt( 2 ) );
0.8472130847
Line 1,784:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
To any arbitrary precision, just increase PrecisionDigits
<syntaxhighlight lang=Mathematica"mathematica">PrecisionDigits = 85;
AGMean[a_, b_] := FixedPoint[{ Tr@#/2, Sqrt[Times@@#] }&, N[{a,b}, PrecisionDigits]]〚1〛</syntaxhighlight>
 
Line 1,791:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=MATLAB"matlab">function [a,g]=agm(a,g)
%%arithmetic_geometric_mean(a,g)
while (1)
Line 1,805:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">agm(a, b) := %pi/4*(a + b)/elliptic_kc(((a - b)/(a + b))^2)$
 
agm(1, 1/sqrt(2)), bfloat, fpprec: 85;
Line 1,811:
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 <-> П0 1 ВП 8 /-/ П2 ИП0 ИП1
- ИП2 - /-/ x<0 31 ИП1 П3 ИП0 ИП1
* КвКор П1 ИП0 ИП3 + 2 / П0 БП
Line 1,818:
=={{header|Modula-2}}==
{{trans|C}}
<syntaxhighlight lang="modula2">MODULE AGM;
FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;
FROM LongConv IMPORT ValueReal;
Line 1,898:
=={{header|NetRexx}}==
{{trans|Java}}
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,929:
 
=={{header|NewLISP}}==
<syntaxhighlight lang=NewLISP"newlisp">
(define (a-next a g) (mul 0.5 (add a g)))
 
Line 1,954:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import math
 
proc agm(a, g: float,delta: float = 1.0e-15): float =
Line 1,976:
See first 24 iterations:
 
<syntaxhighlight lang="nim">from math import sqrt
from strutils import parseFloat, formatFloat, ffDecimal
 
Line 1,999:
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="oberon2">
MODULE Agm;
IMPORT
Line 2,033:
=={{header|Objeck}}==
{{trans|Java}}
<syntaxhighlight lang="objeck">
class ArithmeticMean {
function : Amg(a : Float, g : Float) ~ Nil {
Line 2,056:
 
=={{header|OCaml}}==
<syntaxhighlight lang="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
Line 2,066:
=={{header|Oforth}}==
 
<syntaxhighlight lang=Oforth"oforth">: agm \ a b -- m
while( 2dup <> ) [ 2dup + 2 / -rot * sqrt ] drop ;</syntaxhighlight>
 
Usage :
<syntaxhighlight lang=Oforth"oforth">1 2 sqrt inv agm</syntaxhighlight>
 
{{out}}
Line 2,078:
 
=={{header|OOC}}==
<syntaxhighlight lang="ooc">
import math // import for sqrt() function
 
Line 2,103:
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">numeric digits 20
say agm(1, 1/rxcalcsqrt(2,16))
 
Line 2,126:
=={{header|PARI/GP}}==
Built-in:
<syntaxhighlight lang="parigp">agm(1,1/sqrt(2))</syntaxhighlight>
 
Iteration:
<syntaxhighlight lang="parigp">agm2(x,y)=if(x==y,x,agm2((x+y)/2,sqrt(x*y))</syntaxhighlight>
 
=={{header|Pascal}}==
Line 2,135:
{{libheader|GMP}}
Port of the C example:
<syntaxhighlight lang="pascal">Program ArithmeticGeometricMean;
 
uses
Line 2,173:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl -w
 
my ($a0, $g0, $a1, $g1);
Line 2,194:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">agm</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">tolerance</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1.0e-15</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">-</span><span style="color: #000000;">g</span><span style="color: #0000FF;">)></span><span style="color: #000000;">tolerance</span> <span style="color: #008080;">do</span>
Line 2,214:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
1.0e-15 var tolerance
Line 2,231:
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
define('PRECISION', 13);
 
Line 2,261:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">main =>
println(agm(1.0, 1/sqrt(2))).
 
Line 2,274:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(scl 80)
 
(de agm (A G)
Line 2,288:
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii">
arithmetic_geometric_mean: /* 31 August 2012 */
procedure options (main);
Line 2,315:
=={{header|Potion}}==
Input values should be floating point
<syntaxhighlight lang="potion">sqrt = (x) :
xi = 1
7 times :
Line 2,334:
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">
function agm ([Double]$a, [Double]$g) {
[Double]$eps = 1E-15
Line 2,358:
 
=={{header|Prolog}}==
<syntaxhighlight lang=Prolog"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).
Line 2,367:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Procedure.d AGM(a.d, g.d, ErrLim.d=1e-15)
Protected.d ta=a+1, tg
While ta <> a
Line 2,389:
 
===Basic Version===
<syntaxhighlight lang="python">from math import sqrt
 
def agm(a0, g0, tolerance=1e-10):
Line 2,408:
<pre> 0.847213084835</pre>
===Multi-Precision Version===
<syntaxhighlight lang="python">from decimal import Decimal, getcontext
 
def agm(a, g, tolerance=Decimal("1e-65")):
Line 2,424:
=={{header|Quackery}}==
 
<syntaxhighlight lang=Quackery"quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ temp put
Line 2,454:
 
=={{header|R}}==
<syntaxhighlight lang="r">arithmeticMean <- function(a, b) { (a + b)/2 }
geometricMean <- function(a, b) { sqrt(a * b) }
 
Line 2,472:
1 0.8472130847939792 1.310441309927519e-16</pre>
This function also works on vectors a and b (following the spirit of R):
<syntaxhighlight lang="r">a <- c(1, 1, 1)
b <- c(1/sqrt(2), 1/sqrt(3), 1/2)
agm <- arithmeticGeometricMean(a, b)
Line 2,484:
=={{header|Racket}}==
This version uses Racket's normal numbers:
<syntaxhighlight lang="racket">
#lang racket
(define (agm a g [ε 1e-15])
Line 2,499:
 
This alternative version uses arbitrary precision floats:
<syntaxhighlight lang="racket">
#lang racket
(require math/bigfloat)
Line 2,512:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang=perl6"raku" line>sub agm( $a is copy, $g is copy ) {
($a, $g) = ($a + $g)/2, sqrt $a * $g until $a ≅ $g;
return $a;
Line 2,522:
 
It's also possible to write it recursively:
<syntaxhighlight lang=perl6"raku" line>sub agm( $a, $g ) {
$a ≅ $g ?? $a !! agm(|@$_)
given ($a + $g)/2, sqrt $a * $g;
Line 2,530:
 
=={{header|Raven}}==
<syntaxhighlight lang=Raven"raven">define agm use $a, $g, $errlim
# $errlim $g $a "%d %g %d\n" print
$a 1.0 + as $t
Line 2,550:
 
=={{header|Relation}}==
<syntaxhighlight lang=Relation"relation">
function agm(x,y)
set a = x
Line 2,581:
 
REXX supports arbitrary precision, so the default digits can be changed if desired.
<syntaxhighlight lang="rexx">/*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= 120 /*No DIGS specified? Then use default.*/
Line 2,621:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
decimals(9)
see agm(1, 1/sqrt(2)) + nl
Line 2,640:
===Flt Version===
The thing to note about this implementation is that it uses the [http://flt.rubyforge.org/ Flt] library for high-precision math. This lets you adapt context (including precision and epsilon) to a ridiculous-in-real-life degree.
<syntaxhighlight lang="ruby"># 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).
Line 2,667:
===BigDecimal Version===
Ruby has a BigDecimal class in standard library
<syntaxhighlight lang="ruby">require 'bigdecimal'
 
PRECISION = 100
Line 2,690:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">print agm(1, 1/sqr(2))
print agm(1,1/2^.5)
print using("#.############################",agm(1, 1/sqr(2)))
Line 2,709:
=={{header|Rust}}==
 
<syntaxhighlight lang="rust">// Accepts two command line arguments
// cargo run --name agm arg1 arg2
 
Line 2,748:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
def agm(a: Double, g: Double, eps: Double): Double = {
if (math.abs(a - g) < eps) (a + g) / 2
Line 2,759:
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">
(define agm
(case-lambda
Line 2,778:
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
Line 2,816:
 
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">import <Utilities/Math.sl>;
 
agm(a, g) :=
Line 2,836:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func agm(a, g) {
loop {
var (a1, g1) = ((a+g)/2, sqrt(a*g))
Line 2,855:
 
Better precision than this is not easily obtainable on the ZX81, unfortunately.
<syntaxhighlight lang="basic"> 10 LET A=1
20 LET G=1/SQR 2
30 GOSUB 100
Line 2,872:
{{works with|Smalltalk/X}}
That is simply a copy/paste of the already existing agm method in the Number class:
<syntaxhighlight lang="smalltalk">agm:y
"return the arithmetic-geometric mean agm(x, y)
of the receiver (x) and the argument, y.
Line 2,892:
^ ai</syntaxhighlight>
 
<syntaxhighlight lang="smalltalk">Transcript showCR: (24 agm:6).
Transcript showCR: ( (1/2) agm:(1/6) ).
Transcript showCR: (1 agm:(1 / 2 sqrt)).</syntaxhighlight>
Line 2,903:
{{works with|oracle|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.
<syntaxhighlight lang="sql">with
rec (rn, a, g, diff) as (
select 1, 1, 1/sqrt(2), 1 - 1/sqrt(2)
Line 2,925:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">
fun agm(a, g) = let
fun agm'(a, g, eps) =
Line 2,941:
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">mata
 
real scalar agm(real scalar a, real scalar b) {
Line 2,959:
 
=={{header|Swift}}==
<syntaxhighlight lang=Swift"swift">import Darwin
 
enum AGRError : Error {
Line 2,995:
=={{header|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 <code>old_b</code> 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).
<syntaxhighlight lang="tcl">proc agm {a b} {
set old_b [expr {$b<0?inf:-inf}]
while {$a != $b && $b != $old_b} {
Line 3,009:
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">1→A:1/sqrt(2)→G
While abs(A-G)>e-15
(A+G)/2→B
Line 3,021:
{{works with|ksh93}}
ksh is one of the few unix shells that can do floating point arithmetic (bash does not).
<syntaxhighlight lang="bash">function agm {
float a=$1 g=$2 eps=${3:-1e-11} tmp
while (( abs(a-g) > eps )); do
Line 3,043:
0.8472130848</pre>
 
You can get a more approximate convergence by changing the while condition to compare the numbers as strings: change <syntaxhighlight lang="bash">while (( abs(a-g) > eps ))</syntaxhighlight> to <syntaxhighlight lang="bash">while [[ $a != $g ]]</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">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
Line 3,066:
=={{header|VBScript}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="vb">
Function agm(a,g)
Do Until a = tmp_a
Line 3,085:
{{trans|C#}}
===Double, Decimal Versions===
<syntaxhighlight lang="vbnet">Imports System.Math
Imports System.Console
 
Line 3,122:
{{trans|C#}}
{{Libheader|System.Numerics}}
<syntaxhighlight lang="vbnet">Imports System.Math
Imports System.Console
Imports BI = System.Numerics.BigInteger
Line 3,162:
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">import math
const ep = 1e-14
Line 3,179:
}</syntaxhighlight>
Using standard math module
<syntaxhighlight lang="vlang">import math.stats
import math
 
Line 3,191:
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="ecmascript">var eps = 1e-14
 
var agm = Fn.new { |a, g|
Line 3,210:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codesi;
real A, A1, G;
[Format(0, 16);
Line 3,231:
=={{header|zkl}}==
{{trans|XPL0}}
<syntaxhighlight lang="zkl">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;
Line 3,244:
</pre>
Or, using tail recursion
<syntaxhighlight lang="zkl">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()));
}()</syntaxhighlight>
Line 3,258:
=={{header|ZX Spectrum Basic}}==
{{trans|ERRE}}
<syntaxhighlight lang="zxbasic">10 LET a=1: LET g=1/SQR 2
20 LET ta=a
30 LET a=(a+g)/2
10,327

edits