Jump to content

Pathological floating point problems: Difference between revisions

no edit summary
(Add Swift)
No edit summary
Line 1,200:
-0.8273960599468214
</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
===Task 1: Muller's sequence===
A) Using BigDecimal "div" (similar to Ruby's "quo" method), default iterations 100, here 132 min for last stable output.
<lang Ruby>require "big"
 
ar = [0.to_big_d, 2.to_big_d, -4.to_big_d]
 
100.times { ar << 111 - 1130.to_big_d.div(ar[-1], 132) + 3000.to_big_d.div((ar[-1] * ar[-2]), 132) }
 
[3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n|
puts "%3d -> %0.16f" % [n, ar[n]]
end
</lang>
{{Out}}
<pre> 3 -> 18.5000000000000000
4 -> 9.3783783783783790
5 -> 7.8011527377521617
6 -> 7.1544144809752490
7 -> 6.8067847369236327
8 -> 6.5926327687044388
20 -> 6.0435521101892693
30 -> 6.0067860930312058
50 -> 6.0001758466271875
100 -> 6.0000000193194776
</pre>
 
B) Using BigRationals.
<lang Ruby>require "big"
 
ar = [0, 2, -4].map(&.to_big_r)
 
100.times { ar << (111 - 1130.to_big_r / ar[-1] + 3000.to_big_r / (ar[-1] * ar[-2])) }
 
[3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n|
puts "%3d -> %0.16f" % [n, ar[n]]
end
</lang>
{{Out}}
<pre> 3 -> 18.5000000000000000
4 -> 9.3783783783783772
5 -> 7.8011527377521608
6 -> 7.1544144809752490
7 -> 6.8067847369236327
8 -> 6.5926327687044379
20 -> 6.0435521101892684
30 -> 6.0067860930312049
50 -> 6.0001758466271866
100 -> 6.0000000193194776
</pre>
 
===Task 2: Chaotic Bank Society===
Unlike Ruby, had to manually create "E" to sufficient precision.
<lang Ruby>require "big"
 
def e(precision)
y = BigDecimal.new(10.to_big_i ** precision, precision)
d = y
i = 1
 
while true
d = (d / i).scale_to(y)
y2 = y + d
return y if y2 == y
y = y2
i += 1
end
end
 
balance = e(50) - 1
1.upto(25) { |y| balance = (balance * y) - 1 }
puts "Bank balance after 25 years = #{balance.to_f}"</lang>
{{Out}}
<pre>Bank balance after 25 years = 0.03993872967323021</pre>
 
===Task 3: Rump's example===
Using BigRationals.
<lang Ruby>require "big"
 
def rump(a, b)
a, b = a.to_big_r, b.to_big_r
333.75.to_big_r * b**6 + a**2 * (11 * a**2 * b**2 - b**6 - 121 * b**4 - 2) + 5.5.to_big_r * b**8 + a / (2 * b)
end
puts "rump(77617, 33096) = #{rump(77617, 33096).to_f}"</lang>
{{out}}<pre>rump(77617, 33096) = -0.8273960599468213
</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.