Pathological floating point problems: Difference between revisions

Add Factor
m (→‎Task 2: Chaotic Bank Society: Fixed typo (Socienty → Society))
(Add Factor)
Line 748:
...
100 100
</pre>
 
=={{header|Factor}}==
These problems are straightforward due to Factor's rational numbers. One only needs to take care not to introduce any floating point values to the calculations.
<lang factor>USING: formatting fry io kernel locals math math.floating-point
math.functions math.ranges sequences ;
IN: rosetta-code.pathological
 
: next2 ( x y -- y z )
swap dupd dupd '[ 111 1130 _ / - 3000 _ _ * / + ] call ;
 
: pathological-sequence ( -- seq )
2 -4 100 [ next2 dup ] replicate 2nip { 0 2 -4 } prepend ;
 
: show-sequence ( -- )
{ 3 4 5 6 7 8 20 30 50 100 } dup pathological-sequence nths
[ "n = %-3d %21.16f\n" printf ] 2each ;
 
CONSTANT: e 106246577894593683/39085931702241241
: balance ( n -- x ) [1,b] e 1 - [ * 1 - ] reduce ;
 
:: f ( a b -- x )
333+3/4 b 6 ^ * 11 a sq b sq * * b 6 ^ - b 4 ^ 121 * - 2 - a
sq * b 8 ^ 5+1/2 * a 2 b * / + + + ;
 
: pathological-demo ( -- )
"Task 1 - Sequence convergence:" print show-sequence nl
 
"Task 2 - Chaotic Bank fund after 25 years:" print
25 balance "%.16f\n" printf nl
 
"Task 3 - Siegfried Rump's example:" print
77617 33096 f "77617 33096 f = %.16f\n" printf ;
 
MAIN: pathological-demo</lang>
{{out}}
<pre>
Task 1 - Sequence convergence:
n = 3 18.5000000000000000
n = 4 9.3783783783783784
n = 5 7.8011527377521614
n = 6 7.1544144809752494
n = 7 6.8067847369236330
n = 8 6.5926327687044384
n = 20 6.0435521101892689
n = 30 6.0067860930312058
n = 50 6.0001758466271872
n = 100 6.0000000193194779
 
Task 2 - Chaotic Bank fund after 25 years:
0.0399387300490171
 
Task 3 - Siegfried Rump's example:
77617 33096 f = -0.8273960599468214
</pre>
 
1,808

edits