Pathological floating point problems: Difference between revisions

Content added Content deleted
(Added Perl example)
Line 1,839: Line 1,839:


Output:<pre>f(77617.0,33096.0): -0.827396059946821368141165...</pre>
Output:<pre>f(77617.0,33096.0): -0.827396059946821368141165...</pre>

=={{header|Perl}}==
All three tasks can be solved by using either the <code>bigrat</code> or <code>bignum</code> core modules.
Both approaches are used, as demonstration.
==== Convergent series ====
The constants in the equation must be represented with a decimal point (even just <code>111.</code>) so that
they are treated as rationals, not integers.
<lang perl>use bigrat;

@s = qw(2, -4);
for my $n (2..99) {
$s[$n]= 111.0 - 1130.0/$s[-1] + 3000.0/($s[-1]*$s[-2]);
}

for $n (3..8, 20, 30, 35, 50, 100) {
($nu,$de) = $s[$n-1] =~ m#^(\d+)/(\d+)#;;
printf "n = %3d %18.15f\n", $n, $nu/$de;
}</lang>
{{out}}
<pre>n = 3 18.500000000000000
n = 4 9.378378378378379
n = 5 7.801152737752162
n = 6 7.154414480975249
n = 7 6.806784736923633
n = 8 6.592632768704439
n = 20 6.043552110189269
n = 30 6.006786093031206
n = 35 6.002716153954351
n = 50 6.000175846627188
n = 100 6.000000019319478</pre>

==== Chaotic bank society ====
The value of 𝑒 is imported from a module, but could also be calculated, as is done in
[[Calculating_the_value_of_e#Perl|Calculating the value of e]]
<lang perl>use bignum qw(bexp);
$e = bexp(1,43);
$years = 25;
$balance = $e - 1;

print "Starting balance, \$(e-1): \$$balance\n";
for $i (1..$years) { $balance = $i * $balance - 1 }
printf "After year %d, you will have \$%1.15g in your account.\n", $years, $balance;</lang>
{{out}}
<pre>Starting balance, $(e-1): $1.718281828459045235360287471352662497757247
After year 25, you will have $0.0399387296732302 in your account.</pre>

==== Rump's example ====
<lang perl>use bignum;

$a = 77617;
$b = 33096;
printf "%0.16f\n", 333.75*$b**6 + $a**2 * ( 11*$a**2 * $b**2 - $b**6 - 121*$b**4 - 2) + 5.5*$b**8 + $a/(2*$b);</lang>
{{out}}
<pre>-0.8273960599468214</pre>


=={{header|Perl 6}}==
=={{header|Perl 6}}==