Golden ratio/Convergence: Difference between revisions

Content added Content deleted
(→‎{{header|M4}}: More detail.)
(Added Arizona Icon.)
Line 690: Line 690:
Error (approx) : -0.00000120186465
Error (approx) : -0.00000120186465
</pre>
</pre>

=={{header|Icon}}==
{{trans|M4}}

For the sake of interest I translated this from the m4 rather than the [[#ObjectIcon|Object Icon]]. Thus the calculations are done in scaled integer arithmetic. Every current implementation of Icon should have multiple precision integers. Therefore the full task can easily be carried out, unlike in the m4.

Note that "one" and "one_squared" are different integers. They can both be viewed as fixed-point "1", but with the implicit decimal point in different positions. Where the number "100000" occurs, this represents its true integer value, which is <math>1\over{1\times{10^{-5}}}</math>.

(To come up with a value of "one" I simply typed "1" and then typed a bunch of "0" without counting them.)

<syntaxhighlight lang="icon">
global one, one_squared

procedure main ()
local result, phi, n, floatphi
one := 1000000000000000000
one_squared := one * one
result := iterate (one, 0)
phi := result[1]
n := result[2]
floatphi := real (phi) / one
write ("Result: ", phi, "/", one, " (", floatphi, ")")
write (" ", n, " iterations")
write ("The error is approximately ",
floatphi - (0.5 * (1 + sqrt (5))))
end

procedure iterate (phi, n)
local phi1, n1
phi1 := one + (one_squared / phi)
n1 := n + 1
if 100000 * abs (phi1 - phi) <= one then
return [phi1, n1]
else
return iterate (phi1, n1)
end
</syntaxhighlight>

{{out}}
<pre>Result: 1618032786885245901/1000000000000000000 (1.618032787)
14 iterations
The error is approximately -1.201864649e-06</pre>


=={{header|Java}}==
=={{header|Java}}==