Continued fraction: Difference between revisions

Content added Content deleted
(Added solution for Pascal)
Line 1,757: Line 1,757:


Note that there are two kinds of continued fractions. The kind here where we alternate between '''a''' and '''b''' values, but in some other tasks '''b''' is always 1 (and not included in the list we use to represent the continued fraction). The other kind is evaluated in J using <code>(+%)/</code> instead of <code>+`%/</code>.
Note that there are two kinds of continued fractions. The kind here where we alternate between '''a''' and '''b''' values, but in some other tasks '''b''' is always 1 (and not included in the list we use to represent the continued fraction). The other kind is evaluated in J using <code>(+%)/</code> instead of <code>+`%/</code>.

=={{header|Icon}}==
<syntaxhighlight lang="icon">
$define EVAL_DEPTH 100

# A generalized continued fraction, represented by two functions. Each
# function maps from an index to a floating-point value.
record continued_fraction (a, b)

procedure main ()
local sqrt2_frac, e_frac, pi_frac
writes (" sqrt 2.0 = ")
write (evaluate_continued_fraction (continued_fraction (sqrt2_a, sqrt2_b),
EVAL_DEPTH))
writes (" e = ")
write (evaluate_continued_fraction (continued_fraction (e_a, e_b),
EVAL_DEPTH))
writes (" pi = ")
write (evaluate_continued_fraction (continued_fraction (pi_a, pi_b),
EVAL_DEPTH))
end

procedure evaluate_continued_fraction (frac, depth)
local i, retval
retval := frac.a (depth)
every i := depth to 1 by -1 do {
retval := frac.a (i - 1) + (frac.b (i) / retval)
}
return retval
end

procedure sqrt2_a (i)
return (if i = 0 then 1.0 else 2.0)
end

procedure sqrt2_b (i)
return 1.0
end

procedure e_a (i)
return (if i = 0 then 2.0 else real (i))
end

procedure e_b (i)
return (if i = 1 then 1.0 else real (i - 1))
end

procedure pi_a (i)
return (if i = 0 then 3.0 else 6.0)
end

procedure pi_b (i)
return real (((2 * i) - 1)^2)
end
</syntaxhighlight>

{{out}}
<pre>$ icon continued-fraction-task.icn
sqrt 2.0 = 1.414213562
e = 2.718281828
pi = 3.141592411
</pre>


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