Golden ratio/Convergence: Difference between revisions

Realize in F#
m (→‎{{header|Phix}}: split the overlong printf)
(Realize in F#)
 
(40 intermediate revisions by 22 users not shown)
Line 12:
===See also===
* [[Metallic_ratios|Metallic ratios]]
 
=={{header|Ada}}==
I used fixed point numbers, to show that in Ada it was no difficulty to do so.
 
<syntaxhighlight lang="ada">
with ada.text_io; use ada.text_io;
 
procedure golden_ratio_convergence is
 
-- This is a fixed-point type. I typed a bunch of "0"
-- without counting them.
type number is delta 0.000000000000001 range -10.0 .. 10.0;
 
one : constant number := number (1.0);
phi : constant number := number (1.61803398874989484820458683436563811772030917980576286213544862270526046281890244970720720418939113748475); -- OEIS A001622
phi0, phi1 : number;
count : integer;
 
begin
count := 1;
phi0 := 1.0;
phi1 := (one + (one / phi0));
while abs (phi1 - phi0) > number (1.0e-5) loop
count := count + 1;
phi0 := phi1;
phi1 := (one + (one / phi0));
end loop;
put ("Result:");
put (phi1'image);
put (" after");
put (count'image);
put_line (" iterations");
put ("The error is approximately ");
put_line (number'image (phi1 - phi));
end golden_ratio_convergence;
</syntaxhighlight>
 
{{out}}
<pre>Result: 1.618032786885245 after 14 iterations
The error is approximately -0.000001201864649</pre>
 
=={{header|ALGOL 60}}==
Line 56 ⟶ 96:
{{Trans|RATFOR}} ...but basically similar to many of the other samples, e.g. the Wren sample.
<syntaxhighlight lang="algol68">
BEGIN # calculate the Golden Ratio and show the number of iteratoioinsiterations required #
 
INT count := 0;
Line 82 ⟶ 122:
{{Trans|RATFOR}}
<syntaxhighlight lang="algolw">
begin % calculate the Golden Ratio and show the number of iteratoioinsiterations required %
 
integer count;
Line 153 ⟶ 193:
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|Bas}}===
{{trans|C}}
Line 218 ⟶ 261:
<pre>Result: 1.618033 after 14 iterations
The error is approximately -1.201865E-06</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">precision 6
 
define i = 0, d = 0, phi0 = 1, phi1 = 0
 
do
 
let phi1 = 1 / phi0 + 1
let d = abs(phi1 - phi0)
let phi0 = phi1
let i = i + 1
 
wait
 
loopuntil .00001 > d
 
print "result: ", phi1, " after ", i, " iterations"
print "the error is approximately ", phi1 - (.5 * (1 + sqrt(5)))</syntaxhighlight>
{{out| Output}}<pre>result: 1.618033 after 14 iterations
the error is approximately -0.000001</pre>
 
==={{header|FreeBASIC}}===
Line 326 ⟶ 390:
Result: 1,6180327869 after 14 iterations
The error is approximately -0,0000012019</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|Quite BASIC}}
{{works with|MSX BASIC|any}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">100 CLS : rem 100 HOME for Applesoft BASIC : DELETE for Minimal BASIC
110 LET I = 0
120 LET P0 = 1
130 LET P1 = 1+(1/P0)
140 LET D = ABS(P1-P0)
150 LET P0 = P1
160 LET I = I+1
170 IF .00001 < D THEN 130
180 PRINT "Result: ";P1;" after ";I;" iterations"
190 PRINT "The error is approximately ";P1-(.5*(1+SQR(5)))
200 END</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">Procedure using_Float()
Define iter.i = 0
Define.f phi0 = 1.0, phi1, diff
Repeat
phi1 = 1.0 + (1.0 / phi0)
diff = Abs(phi1 - phi0)
phi0 = phi1
iter + 1
Until (1.0e-5 > diff)
PrintN("Using type Float --")
PrintN("Result: " + FormatNumber((phi1), 10) + " after " + Str(iter) + " iterations")
PrintN("The error is approximately " + FormatNumber((phi1 - (0.5 * (1.0 + Sqr(5.0)))), 10))
EndProcedure
 
Procedure using_Double()
Define iter.i = 0
Define.d phi0 = 1.0, phi1, diff
Repeat
phi1 = 1.0 + (1.0 / phi0)
diff = Abs(phi1 - phi0)
phi0 = phi1
iter + 1
Until (1.0e-5 > diff)
PrintN("Using type Double --")
PrintN("Result: " + FormatNumber((phi1), 10) + " after " + Str(iter) + " iterations")
PrintN("The error is approximately " + FormatNumber((phi1 - (0.5 * (1.0 + Sqr(5.0)))), 10))
EndProcedure
 
OpenConsole()
using_Float()
PrintN("")
using_Double()
Input()
CloseConsole()</syntaxhighlight>
{{out}}
<pre>Using type Float --
Result: 1.6180328131 after 14 iterations
The error is approximately -0.0000011757
 
Using type Double --
Result: 1.6180327869 after 14 iterations
The error is approximately -0.0000012019</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">SUB iterate
iter = 0
phi0 = 1!
DO
phi1 = 1! + (1! / phi0)
diff = ABS(phi1 - phi0)
phi0 = phi1
iter = iter + 1
LOOP UNTIL (.00001 > diff)
 
PRINT "Result: "; phi1; " after "; iter; " iterations"
PRINT "The error is approximately "; phi1 - (.5 * (1! + SQR(5!)))
END SUB
 
CALL iterate
END</syntaxhighlight>
{{out}}
<pre>Result: 1.618033 after 14 iterations
The error is approximately -1.175678E-06</pre>
 
==={{header|Quite BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|True BASIC}}===
{{trans|QBasic}}
<syntaxhighlight lang="qbasic">SUB iterate
LET iter = 0
LET phi0 = 1
DO
LET phi1 = 1+(1/phi0)
LET diff = abs(phi1-phi0)
LET phi0 = phi1
LET iter = iter+1
LOOP until (.00001 > diff)
PRINT "Result: "; phi1; " after "; iter; " iterations"
PRINT "The error is approximately "; phi1-(.5*(1+sqr(5)))
END SUB
 
CALL iterate
END</syntaxhighlight>
 
==={{header|Yabasic}}===
Line 416 ⟶ 598:
Result: 1.618033 after 14 iterations
The error is approximately -0.000001
</pre>
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
 
public class GoldenRatio {
static void Iterate() {
double oldPhi = 1.0, phi = 1.0, limit = 1e-5;
int iters = 0;
while (true) {
phi = 1.0 + 1.0 / oldPhi;
iters++;
if (Math.Abs(phi - oldPhi) <= limit) break;
oldPhi = phi;
}
Console.WriteLine($"Final value of phi : {phi:0.00000000000000}");
double actualPhi = (1.0 + Math.Sqrt(5.0)) / 2.0;
Console.WriteLine($"Number of iterations : {iters}");
Console.WriteLine($"Error (approx) : {phi - actualPhi:0.00000000000000}");
}
 
public static void Main(string[] args) {
Iterate();
}
}
</syntaxhighlight>
{{out}}
<pre>
Final value of phi : 1.61803278688525
Number of iterations : 14
Error (approx) : -0.00000120186465
 
</pre>
 
Line 571 ⟶ 787:
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
By working with 1 - phi_n instead of phi_n, we bring the values into the EDSAC range [-1,1) without a change of scale.
<syntaxhighlight lang="edsac">
[GoldenRatio/Convergence for Rosetta Code.
EDSAC program, Initial Orders 2]
[-----------------------------------------------------------------
Given phi_n as in the task description, let u_n = 1 - phi_n.
Then u_0 = 0 and the recurrence is u_(n+1) = 1/(u_n - 1).
To keep the arguments of the division subroutine D6 within range,
the recurrence is calculated as u_(n+1) = (1/4)/(u_n/4 - 1/4).
-----------------------------------------------------------------]
[Arrange the storage]
T47K P300F [M parameter: main routine]
T48K P56F [& (Delta) parameter: library s/r D6 (division)]
T49K P92F [L parameter: library s/r P1 (prints real)]
T50K P200F [X parameter: library s/r P7 (prints integer)]
[--------------------------------------------------------------------------
Library subroutine R2, reads values as positive integers at load time,
and is then overwritten.]
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z
T#M [tell R2 where to store values]
[Values when interpreted as reals are 1/4, 0.00001, -0.6180339887]
4294967296F171799F23741995290#TZ
[--------------------------------------------------------------------------
[Library subroutine M3, prints header at load time, and is then overwritten.
Here, last character sets teleprinter to figures.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*AIMING!AT!#1!A!*PHI@&ITERATIONS!!!FINAL!VALUE!!!!!ABS!ERROR@&#..
PK [after header, blank tape and PK (WWG, 1951, page 91)]
[--------------------------------------------------------------------------
M parameter: Main routine]
E25K TM GK
[Constants read in by R2 are stored here]
[0] [1/4]
[2] [0.00001, test for convergence]
[4] [limit as adapted for EDSAC, (1 - sqrt(5))/2 = -0.618...]
T6Z [don't overwrite constants: load from relative location 6]
[6] PF PF [current term]
[8] PF PF [previous term]
[10] PF [number of iterations, right justified]
[11] PD [17-bit constant 1]
[Enter here with acc = 0]
[12] T6#@ [u_0 := 0]
T10@ [count of iterations := 0]
[Loop to get next term]
[14] TF [clear acc]
A10@ A11@ T10@ [inc number of iterations]
A#@ TD [0D := 1/4 for division subroutine]
A6#@ U8#@ [previous term := current term u_n]
R1F [shift 2 right, acc := u_n/4]
S#@ T4D [4D := u_n/4 - 1/4 for division subroutine]
A25@ G& [call dvision s/r, 0D := u_(n+1)]
AD U6#@ [store u_(n+1)]
S8#@ E33@ [acc := u_(n+1) - u_n, skip if >= 0]
T4D S4D [else negate to get absolute difference]
[33] S2#@ [test for convergence]
E14@ [loop back if not converged]
[Here when converged]
TF TD [clear acc and whole of 0D (including sandwich bit)]
A10@ TF [0D := count of iterations, extended to 35 bits]
A39@ GX O79@ [print count and space]
A6#@ TD [final value to 0D for printing]
A44@ G59@ O79@ [print value and space]
A4#@ S6#@ E52@ [acc := error, skip if >= 0]
TD SD [else negate to get absolute value]
[52] TD [absolute error to 0D for printing]
A53@ G59@ O80@ O81@ [print error and new line]
O82@ [print null to flush teleprinter buffer]
ZF [halt machine]
[----------------------------------------------------------------------------
Wrapper for library subroutine P1. Adds '0.' before the decimal part,
preceded by space or minus sign.]
[59] A3F T76@ [plant return link as usual]
[61] AD G65@ [acc := number to print; jump if < 0]
O79@ E68@ [write space, join common code]
[65] TD SD [acc := number negated]
O61@ [write minus sign]
[68] YF YF [rounding: add 2^-34, nearest possible to 0.5*(10^-10)]
O77@ O78@ [print '0.']
TD [pass value to print subroutine]
A73@ GL P10F [call P1, print 10 decimals]
[76] ZF [(planted) jump back to caller]
[77] PF [digit '0' in figures mode]
[78] MF [full stop, here used for decimal point]
[79] !F [space]
[80] @F [carriage return]
[81] &F [line feed]
[82] K4096F [null char]
[--------------------------------------------------------------------------
Library subroutine P1: prints non-negative fraction in 0D, without '0.']
E25K TL
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[--------------------------------------------------------------------------
Library subroutine P7, prints long strictly positive integer;
10 characters, right justified, padded left with spaces.
Even address; 35 storage locations; working position 4D.]
E25K TX
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSF
L4FT4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
[--------------------------------------------------------------------------
Library subroutine D6: Division, accurate, fast.
0D := 0D/4D, where 4D <> 0, -1.
36 locations, working positons 6D and 8D.]
E25K T&
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLD
A35@T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
[--------------------------------------------------------------------------
M parameter again: define entry point]
E25K TM GK
E12Z
PF [enter with acc = 0]
</syntaxhighlight>
{{out}}
<pre>
AIMING AT 1 - PHI
ITERATIONS FINAL VALUE ABS ERROR
14 -0.6180327869 0.0000012019
</pre>
 
=={{header|F_Sharp|F#}}==
This task uses code from [https://rosettacode.org/wiki/Continued_fraction#F# Continued fraction(F#)]
<syntaxhighlight lang="fsharp">
// Golden ratio/Convergence. Nigel Galloway: March 8th., 2024
let ϕ=let aπ()=fun()->1M in cf2S(aπ())(aπ())
let (_,n),g=let mutable l=1 in (ϕ|>Seq.pairwise|>Seq.skipWhile(fun(n,g)->l<-l+1;abs(n-g)>1e-5M)|>Seq.head,l)
printfn "Value of ϕ is %1.14f after %d iterations error with respect to (1+√5)/2 is %1.14f" n g (abs(n-(decimal(1.0+(sqrt 5.0))/2M)))
</syntaxhighlight>
{{out}}
<pre>
Value of ϕ is 1.61803278688525 after 14 iterations error with respect to (1+√5)/2 is 0.00000120186465
</pre>
=={{header|Fortran}}==
==={{header|Fortran77}}===
Line 690 ⟶ 1,037:
Error (approx) : -0.00000120186465
</pre>
 
=={{header|Hy}}==
{{trans|Scheme}}
<syntaxhighlight lang="hy">
(import math)
 
(defn iterate [phi n]
(setv phi1 (+ 1.0 (/ 1.0 phi)))
(setv n1 (+ n 1))
(if (<= (abs (- phi1 phi)) 1e-5)
[phi1 n1]
(iterate phi1 n1)))
 
(setv [phi n] (iterate 1.0 0))
(print "Result:" phi "after" n "iterations")
(print "The error is approximately"
(- phi (* 0.5 (+ 1 (math.sqrt 5)))))
</syntaxhighlight>
 
{{out}}
<pre>Result: 1.6180327868852458 after 14 iterations
The error is approximately -1.2018646491362972e-06</pre>
 
=={{header|Icon}}==
Line 734 ⟶ 1,103:
14 iterations
The error is approximately -1.201864649e-06</pre>
 
=={{header|J}}==
(Using IEEE754 64 bit binary floating point, of course):
 
<syntaxhighlight lang=J> (,({:p)-~{&p)>:1 i.~1e_5>:|2 -/\p=. 1&(+%)^:a:1 NB. iterations and error
14 _1.20186e_6</syntaxhighlight>
 
In other words, wait for the series to converge (32 iterations - a few microseconds), check the pairwise differences and calculate the discrepancy.
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
 
Only minor adaptations are required for the following to work with
jaq, the Rust implementation of jq, so the output shown below
includes a run using jaq.
<syntaxhighlight lang="jq">
def phi: (1 + (5|sqrt)) / 2;
 
# epsilon > 0
def phi($epsilon):
{ phi: 1, oldPhi: (1+$epsilon), iters:0}
| until( (.phi - .oldPhi) | length < $epsilon;
.oldPhi = .phi
| .phi = 1 + (1 / .oldPhi)
| .iters += 1 )
 
| "Final value of phi : \(.phi) vs \(phi)",
"Number of iterations : \(.iters)",
"Absolute error (approx) : \((.phi - phi) | length)";
 
phi(1e-5)
</syntaxhighlight>
{{output}}
jq (the C implementation):
<pre>
Final value of phi : 1.6180327868852458 vs 1.618033988749895
Number of iterations : 14
Absolute error (approx) : 1.2018646491362972e-06
</pre>
gojq (the Go implementation):
<pre>
Final value of phi : 1.6180327868852458 vs 1.618033988749895
Number of iterations : 14
Absolute error (approx) : 0.0000012018646491362972
</pre>
jaq (the Rust implementation):
<pre>
Final value of phi : 1.6180327868852458 vs 1.618033988749895
Number of iterations : 14
Absolute error (approx) : 1.2018646491362972e-6
</pre>
 
=={{header|Java}}==
Line 763 ⟶ 1,185:
Number of iterations : 14
Error (approx) : -0.00000120186465
</pre>
 
=={{header|Julia}}==
{{trans|Wren}}
<syntaxhighlight lang="julia">function iterate_phi(limit::T) where T <: Real
phi, oldphi, iters = one(limit), one(limit), 0
while true
phi = 1 + 1 / oldphi
iters += 1
abs(phi - oldphi) <= limit && break
oldphi = phi
end
println("Final value of phi : $phi")
println("Number of iterations : $iters")
println("Error (approx) : $(phi - (1 + sqrt(T(5))) / 2)")
end
 
iterate_phi(1 / 10^5)
iterate_phi(1 / big(10)^25)
</syntaxhighlight>{{out}}
<pre>
Final value of phi : 1.6180327868852458
Number of iterations : 14
Error (approx) : -1.2018646491362972e-6
Final value of phi : 1.618033988749894848204586861593755309455975426621472923229332700794030300052916
Number of iterations : 61
Error (approx) : 2.722811719173566624681571006109388407808876983723400587864054809516456794284321e-26
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">local phi, phi0, expected, iters = 1, 0, (1 + math.sqrt(5)) / 2, 0
repeat
phi0, phi = phi, 1 + 1 / phi
iters = iters + 1
until math.abs(phi0 - phi) < 1e-5
io.write( "after ", iters, " iterations, phi = ", phi )
io.write( ", expected value: ", expected, ", diff: ", math.abs( expected - phi ), "\n" )
</syntaxhighlight>
{{out}}
<pre>after 14 iterations, phi = 1.6180327868852, expected value: 1.6180339887499, diff: 1.2018646491363e-06
</pre>
 
Line 884 ⟶ 1,346:
<pre>Result: 1.6180327868852458 after 14 iterations
The error is approximately -1.2018646491362972e-06
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/strutils
 
iterator goldenRatio(): (int, float) =
var phi = 1.0
var idx = 0
while true:
yield (idx, phi)
phi = 1 + 1 / phi
inc idx
 
const Eps = 1e-5
const Phi = 1.6180339887498948482045868343656381177203091798057628621354486
var prev = 0.0
for (i, phi) in goldenRatio():
if abs(phi - prev) <= Eps:
echo "Final value of φ: ", phi
echo "Number of iterations: ", i
echo "Approximative error: ", formatFloat(phi - Phi, ffDecimal)
break
prev = phi
</syntaxhighlight>
 
{{out}}
<pre>Final value of φ: 1.618032786885246
Number of iterations: 14
Approximative error: -0.0000012018646491</pre>
 
=={{header|Odin}}==
<syntaxhighlight lang="Go">
package golden
import "core:fmt"
import "core:math"
/* main block */
main :: proc() {
iterate()
}
/* definitions */
iterate :: proc() {
count := 0
phi0: f64 = 1.0
difference: f64 = 1.0
phi1: f64
fmt.println("\nGolden ratio/Convergence")
fmt.println("-----------------------------------------")
for 1.0e-5 < difference {
phi1 = 1.0 + (1.0 / phi0)
difference = abs(phi1 - phi0)
phi0 = phi1
count += 1
fmt.printf("Iteration %2d : Estimate : %.8f\n", count, phi1)
}
fmt.println("-----------------------------------------")
fmt.printf("Result: %.8f after %d iterations", phi1, count)
fmt.printf("\nThe error is approximately %.10f\n", (phi1 - (0.5 * (1.0 + math.sqrt_f64(5.0)))))
}
 
</syntaxhighlight>
{{out}}
<pre>
Golden ratio/Convergence
-----------------------------------------
Iteration 01 : Estimate : 2.00000000
Iteration 02 : Estimate : 1.50000000
Iteration 03 : Estimate : 1.66666667
Iteration 04 : Estimate : 1.60000000
Iteration 05 : Estimate : 1.62500000
Iteration 06 : Estimate : 1.61538462
Iteration 07 : Estimate : 1.61904762
Iteration 08 : Estimate : 1.61764706
Iteration 09 : Estimate : 1.61818182
Iteration 10 : Estimate : 1.61797753
Iteration 11 : Estimate : 1.61805556
Iteration 12 : Estimate : 1.61802575
Iteration 13 : Estimate : 1.61803714
Iteration 14 : Estimate : 1.61803279
-----------------------------------------
Result: 1.61803279 after 14 iterations
The error is approximately -0.0000012019
</pre>
 
Line 946 ⟶ 1,489:
<pre>Result: 987/610 (1.618032786) after 14 iterations
The error is approximately -0.000001202</pre>
 
=={{header|Onyx (wasm)}}==
<syntaxhighlight lang="TS">
package main
use core {*}
use core.math{abs}
use core.intrinsics.wasm{sqrt_f64}
main :: () {
iterate();
}
iterate :: () {
count := 0;
phi0: f64 = 1.0;
difference: f64 = 1.0;
phi1: f64;
println("\nGolden ratio/Convergence");
println("-----------------------------------------");
while 0.00001 < difference {
phi1 = 1.0 + (1.0 / phi0);
difference = abs(phi1 - phi0);
phi0 = phi1;
count += 1;
printf("Iteration {} : Estimate : {.8}\n", count, phi1);
}
println("-----------------------------------------");
printf("Result: {} after {} iterations", phi1, count);
printf("\nThe error is approximately {.8}\n", (phi1 - (0.5 * (1.0 + sqrt_f64(5.0)))));
println("\n");
}
</syntaxhighlight>
{{out}}
<pre>
Golden ratio/Convergence
-----------------------------------------
Iteration 1 : Estimate : 2.00000000
Iteration 2 : Estimate : 1.50000000
Iteration 3 : Estimate : 1.66666666
Iteration 4 : Estimate : 1.60000000
Iteration 5 : Estimate : 1.62500000
Iteration 6 : Estimate : 1.61538461
Iteration 7 : Estimate : 1.61904761
Iteration 8 : Estimate : 1.61764705
Iteration 9 : Estimate : 1.61818181
Iteration 10 : Estimate : 1.61797752
Iteration 11 : Estimate : 1.61805555
Iteration 12 : Estimate : 1.61802575
Iteration 13 : Estimate : 1.61803713
Iteration 14 : Estimate : 1.61803278
-----------------------------------------
Result: 1.6180 after 14 iterations
The error is approximately -0.00000120
</pre>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">/* REXX
* Compute the Golden Ratio using iteration
* 20230604 Walter Pachl
*/
Numeric Digits 16
Parse Value '1 1 1e-5' With oldPhi phi limit
Do iterations=1 By 1 Until delta<=limit
phi=1+1/oldPhi /* next approximation */
delta=abs(phi-oldPhi) /* difference to previous */
If delta>limit Then /* not small enough */
oldPhi=phi /* proceed with new value */
End
actualPhi=(1+rxCalcsqrt(5,16))/2 /* compute the real value */
Say 'Final value of phi : ' phi /* our approximation */
Say 'Actual value : ' actualPhi /* the real value */
Say 'Error (approx) :' (phi-actualPhi) /* the difference */
Say 'Number of iterations:' iterations
Exit
::REQUIRES RXMATH library
</syntaxhighlight>
{{out}}
<pre>Final value of phi : 1.618032786885246
Actual value : 1.618033988749895
Error (approx) : -0.000001201864649
Number of iterations: 14
</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl" line>
use strict; use warnings;
use constant phi => (1 + sqrt 5) / 2;
 
sub GR { my $n = shift; $n == 1 ? 2 : 1 + 1 / GR($n - 1) }
 
my $i;
while (++$i) {
my $dev = abs phi - GR($i);
(printf "%d iterations: %8.6f vs %8.6f (%8.6f)\n", $i, phi, GR($i), $dev and last) if $dev < 1e-5;
}
</syntaxhighlight>
{{out}}
<pre>
12 iterations: 1.618034 vs 1.618026 (0.000008)
</pre>
 
=={{header|Phix}}==
Line 1,028 ⟶ 1,669:
Error (approx) : -0.00000120186465
</pre>
 
=={{header|Raku}}==
<syntaxhighlight lang="raku">constant phi = 1.FatRat, 1 + 1/* ... { abs($^a-$^b)≤1e-5 };
 
say "It took {phi.elems} iterations to reach {phi.tail}";
say "The error is {{ ($^a - $^b)/$^b }(phi.tail, (1+sqrt(5))/2)}"</syntaxhighlight>
{{out}}
<pre>It took 15 iterations to reach 1.618033
The error is -7.427932029059675e-07</pre>
 
=={{header|RATFOR}}==
Line 1,056 ⟶ 1,706:
<pre>Result: 1.618033 after 14 iterations
The error is approximately -0.000001
</pre>
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/* REXX
* Compute the Golden Ratio using iteration
* 20230604 Walter Pachl
*/
Numeric Digits 16
Parse Value '1 1 1e-5' With oldPhi phi limit
Do iterations=1 By 1 Until delta<=limit
phi=1+1/oldPhi /* next approximation */
delta=abs(phi-oldPhi) /* difference to previous */
If delta>limit Then /* not small enough */
oldPhi=phi /* proceed with new value */
End
actualPhi=(1+sqrt(5,16))/2 /* compute the real value */
Say 'Final value of phi : ' phi /* our approximation */
Say 'Actual value : ' actualPhi /* the real value */
Say 'Error (approx) :' (phi-actualPhi) /* the difference */
Say 'Number of iterations:' iterations
Exit
 
sqrt: Procedure
/* REXX *************************************************************
* Return sqrt(x,precision) -- with the specified precision
********************************************************************/
Parse Arg x,xprec
If x<0 Then /* a negative argument */
Return 'nan' /* has no real square root */
iprec=xprec+10 /* increase precision */
Numeric Digits iprec /* for very safe results */
r0= x
r = 1 /* start value */
Do Until r=r0 /* loop until no change of r */
r0 = r /* previous value */
r = (r + x/r) / 2 /* next approximation */
End
Numeric Digits xprec /* reset to desired precision*/
Return (r+0) /* normalize the result */
</syntaxhighlight>
 
{{out}}
<pre>Final value of phi : 1.618032786885246
Actual value : 1.618033988749895
Error (approx) : -0.000001201864649
Number of iterations: 14
</pre>
 
Line 1,092 ⟶ 1,787:
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
φ_convergence = Enumerator.produce(1.0r){|prev| 1 + 1/prev}
(_prev, c), i = φ_convergence.each_cons(2).with_index(1).detect{|(v1, v2), i| (v1-v2).abs <= 1E-5}
 
puts "Result after #{i} iterations: #{c.to_f}
Error is about #{c - (0.5 * (1 + (5.0**0.5)))}."
</syntaxhighlight>
{{out}}
<pre>Result after 14 iterations: 1.618032786885246
Error is about -1.2018646489142526e-06.
</pre>
=={{header|Scheme}}==
{{trans|ATS}}
Line 1,126 ⟶ 1,833:
<pre>Result: 987/610 (1.618032786885246) after 14 iterations
The error is approximately -1.2018646489142526e-6</pre>
 
=={{header|Shen}}==
 
I plugged in a value for <math>\phi</math> rather than write a sqrt procedure or see what there might be in the standard library. (''Actually I wrote a sqrt procedure, but eventually decided to do this instead.'')
 
<syntaxhighlight lang="shen">
(define iterate
PHI N ->
(let PHI1 (+ 1 (/ 1 PHI))
N1 (+ N 1)
DIFF (* 100000 (- PHI1 PHI))
(if (and (<= -1 DIFF) (<= DIFF 1))
[PHI1 N1 (- PHI1 1.618033988749895)]
(iterate PHI1 N1))))
 
(print (iterate 1 0))
</syntaxhighlight>
 
{{out}}
I ran this with shen-scheme.
<pre>[1.6180327868852458 14 -1.2018646493583418e-6]</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">const phi = (1+sqrt(5))/2
func GR(n) is cached { (n == 1) ? 1 : (1 + 1/__FUNC__(n-1)) }
 
var n = (1..Inf -> first {|n|
abs(GR(n) - GR(n+1)) <= 1e-5
})
 
say "#{n} iterations: #{GR(n+1)} (cfrac)\n#{' '*15}#{phi} (actual)"
say "The error is: #{GR(n+1) - phi}"</syntaxhighlight>
{{out}}
<pre>
14 iterations: 1.6180327868852459016393442622950819672131147541 (cfrac)
1.61803398874989484820458683436563811772030917981 (actual)
The error is: -0.00000120186464894656524257207055615050719442570740221
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Wren}}
<syntaxhighlight lang="Rust">
import math
 
fn main() {
limit := 1e-5
mut old_phi := 1.0
mut iters := 0
mut phi, mut actual_phi := f64(0), f64(0)
for {
phi = 1 + 1 / old_phi
iters++
if math.abs(phi - old_phi) <= limit {break}
old_phi = phi
}
println("Final value of phi : ${phi:.14f}")
actual_phi = (1.0 + math.sqrt(5.0)) / 2.0
println("Number of iterations : ${iters}")
println("Error (approx) : ${phi - actual_phi:.14f}")
}
</syntaxhighlight>
 
{{out}}
<pre>
Final value of phi : 1.61803278688525
Number of iterations : 14
Error (approx) : -0.00000120186465
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
Wren's only built-in numeric type is a 64 bit float.
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
 
var oldPhi = 1
Line 1,150 ⟶ 1,925:
<pre>
Final value of phi : 1.61803278688525
Number of iterations : 14
Error (approx) : -0.00000120186465
</pre>
 
=={{header|XPL0}}==
{{trans|Go}}
XPL0's real = float64 = double
<syntaxhighlight lang "XPL0">include xpllib; \for Print
 
real OldPhi, Phi, Limit, ActualPhi;
int Iters;
[OldPhi := 1.0;
Iters := 0;
Limit := 1e-5;
loop [Phi := 1.0 + 1.0/OldPhi;
Iters := Iters+1;
if abs(Phi-OldPhi) <= Limit then
quit;
OldPhi := Phi;
];
Print("Final value of phi : %2.14f\n", Phi);
ActualPhi := (1.0 + sqrt(5.0)) / 2.0;
Print("Number of iterations : %d\n", Iters);
Print("Error (approx) : %2.14f\n", Phi-ActualPhi);
]</syntaxhighlight>
{{out}}
<pre>
Final value of phi : 1.61803278688525
Number of iterations : 14
Error (approx) : -0.00000120186465
2,171

edits