Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Pathological_floating_point_problems

View file

@ -0,0 +1,76 @@
Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
<pre>
0.1 + 0.2 = 0.30000000000000004
</pre>
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
'''A sequence that seems to converge to a wrong limit.'''
Consider the sequence:
:::::: <big><big> v<sub>1</sub> = 2 </big></big>
:::::: <big><big> v<sub>2</sub> = -4 </big></big>
:::::: <big><big> v<sub>n</sub> = 111 &nbsp; - &nbsp; 1130 &nbsp; / &nbsp; v<sub>n-1</sub> &nbsp; + &nbsp; 3000&nbsp; / &nbsp; (v<sub>n-1</sub> * v<sub>n-2</sub>) </big></big>
As &nbsp; '''n''' &nbsp; grows larger, the series should converge to &nbsp; '''6''' &nbsp; but small amounts of error will cause it to approach &nbsp; '''100'''.
;Task 1:
Display the values of the sequence where &nbsp; n = &nbsp; 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 &nbsp; to at least '''16''' decimal places.
<pre>
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
</pre>
;Task 2:
'''The Chaotic Bank Society''' &nbsp; is offering a new investment account to their customers.
You first deposit &nbsp; $e - 1 &nbsp; where &nbsp; e &nbsp; is &nbsp; 2.7182818... &nbsp; the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
::* after 2 years your balance will be doubled and $1 removed.
::* after 3 years your balance will be tripled and $1 removed.
::* <b> ... </b>
::* after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after &nbsp; 25 &nbsp; years?
Starting balance: $<i>e</i>-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
;Task 3, extra credit:
'''Siegfried Rump's example.''' &nbsp; Consider the following function, designed by Siegfried Rump in 1988.
:::::: <big><big> f(a,b) = 333.75b<sup>6</sup> + a<sup>2</sup>( 11a<sup>2</sup>b<sup>2</sup> - b<sup>6</sup> - 121b<sup>4</sup> - 2 ) + 5.5b<sup>8</sup> + a/(2b) </big></big>
:::::: <big> compute &nbsp; <big> f(a,b) </big> &nbsp; where &nbsp; <big> a=77617.0 </big> &nbsp; and &nbsp; <big> b=33096.0 </big></big>
:::::: <big><big> f(77617.0, 33096.0) &nbsp; = &nbsp; -0.827396059946821 </big></big>
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
;See also;
* &nbsp; [https://perso.ens-lyon.fr/jean-michel.muller/chapitre1.pdf Floating-Point Arithmetic] &nbsp; Section 1.3.2 Difficult problems.
<br><br>

View file

@ -0,0 +1,53 @@
* Pathological floating point problems 03/05/2016
PATHOFP CSECT
USING PATHOFP,R13
SAVEAR B STM-SAVEAR(R15)
DC 17F'0'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
LE F0,=E'2'
STE F0,U u(1)=2
LE F0,=E'-4'
STE F0,U+4 u(2)=-4
LA R6,3 n=3
LA R7,U+4 @u(n-1)
LA R8,U @u(n-2)
LA R9,U+8 @u(n)
LOOPN CH R6,=H'100' do n=3 to 100
BH ELOOPN
LE F4,0(R7) u(n-1)
LE F2,=E'1130' 1130
DER F2,F4 1130/u(n-1)
LE F0,=E'111' 111
SER F0,F2 111-1130/u(n-1)
LE F2,0(R7) u(n-1)
LE F4,0(R8) u(n-2)
MER F2,F4 u(n-1)*u(n-2)
LE F6,=E'3000' 3000
DER F6,F2 3000/(u(n-1)*u(n-2))
AER F0,F6 111-1130/u(n-1)+3000/(u(n-1)*u(n-2))
STE F0,0(R9) store into u(n)
XDECO R6,PG+0 n
LE F0,0(R9) u(n)
LA R0,3 number of decimals
BAL R14,FORMATF format(u(n),'F13.3')
MVC PG+12(13),0(R1) put into buffer
XPRNT PG,80 print buffer
LA R6,1(R6) n=n+1
LA R7,4(R7) @u(n-1)
LA R8,4(R8) @u(n-2)
LA R9,4(R9) @u(n)
B LOOPN
ELOOPN L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
COPY FORMATF
LTORG
PG DC CL80' ' buffer
U DS 100E
YREGS
YFPREGS
END PATHOFP

View file

@ -0,0 +1,47 @@
BEGIN
# task 1 #
BEGIN
PR precision 32 PR
print( ( " 32 digit REAL numbers", newline ) );
[ 1 : 100 ]LONG LONG REAL v;
v[ 1 ] := 2;
v[ 2 ] := -4;
FOR n FROM 3 TO UPB v DO v[ n ] := 111 - ( 1130 / v[ n - 1 ] ) + ( 3000 / ( v[ n - 1 ] * v[ n - 2 ] ) ) OD;
FOR n FROM 3 TO 8 DO print( ( "n = ", whole( n, 3 ), " ", fixed( v[ n ], -22, 16 ), newline ) ) OD;
FOR n FROM 20 BY 10 TO 50 DO print( ( "n = ", whole( n, 3 ), " ", fixed( v[ n ], -22, 16 ), newline ) ) OD;
print( ( "n = 100 ", fixed( v[ 100 ], -22, 16 ), newline ) )
END;
BEGIN
PR precision 120 PR
print( ( "120 digit REAL numbers", newline ) );
[ 1 : 100 ]LONG LONG REAL v;
v[ 1 ] := 2;
v[ 2 ] := -4;
FOR n FROM 3 TO UPB v DO v[ n ] := 111 - ( 1130 / v[ n - 1 ] ) + ( 3000 / ( v[ n - 1 ] * v[ n - 2 ] ) ) OD;
print( ( "n = 100 ", fixed( v[ 100 ], -22, 16 ), newline ) )
END;
print( ( newline ) );
# task 2 #
BEGIN
print( ( "single precision REAL numbers...", newline ) );
REAL chaotic balance := exp( 1 ) - 1;
print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) );
FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD;
print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) )
END;
BEGIN
print( ( "double precision REAL numbers...", newline ) );
LONG REAL chaotic balance := long exp( 1 ) - 1;
print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) );
FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD;
print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) )
END;
BEGIN
PR precision 32 PR
print( ( " 32 digit REAL numbers...", newline ) );
LONG LONG REAL chaotic balance := long long exp( 1 ) - 1;
print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) );
FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD;
print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) )
END
END

View file

@ -0,0 +1,40 @@
BEGIN {
do_task1()
do_task2()
do_task3()
exit
}
function do_task1(){
print "Task 1"
v[1] = 2
v[2] = -4
for (n=3; n<=100; n++) v[n] = 111 - 1130 / v[n-1] + 3000 / (v[n-1] * v[n-2])
for (i=3; i<=8; i++) print_results(i)
print_results(20)
print_results(30)
print_results(50)
print_results(100)
}
# This works because all awk variables are global, except when declared locally
function print_results(n){
printf("n = %d\t%20.16f\n", n, v[n])
}
# This function doesn't need any parameters; declaring balance and i in the function parameters makes them local
function do_task2( balance, i){
balance[0] = exp(1)-1
for (i=1; i<=25; i++) balance[i] = balance[i-1]*i-1
printf("\nTask 2\nBalance after 25 years: $%12.10f", balance[25])
}
function do_task3( a, b, f_ab){
a = 77617
b = 33096
f_ab = 333.75 * b^6 + a^2 * (11*a^2*b^2 - b^6 - 121*b^4 - 2) + 5.5*b^8 + a/(2*b)
printf("\nTask 3\nf(%6.12f, %6.12f) = %10.24f", a, b, f_ab)
}

View file

@ -0,0 +1,46 @@
with Ada.Text_IO;
procedure Converging_Sequence is
generic
type Num is digits <>;
After: Positive;
procedure Task_1;
procedure Task_1 is
package FIO is new Ada.Text_IO.Float_IO(Num);
package IIO is new Ada.Text_IO.Integer_IO(Integer);
procedure Output (I: Integer; N: Num) is
begin
IIO.Put(Item => I, Width => 4);
FIO.Put(Item => N, Fore => 4, Aft => After, Exp => 0);
Ada.Text_IO.New_Line;
end Output;
Very_Old: Num := 2.0;
Old: Num := -4.0;
Now: Num;
begin
Ada.Text_IO.Put_Line("Converging Sequence with" & Integer'Image(After) &
" digits");
for I in 3 .. 100 loop
Now := 111.0 - 1130.0 / Old + 3000.0 / (Old * Very_Old);
Very_Old := Old;
Old := Now;
if (I < 9) or else (I=20 or I=30 or I=50 or I=100) then
Output(I, Now);
end if;
end loop;
Ada.Text_IO.New_Line;
end Task_1;
type Short is digits(8);
type Long is digits(16);
procedure Task_With_Short is new Task_1(Short, 8);
procedure Task_With_Long is new Task_1(Long, 16);
begin
Task_With_Short;
Task_With_Long;
end Converging_Sequence;

View file

@ -0,0 +1,36 @@
with Ada.Text_IO, Ada.Numerics;
procedure Chaotic_Bank is
generic
type Num is digits <>;
After: Positive;
procedure Task_2;
procedure Task_2 is
package IIO is new Ada.Text_IO.Integer_IO(Integer);
package FIO is new Ada.Text_IO.Float_IO(Num);
Balance: Num := Ada.Numerics.E - 1.0;
begin
Ada.Text_IO.Put_Line("Chaotic Bank Society with" &
Integer'Image(After) & " digits");
Ada.Text_IO.Put_Line("year balance");
for year in 1 .. 25 loop
Balance := (Balance * Num(year))- 1.0;
IIO.Put(Item => Year, Width => 2);
FIO.Put(Balance, Fore => 11, Aft => After, Exp => 0);
Ada.Text_IO.New_Line;
end loop;
Ada.Text_IO.New_Line;
end Task_2;
type Short is digits(8);
type Long is digits(16);
procedure Task_With_Short is new Task_2(Short, 8);
procedure Task_With_Long is new Task_2(Long, 16);
begin
Task_With_Short;
Task_With_Long;
end Chaotic_Bank;

View file

@ -0,0 +1,19 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Rumps_example is
type Short is digits(8);
type Long is digits(16);
A: constant := 77617.0;
B: constant := 33096.0;
C: constant := 333.75*B**6 + A**2*(11.0*A**2*B**2 - B**6 - 121.0*B**4 - 2.0) + 5.5*B**8 + A/(2.0*B);
package LIO is new Float_IO(Long);
package SIO is new Float_IO(Short);
begin
Put("Rump's Example, Short: ");
SIO.Put(C, Fore => 1, Aft => 8, Exp => 0); New_Line;
Put("Rump's Example, Long: ");
LIO.Put(C, Fore => 1, Aft => 16, Exp => 0); New_Line;
end Rumps_example;

View file

@ -0,0 +1,69 @@
#define USE_BIGRATIONAL
#define BANDED_ROWS
#define INCREASED_LIMITS
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using Numerics;
using static Common;
using static Task1;
using static Task2;
using static Task3;
#if !USE_BIGRATIONAL
// Mock structure to make test code work.
struct BigRational
{
public override string ToString() => "NOT USING BIGRATIONAL";
public static explicit operator decimal(BigRational value) => -1;
}
#endif
static class Common
{
public const string FMT_STR = "{0,4} {1,-15:G9} {2,-24:G17} {3,-32} {4,-32}";
public static string Headings { get; } =
string.Format(
CultureInfo.InvariantCulture,
FMT_STR,
new[] { "N", "Single", "Double", "Decimal", "BigRational (rounded as Decimal)" });
[Conditional("BANDED_ROWS")]
static void SetConsoleFormat(int n)
{
if (n % 2 == 0)
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
}
else
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
}
}
public static string FormatOutput(int n, (float sn, double db, decimal dm, BigRational br) x)
{
SetConsoleFormat(n);
return string.Format(CultureInfo.CurrentCulture, FMT_STR, n, x.sn, x.db, x.dm, (decimal)x.br);
}
static void Main()
{
WrongConvergence();
Console.WriteLine();
ChaoticBankSociety();
Console.WriteLine();
SiegfriedRump();
SetConsoleFormat(0);
}
}

View file

@ -0,0 +1,118 @@
static class Task1
{
public static IEnumerable<float> SequenceSingle()
{
// n, n-1, and n-2
float vn, vn_1, vn_2;
vn_2 = 2;
vn_1 = -4;
while (true)
{
yield return vn_2;
vn = 111f - (1130f / vn_1) + (3000f / (vn_1 * vn_2));
vn_2 = vn_1;
vn_1 = vn;
}
}
public static IEnumerable<double> SequenceDouble()
{
// n, n-1, and n-2
double vn, vn_1, vn_2;
vn_2 = 2;
vn_1 = -4;
while (true)
{
yield return vn_2;
vn = 111 - (1130 / vn_1) + (3000 / (vn_1 * vn_2));
vn_2 = vn_1;
vn_1 = vn;
}
}
public static IEnumerable<decimal> SequenceDecimal()
{
// n, n-1, and n-2
decimal vn, vn_1, vn_2;
vn_2 = 2;
vn_1 = -4;
// Use constants to avoid calling the Decimal constructor in the loop.
const decimal i11 = 111;
const decimal i130 = 1130;
const decimal E000 = 3000;
while (true)
{
yield return vn_2;
vn = i11 - (i130 / vn_1) + (E000 / (vn_1 * vn_2));
vn_2 = vn_1;
vn_1 = vn;
}
}
#if USE_BIGRATIONAL
public static IEnumerable<BigRational> SequenceRational()
{
// n, n-1, and n-2
BigRational vn, vn_1, vn_2;
vn_2 = 2;
vn_1 = -4;
// Same reasoning as for decimal.
BigRational i11 = 111;
BigRational i130 = 1130;
BigRational E000 = 3000;
while (true)
{
yield return vn_2;
vn = i11 - (i130 / vn_1) + (E000 / (vn_1 * vn_2));
vn_2 = vn_1;
vn_1 = vn;
}
}
#else
public static IEnumerable<BigRational> SequenceRational()
{
while (true) yield return default;
}
#endif
static void IncreaseMaxN(ref int[] arr)
{
int[] tmp = new int[arr.Length + 1];
arr.CopyTo(tmp, 0);
tmp[arr.Length] = 1000;
arr = tmp;
}
public static void WrongConvergence()
{
Console.WriteLine("Wrong Convergence Sequence:");
int[] displayedIndices = { 3, 4, 5, 6, 7, 8, 20, 30, 50, 100 };
IncreaseMaxN(ref displayedIndices);
var indicesSet = new HashSet<int>(displayedIndices);
Console.WriteLine(Headings);
int n = 1;
// Enumerate the implementations in parallel as tuples.
foreach (var x in SequenceSingle()
.Zip(SequenceDouble(), (sn, db) => (sn, db))
.Zip(SequenceDecimal(), (a, dm) => (a.sn, a.db, dm))
.Zip(SequenceRational(), (a, br) => (a.sn, a.db, a.dm, br)))
{
if (n > displayedIndices.Max()) break;
if (indicesSet.Contains(n))
Console.WriteLine(FormatOutput(n, x));
n++;
}
}
}

View file

@ -0,0 +1,94 @@
static class Task2
{
public static IEnumerable<float> ChaoticBankSocietySingle()
{
float balance = (float)(Math.E - 1);
for (int year = 1; ; year++)
yield return balance = (balance * year) - 1;
}
public static IEnumerable<double> ChaoticBankSocietyDouble()
{
double balance = Math.E - 1;
for (int year = 1; ; year++)
yield return balance = (balance * year) - 1;
}
public static IEnumerable<decimal> ChaoticBankSocietyDecimal()
{
// 27! is the largest factorial decimal can represent.
decimal balance = CalculateEDecimal(27) - 1;
for (int year = 1; ; year++)
yield return balance = (balance * year) - 1;
}
#if USE_BIGRATIONAL
public static IEnumerable<BigRational> ChaoticBankSocietyRational()
{
// 100 iterations is precise enough for 25 years.
BigRational brBalance = CalculateERational(100) - 1;
for (int year = 1; ; year++)
yield return brBalance = (brBalance * year) - 1;
}
#else
public static IEnumerable<BigRational> ChaoticBankSocietyRational()
{
while (true) yield return default;
}
#endif
public static decimal CalculateEDecimal(int terms)
{
decimal e = 1;
decimal fact = 1;
for (int i = 1; i <= terms; i++)
{
fact *= i;
e += decimal.One / fact;
}
return e;
}
#if USE_BIGRATIONAL
public static BigRational CalculateERational(int terms)
{
BigRational e = 1;
BigRational fact = 1;
for (int i = 1; i < terms; i++)
{
fact *= i;
e += BigRational.Invert(fact);
}
return e;
}
#endif
[Conditional("INCREASED_LIMITS")]
static void InceaseMaxYear(ref int year) => year = 40;
public static void ChaoticBankSociety()
{
Console.WriteLine("Chaotic Bank Society:");
Console.WriteLine(Headings);
int maxYear = 25;
InceaseMaxYear(ref maxYear);
int i = 0;
foreach (var x in ChaoticBankSocietySingle()
.Zip(ChaoticBankSocietyDouble(), (sn, db) => (sn, db))
.Zip(ChaoticBankSocietyDecimal(), (a, dm) => (a.sn, a.db, dm))
.Zip(ChaoticBankSocietyRational(), (a, br) => (a.sn, a.db, a.dm, br)))
{
if (i >= maxYear) break;
Console.WriteLine(FormatOutput(i + 1, x));
i++;
}
}
}

View file

@ -0,0 +1,122 @@
static class Task3
{
public static float SiegfriedRumpSingle(float a, float b)
{
float
a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
;
// Non-integral literals must be coerced to single using the type suffix.
return 333.75f * b6 +
(a2 * (
11 * a2 * b2 -
b6 -
121 * b4 -
2)) +
5.5f * b4 * b4 +
a / (2 * b);
}
public static double SiegfriedRumpDouble(double a, double b)
{
double
a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
;
// Non-integral literals are doubles by default.
return
333.75 * b6
+ a2 * (
11 * a2 * b * b
- b6
- 121 * b4
- 2)
+ 5.5 * b4 * b4
+ a / (2 * b);
}
public static decimal SiegfriedRumpDecimal(decimal a, decimal b)
{
decimal
a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
;
// The same applies for decimal.
return
333.75m * b6
+ a2 * (
11 * a2 * b * b
- b6
- 121 * b4
- 2)
+ 5.5m * b4 * b4
+ a / (2 * b);
}
#if USE_BIGRATIONAL
public static BigRational SiegfriedRumpRational(BigRational a, BigRational b)
{
// Use mixed number constructor to maintain exact precision (333+3/4, 5+1/2).
var c1 = new BigRational(33375, 100);
var c2 = new BigRational(55, 10);
return c1 * BigRational.Pow(b, 6)
+ (a * a * (
11 * a * a * b * b
- BigRational.Pow(b, 6)
- 121 * BigRational.Pow(b, 4)
- 2))
+ c2 * BigRational.Pow(b, 8)
+ a / (2 * b);
}
#else
public static IEnumerable<BigRational> SiegfriedRumpRational()
{
while (true) yield return default;
}
#endif
public static void SiegfriedRump()
{
Console.WriteLine("Siegfried Rump Formula");
int a = 77617;
int b = 33096;
Console.Write("Single: ");
float sn = SiegfriedRumpSingle(a, b);
Console.WriteLine("{0:G9}", sn);
Console.WriteLine();
Console.Write("Double: ");
double db = SiegfriedRumpDouble(a, b);
Console.WriteLine("{0:G17}", db);
Console.WriteLine();
Console.WriteLine("Decimal:");
decimal dm = 0;
try
{
dm = SiegfriedRumpDecimal(a, b);
}
catch (OverflowException ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine($" {dm}");
Console.WriteLine();
Console.WriteLine("BigRational:");
BigRational br = SiegfriedRumpRational(a, b);
Console.WriteLine($" Rounded: {(decimal)br}");
Console.WriteLine($" Exact: {br}");
}
}

View file

@ -0,0 +1,94 @@
#include<stdio.h>
#include<gmp.h>
void firstCase(){
mpf_t a,b,c;
mpf_inits(a,b,c,NULL);
mpf_set_str(a,"0.1",10);
mpf_set_str(b,"0.2",10);
mpf_add(c,a,b);
gmp_printf("\n0.1 + 0.2 = %.*Ff",20,c);
}
void pathologicalSeries(){
int n;
mpf_t v1, v2, vn, a1, a2, a3, t2, t3, prod;
mpf_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);
mpf_set_str(v1,"2",10);
mpf_set_str(v2,"-4",10);
mpf_set_str(a1,"111",10);
mpf_set_str(a2,"1130",10);
mpf_set_str(a3,"3000",10);
for(n=3;n<=100;n++){
mpf_div(t2,a2,v2);
mpf_mul(prod,v1,v2);
mpf_div(t3,a3,prod);
mpf_add(vn,a1,t3);
mpf_sub(vn,vn,t2);
if((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){
gmp_printf("\nv_%d : %.*Ff",n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,vn);
}
mpf_set(v1,v2);
mpf_set(v2,vn);
}
}
void healthySeries(){
int n;
mpf_t num,denom,result;
mpq_t v1, v2, vn, a1, a2, a3, t2, t3, prod;
mpf_inits(num,denom,result,NULL);
mpq_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);
mpq_set_str(v1,"2",10);
mpq_set_str(v2,"-4",10);
mpq_set_str(a1,"111",10);
mpq_set_str(a2,"1130",10);
mpq_set_str(a3,"3000",10);
for(n=3;n<=100;n++){
mpq_div(t2,a2,v2);
mpq_mul(prod,v1,v2);
mpq_div(t3,a3,prod);
mpq_add(vn,a1,t3);
mpq_sub(vn,vn,t2);
if((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){
mpf_set_z(num,mpq_numref(vn));
mpf_set_z(denom,mpq_denref(vn));
mpf_div(result,num,denom);
gmp_printf("\nv_%d : %.*Ff",n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,result);
}
mpq_set(v1,v2);
mpq_set(v2,vn);
}
}
int main()
{
mpz_t rangeProd;
firstCase();
printf("\n\nPathological Series : ");
pathologicalSeries();
printf("\n\nNow a bit healthier : ");
healthySeries();
return 0;
}

View file

@ -0,0 +1,6 @@
(def converge-to-six ((fn task1 [a b] (lazy-seq (cons a (task1 b (+ (- 111 (/ 1130 b)) (/ 3000 (* b a))))))) 2 -4))
(def values [3 4 5 6 7 8 20 30 50 100])
; print decimal values:
(pprint (sort (zipmap values (map double (map #(nth converge-to-six (dec %)) values)))))
; print rational values:
(pprint (sort (zipmap values (map #(nth converge-to-six (dec %)) values))))

View file

@ -0,0 +1,3 @@
(def e-ratio 106246577894593683/39085931702241241)
(defn bank [n m] (- (* n m) 1))
(double (reduce bank (- e-ratio 1) (range 1 26)))

View file

@ -0,0 +1,8 @@
(defn rump [a b]
(+ (* (rationalize 333.75) (expt b 6))
(* (expt a 2)
(- (* 11 (expt a 2) (expt b 2)) (expt b 6) (* 121 (expt b 4)) 2))
(* (rationalize 5.5) (expt b 8))
(/ a (* 2 b))))
; Using BigInt numeric literal style to avoid integer overflow
(double (rump 77617 33096N))

View file

@ -0,0 +1,9 @@
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

View file

@ -0,0 +1,9 @@
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

View file

@ -0,0 +1,19 @@
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}"

View file

@ -0,0 +1,7 @@
require "big"
e = 106246577894593683.to_big_d.div(39085931702241241.to_big_d)
balance = e - 1
1.upto(25) { |y| balance = (balance * y) - 1 }
puts "Bank balance after 25 years = #{balance.to_f}"

View file

@ -0,0 +1,8 @@
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}"

View file

@ -0,0 +1,149 @@
program Pathological_floating_point_problems;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigIntegers,
Velthuis.BigRationals,
Velthuis.BigDecimals;
type
TBalance = record
e, d: BigInteger;
end;
procedure Sequence(Precision: Integer);
var
v, v1, c111, c1130, c3000, t2, t3: BigRational;
n: integer;
begin
BigDecimal.DefaultPrecision := Precision;
v1 := 2;
v := -4;
n := 2;
c111 := BigRational(111);
c1130 := BigRational(1130);
c3000 := BigRational(3000);
var r :=
function(): BigRational
begin
t3 := v * v1;
t3 := BigRational.Create(BigDecimal.Divide(c3000, t3));
t2 := BigRational.Create(BigDecimal.Divide(c1130, v));
result := c111 - t2;
result := result + t3;
end;
writeln(' n sequence value');
for var x in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] do
begin
while n < x do
begin
var tmp := BigRational.Create(v);
v := BigRational.Create(r());
v1 := BigRational.Create(tmp);
inc(n);
end;
var f := double(v);
writeln(format('%3d %19.16f', [n, f]));
end;
end;
procedure Bank();
var
balance: TBalance;
m, one, ef, df: BigInteger;
e, b: BigDecimal;
begin
balance.e := 1;
balance.d := -1;
one := BigInteger.One;
for var y := 1 to 25 do
begin
m := y;
balance.e := m * balance.e;
balance.d := m * balance.d;
balance.d := balance.d - one;
end;
e := BigDecimal.Create('2.71828182845904523536028747135');
ef := balance.e;
df := balance.d;
b := e * ef;
b := b + df;
writeln(format('Bank balance after 25 years: $%.2f', [b.AsDouble]));
end;
function f(a, b: Double): Double;
var
a1, a2, b1, b2, b4, b6, b8, two, t1, t21, t2, t3, t4, t23: BigDecimal;
begin
var fp :=
function(x: double): BigDecimal
begin
Result := BigDecimal.Create(x);
end;
a1 := fp(a);
b1 := fp(b);
a2 := a1 * a1;
b2 := b1 * b1;
b4 := b2 * b2;
b6 := b2 * b4;
b8 := b4 * b4;
two := fp(2);
t1 := fp(333.75);
t1 := t1 * b6;
t21 := fp(11);
t21 := t21 * a2 * b2;
t23 := fp(121);
t23 := t23 * b4;
t2 := t21 - b6;
t2 := (t2 - t23) - two;
t2 := a2 * t2;
t3 := fp(5.5);
t3 := t3 * b8;
t4 := two * b1;
t4 := a1 / t4;
var s := t1 + t2;
s := s + t3;
s := s + t4;
result := s.AsDouble;
end;
procedure Rump();
var
a, b: Double;
begin
a := 77617;
b := 33096;
writeln(format('Rump f(%g, %g): %g', [a, b, f(a, b)]));
end;
{ TBigRationalHelper }
begin
for var Precision in [100, 200] do
begin
writeln(#10'Precision: ', Precision);
sequence(Precision);
bank();
rump();
end;
readln;
end.

View file

@ -0,0 +1,5 @@
A1: 2
A2: -4
A3: =111-1130/A2+3000/(A2*A1)
A4: =111-1130/A3+3000/(A3*A2)
...

View file

@ -0,0 +1,31 @@
USING: formatting fry io kernel locals math 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

View file

@ -0,0 +1,70 @@
SUBROUTINE MULLER
REAL*4 VN,VNL1,VNL2 !The exact precision and dynamic range
REAL*8 WN,WNL1,WNL2 !Depends on the format's precise usage of bits.
INTEGER I !A stepper.
WRITE (6,1) !A heading.
1 FORMAT ("Muller's sequence should converge to six...",/
1 " N Single Double")
VNL1 = 2; VN = -4 !Initialise for N = 2.
WNL1 = 2; WN = -4 !No fractional parts yet.
DO I = 3,36 !No point going any further.
VNL2 = VNL1; VNL1 = VN !Shuffle the values along one place.
WNL2 = WNL1; WNL1 = WN !Ready for the next term's calculation.
VN = 111 - 1130/VNL1 + 3000/(VNL1*VNL2) !Calculate the next term.
WN = 111 - 1130/WNL1 + 3000/(WNL1*WNL2) !In double precision.
WRITE (6,2) I,VN,WN !Show both.
2 FORMAT (I3,F12.7,F21.16) !With too many fractional digits.
END DO !On to the next term.
END SUBROUTINE MULLER !That was easy. Too bad the results are wrong.
SUBROUTINE CBS !The Chaotic Bank Society.
INTEGER YEAR !A stepper.
REAL*4 V !The balance.
REAL*8 W !In double precision as well.
V = 1; W = 1 !Initial values, without dozy 1D0 stuff.
V = EXP(V) - 1 !Actual initial value desired is e - 1..,
W = EXP(W) - 1 !This relies on double-precision W selecting DEXP.
WRITE (6,1) !Here we go.
1 FORMAT (///"The Chaotic Bank Society in action..."/"Year")
WRITE (6,2) 0,V,W !Show the initial deposit.
2 FORMAT (I3,F16.7,F28.16)
DO YEAR = 1,25 !Step through some years.
V = V*YEAR - 1 !The specified procedure.
W = W*YEAR - 1 !The compiler handles type conversions.
WRITE (6,2) YEAR,V,W !The current balance.
END DO !On to the following year.
END SUBROUTINE CBS !Madness!
REAL*4 FUNCTION SR4(A,B) !Siegfried Rump's example function of 1988.
REAL*4 A,B
SR4 = 333.75*B**6
1 + A**2*(11*A**2*B**2 - B**6 - 121*B**4 - 2)
2 + 5.5*B**8 + A/(2*B)
END FUNCTION SR4
REAL*8 FUNCTION SR8(A,B) !Siegfried Rump's example function.
REAL*8 A,B
SR8 = 333.75*B**6 !.75 is exactly represented in binary.
1 + A**2*(11*A**2*B**2 - B**6 - 121*B**4 - 2)
2 + 5.5*B**8 + A/(2*B)!.5 is exactly represented in binary.
END FUNCTION SR8
PROGRAM POKE
REAL*4 V !Some example variables.
REAL*8 W !Whose type goes to the inquiry function.
WRITE (6,1) RADIX(V),DIGITS(V),"single",DIGITS(W),"double"
1 FORMAT ("Floating-point arithmetic is conducted in base ",I0,/
1 2(I3," digits for ",A," precision",/))
WRITE (6,*) "Single precision limit",HUGE(V)
WRITE (6,*) "Double precision limit",HUGE(W)
WRITE (6,*)
CALL MULLER
CALL CBS
WRITE (6,10)
10 FORMAT (///"Evaluation of Siegfried Rump's function of 1988",
1 " where F(77617,33096) = -0.827396059946821")
WRITE (6,*) "Single precision:",SR4(77617.0,33096.0)
WRITE (6,*) "Double precision:",SR8(77617.0D0,33096.0D0) !Must match the types.
END

View file

@ -0,0 +1,36 @@
SUBROUTINE CBS !The Chaotic Bank Society.
INTEGER YEAR !A stepper.
REAL*4 V !The balance.
REAL*8 W !In double precision as well.
INTEGER NTERM !Share information with CBSERIES.
REAL*8 T !So as to show workings.
V = 1; W = 1 !Initial values, without dozy 1D0 stuff.
V = EXP(V) - 1 !Actual initial value desired is e - 1..,
W = EXP(W) - 1 !This relies on double-precision W selecting DEXP.
WRITE (6,1) !Here we go.
1 FORMAT (///"The Chaotic Bank Society in action...",/,
* "Year",9X,"Real*4",22X,"Real*8",12X,"Series summation",
* 9X,"Last term",2X,"Terms.")
WRITE (6,2) 0,V,W,CBSERIES(0),T,NTERM !Show the initial deposit.
2 FORMAT (I3,F16.7,2F28.16,D18.8,I7) !Not quite 16-digit precision for REAL*8.
DO YEAR = 1,25 !Step through some years.
V = V*YEAR - 1 !The specified procedure.
W = W*YEAR - 1 !The compiler handles type conversions.
WRITE (6,2) YEAR,V,W,CBSERIES(YEAR),T,NTERM !The current balance.
END DO !On to the following year.
CONTAINS !An alternative.
REAL*8 FUNCTION CBSERIES(N) !Calculates for the special deposit of e - 1.
INTEGER N !Desire the balance after year N for the deposit of e - 1.
REAL*8 S !Via a series summation.
S = 0 !Start the summation.
T = 1 !First term is 1/(N + 1)
I = N !Second is 1/[(N + 1)*(N + 2)], etc.
NTERM = 0 !No terms so far.
3 NTERM = NTERM + 1 !Here we go.
I = I + 1 !Thus advance to the next divisor, and not divide by zero.
T = T/I !Thus not compute the products from scratch each time.
S = S + T !Add the term.
IF (T/S .GE. EPSILON(S)) GO TO 3 !If they're still making a difference, another.
CBSERIES = S !Convergence is ever-faster as N increases.
END FUNCTION CBSERIES !So this is easy.
END SUBROUTINE CBS !Madness!

View file

@ -0,0 +1,98 @@
' FB 1.05.0 Win64
' As FB's native types have only 64 bit precision at most we need to use the
' C library, GMP v6.1.0, for arbitrary precision arithmetic
#Include Once "gmp.bi"
mpf_set_default_prec(640) '' 640 bit precision, enough for this exercise
Function v(n As UInteger, prev As __mpf_struct, prev2 As __mpf_struct) As __mpf_struct
Dim As __mpf_struct a, b, c
mpf_init(@a) : mpf_init(@b) : mpf_init(@c)
If n = 0 Then mpf_set_ui(@a, 0UL)
If n = 1 Then mpf_set_ui(@a, 2UL)
If n = 2 Then mpf_set_si(@a, -4L)
If n < 3 Then Return a
mpf_ui_div(@a, 1130UL, @prev)
mpf_mul(@b, @prev, @prev2)
mpf_ui_div(@c, 3000UL, @b)
mpf_ui_sub(@b, 111UL, @a)
mpf_add(@a, @b, @c)
mpf_clear(@b)
mpf_clear(@c)
Return a
End Function
Function f(a As Double, b As Double) As __mpf_Struct
Dim As __mpf_struct temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8
mpf_init(@temp1) : mpf_init(@temp2) : mpf_init(@temp3) : mpf_init(@temp4)
mpf_init(@temp5) : mpf_init(@temp6) : mpf_init(@temp7) : mpf_init(@temp8)
mpf_set_d(@temp1, a) '' a
mpf_set_d(@temp2, b) '' b
mpf_set_d(@temp3, 333.75) '' 333.75
mpf_pow_ui(@temp4, @temp2, 6UL) '' b ^ 6
mpf_mul(@temp3, @temp3, @temp4) '' 333.75 * b^6
mpf_pow_ui(@temp5, @temp1, 2UL) '' a^2
mpf_pow_ui(@temp6, @temp2, 2UL) '' b^2
mpf_mul_ui(@temp7, @temp5, 11UL) '' 11 * a^2
mpf_mul(@temp7, @temp7, @temp6) '' 11 * a^2 * b^2
mpf_sub(@temp7, @temp7, @temp4) '' 11 * a^2 * b^2 - b^6
mpf_pow_ui(@temp4, @temp2, 4UL) '' b^4
mpf_mul_ui(@temp4, @temp4, 121UL) '' 121 * b^4
mpf_sub(@temp7, @temp7, @temp4) '' 11 * a^2 * b^2 - b^6 - 121 * b^4
mpf_sub_ui(@temp7, @temp7, 2UL) '' 11 * a^2 * b^2 - b^6 - 121 * b^4 - 2
mpf_mul(@temp7, @temp7, @temp5) '' (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2
mpf_add(@temp3, @temp3, @temp7) '' 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2
mpf_set_d(@temp4, 5.5) '' 5.5
mpf_pow_ui(@temp5, @temp2, 8UL) '' b^8
mpf_mul(@temp4, @temp4, @temp5) '' 5.5 * b^8
mpf_add(@temp3, @temp3, @temp4) '' 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 + 5.5 * b^8
mpf_mul_ui(@temp4, @temp2, 2UL) '' 2 * b
mpf_div(@temp5, @temp1, @temp4) '' a / (2 * b)
mpf_add(@temp3, @temp3, @temp5) '' 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 + 5.5 * b^8 + a / (2 * b)
mpf_clear(@temp1) : mpf_clear(@temp2) : mpf_clear(@temp4) : mpf_clear(@temp5)
mpf_clear(@temp6) : mpf_clear(@temp7) : mpf_clear(@temp8)
Return temp3
End Function
Dim As Zstring * 60 z
Dim As __mpf_struct result, prev, prev2
' We cache the two previous results to avoid recursive calls to v
For i As Integer = 1 To 100
result = v(i, prev, prev2)
If (i >= 3 AndAlso i <= 8) OrElse i = 20 OrElse i = 30 OrElse i = 50 OrElse i = 100 Then
gmp_sprintf(@z,"%53.50Ff",@result) '' express result to 50 decimal places
Print "n ="; i , z
End If
prev2 = prev
prev = result
Next
mpf_clear(@prev) : mpf_clear(@prev2) '' note : prev = result
Dim As __mpf_struct e, balance, ii, temp
mpf_init(@e) : mpf_init(@balance) : mpf_init(@ii) : mpf_init(@temp)
mpf_set_str(@e, "2.71828182845904523536028747135266249775724709369995", 10) '' e to 50 decimal places
mpf_sub_ui(@balance, @e, 1UL)
For i As ULong = 1 To 25
mpf_set_ui(@ii, i)
mpf_mul(@temp, @balance, @ii)
mpf_sub_ui(@balance, @temp, 1UL)
Next
Print
Print "Chaotic B/S balance after 25 years : ";
gmp_sprintf(@z,"%.16Ff",@balance) '' express balance to 16 decimal places
Print z
mpf_clear(@e) : mpf_clear(@balance) : mpf_clear(@ii) : mpf_clear(@temp)
Print
Dim rump As __mpf_struct
rump = f(77617.0, 33096.0)
gmp_sprintf(@z,"%.16Ff", @rump) '' express rump to 16 decimal places
Print "f(77617.0, 33096.0) = "; z
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,94 @@
package main
import (
"fmt"
"math/big"
)
func main() {
sequence()
bank()
rump()
}
func sequence() {
// exact computations using big.Rat
var v, v1 big.Rat
v1.SetInt64(2)
v.SetInt64(-4)
n := 2
c111 := big.NewRat(111, 1)
c1130 := big.NewRat(1130, 1)
c3000 := big.NewRat(3000, 1)
var t2, t3 big.Rat
r := func() (vn big.Rat) {
vn.Add(vn.Sub(c111, t2.Quo(c1130, &v)), t3.Quo(c3000, t3.Mul(&v, &v1)))
return
}
fmt.Println(" n sequence value")
for _, x := range []int{3, 4, 5, 6, 7, 8, 20, 30, 50, 100} {
for ; n < x; n++ {
v1, v = v, r()
}
f, _ := v.Float64()
fmt.Printf("%3d %19.16f\n", n, f)
}
}
func bank() {
// balance as integer multiples of e and whole dollars using big.Int
var balance struct{ e, d big.Int }
// initial balance
balance.e.SetInt64(1)
balance.d.SetInt64(-1)
// compute balance over 25 years
var m, one big.Int
one.SetInt64(1)
for y := 1; y <= 25; y++ {
m.SetInt64(int64(y))
balance.e.Mul(&m, &balance.e)
balance.d.Mul(&m, &balance.d)
balance.d.Sub(&balance.d, &one)
}
// sum account components using big.Float
var e, ef, df, b big.Float
e.SetPrec(100).SetString("2.71828182845904523536028747135")
ef.SetInt(&balance.e)
df.SetInt(&balance.d)
b.Add(b.Mul(&e, &ef), &df)
fmt.Printf("Bank balance after 25 years: $%.2f\n", &b)
}
func rump() {
a, b := 77617., 33096.
fmt.Printf("Rump f(%g, %g): %g\n", a, b, f(a, b))
}
func f(a, b float64) float64 {
// computations done with big.Float with enough precision to give
// a correct answer.
fp := func(x float64) *big.Float { return big.NewFloat(x).SetPrec(128) }
a1 := fp(a)
b1 := fp(b)
a2 := new(big.Float).Mul(a1, a1)
b2 := new(big.Float).Mul(b1, b1)
b4 := new(big.Float).Mul(b2, b2)
b6 := new(big.Float).Mul(b2, b4)
b8 := new(big.Float).Mul(b4, b4)
two := fp(2)
t1 := fp(333.75)
t1.Mul(t1, b6)
t21 := fp(11)
t21.Mul(t21.Mul(t21, a2), b2)
t23 := fp(121)
t23.Mul(t23, b4)
t2 := new(big.Float).Sub(t21, b6)
t2.Mul(a2, t2.Sub(t2.Sub(t2, t23), two))
t3 := fp(5.5)
t3.Mul(t3, b8)
t4 := new(big.Float).Mul(two, b1)
t4.Quo(a1, t4)
s := new(big.Float).Add(t1, t2)
f64, _ := s.Add(s.Add(s, t3), t4).Float64()
return f64
}

View file

@ -0,0 +1,88 @@
#
# Pathological floating point problems
#
procedure main()
sequence()
chaotic()
end
#
# First task, sequence convergence
#
link printf
procedure sequence()
local l := [2, -4]
local iters := [3, 4, 5, 6, 7, 8, 20, 30, 50, 100, 200]
local i, j, k
local n := 1
write("Sequence convergence")
# Demonstrate the convergence problem with various precision values
every k := (100 | 300) do {
n := 10^k
write("\n", k, " digits of intermediate precision")
# numbers are scaled up using large integer powers of 10
every i := !iters do {
l := [2 * n, -4 * n]
printf("i: %3d", i)
every j := 3 to i do {
# build out a list of intermediate passes
# order of scaling operations matters
put(l, 111 * n - (1130 * n * n / l[j - 1]) +
(3000 * n * n * n / (l[j - 1] * l[j - 2])))
}
# down scale the result to a real
# some precision may be lost in the final display
printf(" %20.16r\n", l[i] * 1.0 / n)
}
}
end
#
# Task 2, chaotic bank of Euler
#
procedure chaotic()
local euler, e, scale, show, y, d
write("\nChaotic Banking Society of Euler")
# format the number for listing, string form, way overboard on digits
euler :=
"2718281828459045235360287471352662497757247093699959574966967627724076630353_
547594571382178525166427427466391932003059921817413596629043572900334295260_
595630738132328627943490763233829880753195251019011573834187930702154089149_
934884167509244761460668082264800168477411853742345442437107539077744992069_
551702761838606261331384583000752044933826560297606737113200709328709127443_
747047230696977209310141692836819025515108657463772111252389784425056953696_
770785449969967946864454905987931636889230098793127736178215424999229576351_
482208269895193668033182528869398496465105820939239829488793320362509443117_
301238197068416140397019837679320683282376464804295311802328782509819455815_
301756717361332069811250996181881593041690351598888519345807273866738589422_
879228499892086805825749279610484198444363463244968487560233624827041978623_
209002160990235304369941849146314093431738143640546253152096183690888707016_
768396424378140592714563549061303107208510383750510115747704171898610687396_
9655212671546889570350354"
# precise math with long integers, string form just for pretty listing
e := integer(euler)
# 1000 digits after the decimal for scaling intermediates and service fee
scale := 10^1000
# initial deposit - $1
d := e - scale
# show balance with 16 digits
show := 10^16
write("Starting balance: $", d * show / scale * 1.0 / show, "...")
# wait 25 years, with only a trivial $1 service fee
every y := 1 to 25 do {
d := d * y - scale
}
# show final balance with 4 digits after the decimal (truncation)
show := 10^4
write("Balance after ", y, " years: $", d * show / scale * 1.0 / show)
end

View file

@ -0,0 +1 @@
vn=: 111 +(_1130 % _1&{) + (3000 % _1&{ * _2&{)

View file

@ -0,0 +1,31 @@
rump=:4 :0
NB. enforce exact arithmetic
add=. +&x:
sub=. -&x:
mul=. *&x:
div=. %&x:
a=. x
a2=. a mul a
b=. y
b2=. b mul b
b4=. b2 mul b2
b6=. b2 mul b4
b8=. b4 mul b4
c333_75=. 1335 div 4 NB. 333.75
term1=. c333_75 mul b6
t11a2b2=. 11 mul a2 mul b2
tnb6=. 0 sub b6
tn121b4=. 0 sub 121 mul b4
term2=. a2*(t11a2b2 + tnb6 + tn121b4 sub 2)
c5_5=. 11 div 2 NB. 5.5
term3=. c5_5 mul b8
term4=. a div 2 mul b
term1 add term2 add term3 add term4
)

View file

@ -0,0 +1,2 @@
21j16": 77617 rump 33096
_0.8273960599468214

View file

@ -0,0 +1,2 @@
77617 rump 33096
_1.39061e21

View file

@ -0,0 +1,2 @@
33096^8
1.43947e36

View file

@ -0,0 +1,11 @@
3 21j16 ":"1] 3 4 5 6 7 8 20 30 50 100 ([,.{) (,vn)^:100(2 _4)
3 9.3783783783783861
4 7.8011527377522611
5 7.1544144809765555
6 6.8067847369419638
7 6.5926327689743687
8 6.4494659378910058
20 99.9934721906444960
30 100.0000000000000000
50 100.0000000000000000
100 100.0000000000000000

View file

@ -0,0 +1,11 @@
3 21j16 ":"1] 3 4 5 6 7 8 20 30 50 100 ([,.{) (,vn)^:100(2 _4x)
3 9.3783783783783784
4 7.8011527377521614
5 7.1544144809752494
6 6.8067847369236330
7 6.5926327687044384
8 6.4494659337902880
20 6.0360318810818568
30 6.0056486887714203
50 6.0001465345613879
100 6.0000000160995649

View file

@ -0,0 +1,5 @@
e=: +/%1,*/\1+i.100x
81j76":e
2.7182818284590452353602874713526624977572470936999595749669676277240766303535
21j16":+`*/,_1,.(1+i.-25),e
0.0399387296732302

View file

@ -0,0 +1,2 @@
31j16":+`*/,_1,.(1+i.-25),6157974361033%2265392166685x
_2053975868590.1852178761057505

View file

@ -0,0 +1,2 @@
31j16":+`*/,_1,.(1+i.-25),6157974361034%2265392166685x
4793054977300.3491517765983265

View file

@ -0,0 +1,4 @@
1x1
2.71828
+`*/,_1,.(1+i.-25),1x1
_2.24237e9

View file

@ -0,0 +1,10 @@
21j16":+`*/,_1,.(1+i.-25),+/%1,*/\1+i.40x
0.0399387296732302
21j16":+`*/,_1,.(1+i.-25),+/%1,*/\1+i.30x
0.0399387277260840
21j16":+`*/,_1,.(1+i.-25),+/%1,*/\1+i.26x
0.0384615384615385
21j16":+`*/,_1,.(1+i.-25),+/%1,*/\1+i.25x
0.0000000000000000
21j16":+`*/,_1,.(1+i.-25),+/%1,*/\1+i.24x
_1.0000000000000000

View file

@ -0,0 +1,6 @@
41j36":+/%1,*/\1+i.26x
2.718281828459045235360287471257428715
41j36":+/%1,*/\1+i.25x
2.718281828459045235360287468777832452
41j36":+/%1,*/\1+i.24x
2.718281828459045235360287404308329608

View file

@ -0,0 +1,97 @@
import java.math.BigDecimal;
import java.math.RoundingMode;
public class FPProblems {
public static void wrongConvergence() {
int[] INDEXES = new int[] { 3, 4, 5, 6, 7, 8, 20, 30, 50, 100 };
// Standard 64-bit floating point
double[] fpValues = new double[100];
fpValues[0] = 2.0;
fpValues[1] = -4.0;
for (int i = 2; i < fpValues.length; i++) {
fpValues[i] = 111.0 - 1130.0 / fpValues[i - 1] + 3000.0 / (fpValues[i - 1] * fpValues[i - 2]);
}
// Using rational representation
BigRational[] brValues = new BigRational[100];
brValues[0] = BigRational.valueOf(2);
brValues[1] = BigRational.valueOf(-4);
for (int i = 2; i < brValues.length; i++) {
// Using intermediate values for better readability
BigRational clause2 = BigRational.valueOf(1130).divide(brValues[i - 1]);
BigRational clause3 = BigRational.valueOf(3000).divide(brValues[i - 1].multiply(brValues[i - 2]));
brValues[i] = BigRational.valueOf(111).subtract(clause2).add(clause3);
}
System.out.println("Wrong Convergence Sequence");
for (int n : INDEXES) {
BigDecimal value = brValues[n - 1].toBigDecimal(16, RoundingMode.HALF_UP);
System.out.println(" For index " + n + ", FP value is " + fpValues[n - 1] + ", and rounded BigRational value is " + value.toPlainString());
}
return;
}
public static void chaoticBankSociety() {
System.out.println("Chaotic Bank Society");
double balance = Math.E - 1.0;
// Calculate e using first 1000 terms of the reciprocal of factorials formula
BigRational e = BigRational.ONE;
BigRational d = BigRational.ONE;
for (int i = 1; i < 1000; i++) {
d = d.multiply(BigRational.valueOf(i));
e = e.add(d.reciprocal());
}
System.out.println("DEBUG: e=" + e.toBigDecimal(100, RoundingMode.HALF_UP).toPlainString());
// Alternatively,
// BigRational e = BigRational.valueOf(Math.E);
BigRational brBalance = e.subtract(BigRational.ONE);
for (int year = 1; year <= 25; year++) {
balance = (balance * year) - 1.0;
brBalance = brBalance.multiply(BigRational.valueOf(year)).subtract(BigRational.ONE);
BigDecimal bdValue = brBalance.toBigDecimal(16, RoundingMode.HALF_UP);
System.out.println(" Year=" + year + ", FP balance=" + balance + ", BigRational balance=" + bdValue.toPlainString());
}
}
public static void siegfriedRump() {
System.out.println("Siegfried Rump formula");
double fpValue;
{
double a = 77617.0;
double b = 33096.0;
fpValue = 333.75 * Math.pow(b, 6) + a * a * (11.0 * a * a * b * b - Math.pow(b, 6) - 121.0 * Math.pow(b, 4) - 2.0) + 5.5 * Math.pow(b, 8) + a / (2.0 * b);
}
BigRational brValue;
{
BigRational a = BigRational.valueOf(77617);
BigRational b = BigRational.valueOf(33096);
BigRational clause1 = BigRational.valueOf(333.75).multiply(b.pow(6));
BigRational clause2a = BigRational.valueOf(11).multiply(a).multiply(a).multiply(b).multiply(b);
BigRational clause2b = b.pow(6).add(BigRational.valueOf(121).multiply(b.pow(4))).add(BigRational.valueOf(2));
BigRational clause2 = a.multiply(a).multiply(clause2a.subtract(clause2b));
BigRational clause3 = BigRational.valueOf(5.5).multiply(b.pow(8));
BigRational clause4 = a.divide(b.multiply(BigRational.valueOf(2)));
brValue = clause1.add(clause2).add(clause3).add(clause4);
}
System.out.println(" FP value is " + fpValue);
System.out.println(" BigRational rounded value is " + brValue.toBigDecimal(64, RoundingMode.HALF_UP).toPlainString());
System.out.println(" BigRational full value is " + brValue.toString());
}
public static void main(String... args) {
wrongConvergence();
System.out.println();
chaoticBankSociety();
System.out.println();
siegfriedRump();
}
}

View file

@ -0,0 +1,17 @@
# Input: the value at which to compute v
def v:
# Input: cache
# Output: updated cache
def v_(n):
(n|tostring) as $s
| . as $cache
| if ($cache | has($s)) then .
else if n == 1 then $cache["1"] = 2
elif n == 2 then $cache["2"] = -4
else ($cache | v_(n-1) | v_(n - 2)) as $new
| $new[(n-1)|tostring] as $x
| $new[(n-2)|tostring] as $y
| $new + {($s): ((111 - (1130 / $x) + (3000 / ($x * $y)))) }
end
end;
. as $m | {} | v_($m) | .[($m|tostring)] ;

View file

@ -0,0 +1 @@
(3,4,5,6,7,8,20,30,50,100) | v

View file

@ -0,0 +1,11 @@
# Given the balance in the prior year, compute the new balance in year n.
# Input: { e: m, c: n } representing m*e + n
def new_balance(n):
if n == 0 then {e: 1, c: -1}
else {e: (.e * n), c: (.c * n - 1) }
end;
def balance(n):
def e: 1|exp;
reduce range(0;n) as $i ({}; new_balance($i) )
| (.e * e) + .c;

View file

@ -0,0 +1,39 @@
using Printf
# arbitrary precision
setprecision(2000)
# Task 1
function seq(n)
len = maximum(n)
r = Vector{BigFloat}(len)
r[1] = 2
if len > 1 r[2] = -4 end
for i in 3:len
r[i] = 111 - 1130 / r[i-1] + 3000 / (r[i-1] * r[i-2])
end
return r[n]
end
n = [1, 2, 3, 5, 10, 100]
v = seq(n)
println("Task 1 - Sequence convergence:\n", join((@sprintf("v%-3i = %23.20f", i, s) for (i, s) in zip(n, v)), '\n'))
# Task 2: solution with big float (precision can be set with setprecision function)
function chaoticbankfund(years::Integer)
balance = big(e) - 1
for y in 1:years
balance = (balance * y) - 1
end
return balance
end
println("\nTask 2 - Chaotic Bank fund after 25 years:\n", @sprintf "%.20f" chaoticbankfund(25))
# Task 3: solution with big float
f(a::Union{BigInt,BigFloat}, b::Union{BigInt,BigFloat}) =
333.75b ^ 6 + a ^ 2 * ( 11a ^ 2 * b ^ 2 - b ^ 6 - 121b ^ 4 - 2 ) + 5.5b ^ 8 + a / 2b
println("\nTask 3 - Siegfried Rump's example:\nf(77617.0, 33096.0) = ", @sprintf "%.20f" f(big(77617.0), big(33096.0)))

View file

@ -0,0 +1,42 @@
// version 1.0.6
import java.math.*
const val LIMIT = 100
val con480 = MathContext(480)
val bigTwo = BigDecimal(2)
val bigE = BigDecimal("2.71828182845904523536028747135266249775724709369995") // precise enough!
fun main(args: Array<String>) {
// v(n) sequence task
val c1 = BigDecimal(111)
val c2 = BigDecimal(1130)
val c3 = BigDecimal(3000)
var v1 = bigTwo
var v2 = BigDecimal(-4)
var v3: BigDecimal
for (i in 3 .. LIMIT) {
v3 = c1 - c2.divide(v2, con480) + c3.divide(v2 * v1, con480)
println("${"%3d".format(i)} : ${"%19.16f".format(v3)}")
v1 = v2
v2 = v3
}
// Chaotic Building Society task
var balance = bigE - BigDecimal.ONE
for (year in 1..25) balance = balance.multiply(BigDecimal(year), con480) - BigDecimal.ONE
println("\nBalance after 25 years is ${"%18.16f".format(balance)}")
// Siegfried Rump task
val a = BigDecimal(77617)
val b = BigDecimal(33096)
val c4 = BigDecimal("333.75")
val c5 = BigDecimal(11)
val c6 = BigDecimal(121)
val c7 = BigDecimal("5.5")
var f = c4 * b.pow(6, con480) + c7 * b.pow(8, con480) + a.divide(bigTwo * b, con480)
val c8 = c5 * a.pow(2, con480) * b.pow(2, con480) - b.pow(6, con480) - c6 * b.pow(4, con480) - bigTwo
f += c8 * a.pow(2, con480)
println("\nf(77617.0, 33096.0) is ${"%18.16f".format(f)}")
}

View file

@ -0,0 +1,29 @@
module Pathological_floating_point_problems{
decimal vn[3]
vn[1]=2
vn[2]=-4
for i=3 to 100
vn[i]=111@-1130@/vn[i-1]+3000@/(vn[i-1]*vn[i-2])
next
n=list:=3,4,5,6,7,8,20,25
k=each(n)
while k
report "n = "+eval$(k)+chr$(9)+(vn[eval(k)])
end while
}
print "Task 1"
Pathological_floating_point_problems
print
print "Task 2"
module Chaotic_Bank_Society {
decimal Balance=2.7182818284590452353602874713@-1@
string frmt="year {0::-2} Balance:{1}"
for i=1 to 25
Balance=Balance*i-1@
rem print format$(frmt, i, Balance)
next i
Print "Starting balance: $e-1"
Print "Balance = (Balance * year) - 1 for 25 years"
print "Balance after 25 years: $"+Balance
}
Chaotic_Bank_Society

View file

@ -0,0 +1,4 @@
v[1] = 2;
v[2] = -4;
v[n_] := Once[111 - 1130/v[n - 1] + 3000/(v[n - 1]*v[n - 2])]
N[Map[v, {3, 4, 5, 6, 7, 8, 20, 30, 50, 100}], 80]

View file

@ -0,0 +1 @@
year = 1; N[Nest[# year++ - 1 &, E - 1, 25], 30]

View file

@ -0,0 +1,2 @@
f[a_, b_] := 333.75`100 b^6 + a^2 (11 a^2 b^2 - b^6 - 121 b^4 - 2) + 5.5`100 b^8 + a/(2 b)
f[77617, 33096]

View file

@ -0,0 +1,115 @@
import math, strutils, strformat
import decimal
import bignum
####################################################################################################
# Utilities.
proc format[T: DecimalType|Rat](val: T; intLen, fractLen: Positive): string =
## Format a decimal or a rational with "intLen" integer digits and "fractLen"
## fractional digits.
let s = when T is DecimalType: ($val).split('.')
else: ($val.toFloat).split('.')
result = s[0].align(intLen) & '.'
if s[1].len < fractLen:
result.add s[1].alignLeft(fractLen, '0')
else:
result.add s[1][0..<fractLen]
proc `^`(a: Rat; b: Natural): Rat =
## Missing exponentiation operator for rationals.
## Adaptation of operator for floats.
case b
of 0: result = newRat(1)
of 1: result = a
of 2: result = a * a
of 3: result = a * a * a
else:
var (a, b) = (a.clone, b)
result = newRat(1)
while true:
if (b and 1) != 0:
result *= a
b = b shr 1
if b == 0: break
a *= a
####################################################################################################
# Task 1.
proc v[T: float|DecimalType|Rat](n: Positive): seq[T] =
## Return the "n" first values for sequence "Vn".
var (v1, v2) = when T is float: (2.0, -4.0)
elif T is Rat: (newRat(2), newRat(-4))
else: (newDecimal(2), newDecimal(-4))
result.add default(T) # Dummy value to start at index one.
result.add v1
result.add v2
for _ in 3..n:
# Need to change evaluation order to avoid a bug with rationals.
result.add 3000 / (result[^1] * result[^2]) - 1130 / result[^1] + 111
setPrec(130) # Default precision is not sufficient.
let vfloat = v[float](100)
let vdecimal = v[DecimalType](100)
let vrational = v[Rat](100)
echo "Task 1"
echo " n v(n) float v(n) decimal v(n) rational"
for n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]:
echo &"{n:>3} {vfloat[n]:>20.16f} {vdecimal[n].format(3, 16)} {vrational[n].format(3, 16)}"
####################################################################################################
# Task 2.
proc balance[T: float|DecimalType|Rat](): T =
## Return the balance after 25 years.
result = when T is float: E - 1
elif T is DecimalType: exp(newDecimal(1)) - 1
else: newInt("17182818284590452353602874713526624977572470") /
newInt("10000000000000000000000000000000000000000000")
var n = when T is float: 1.0 else: 1
while n <= 25:
result = result * n - 1
n += 1
echo "\nTask 2."
echo "Balance after 25 years (float): ", (&"{balance[float]():.16f}")[0..17]
echo "Balance after 25 years (decimal): ", balance[DecimalType]().format(1, 16)
echo "Balance after 25 years: (rational): ", balance[Rat]().format(1, 16)
####################################################################################################
# Task 3.
const
A = 77617
B = 33096
proc rump[T: float|DecimalType|Rat](a, b: T): T =
## Return the value of the Rump's function.
let C1 = when T is float: 333.75
elif T is Rat: newRat(333.75)
else: newDecimal("333.75")
let C2 = when T is float: 5.5
elif T is Rat: newRat(5.5)
else: newDecimal("5.5")
result = C1 * b^6 + a^2 * (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) + C2 * b^8 + a / (2 * b)
echo "\nTask 3"
let rumpFloat = rump(A.toFloat, B.toFloat)
let rumpDecimal = rump(newDecimal(A), newDecimal(B))
let rumpRational = rump(newRat(A), newRat(B))
echo &"f({A}, {B}) float = ", rumpFloat
echo &"f({A}, {B}) decimal = ", rumpDecimal.format(1, 16)
echo &"f({A}, {B}) rational = ", rumpRational.format(1, 16)

View file

@ -0,0 +1 @@
V(n,a=2,v=-4.)=if(n < 3,return(v));V(n--,v,111-1130/v+3000/(v*a))

View file

@ -0,0 +1 @@
balance(d,y)=d--;for(n=1,y,d=d*n-1);d

View file

@ -0,0 +1 @@
f(a,b)=333.75*b^6+a*a*(11*a*a*b*b-b^6-121*b^4-2)+5.5*b^8+a/(2*b)

View file

@ -0,0 +1,11 @@
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;
}

View file

@ -0,0 +1,8 @@
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;

View file

@ -0,0 +1,5 @@
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);

View file

@ -0,0 +1,46 @@
(phixonline)-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">bigatom</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Task 1\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fns</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmts</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">24</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">50</span><span style="color: #0000FF;">,</span><span style="color: #000000;">40</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">78</span><span style="color: #0000FF;">}})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_scale</span><span style="color: #0000FF;">(</span><span style="color: #000000;">196</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #000080;font-style:italic;">-- v = append(v,111 - 1130/v[n-1] + 3000/(v[n-1]*v[n-2]))</span>
<span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">111</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_divide</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1130</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])),</span><span style="color: #000000;">ba_divide</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]))))</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">9</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- printf(1,"n = %-3d %20.16f\n", {n, v[n]})</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%%.%dB"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmts</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fns</span><span style="color: #0000FF;">)])</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"n = %-3d %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ba_sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">])})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nTask 2\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--atom balance = exp(1)-1
--for i=1 to 25 do balance = balance*i-1 end for
--printf(1,"\nTask 2\nBalance after 25 years: $%12.10f", balance)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_scale</span><span style="color: #0000FF;">(</span><span style="color: #000000;">41</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">bigatom</span> <span style="color: #000000;">balance</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_euler</span><span style="color: #0000FF;">(</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">25</span> <span style="color: #008080;">do</span> <span style="color: #000000;">balance</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">balance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">ba_printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Balance after 25 years: $%.16B\n\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">balance</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Task 3\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_scale</span><span style="color: #0000FF;">(</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- fine!</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">77617</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">33096</span>
<span style="color: #000080;font-style:italic;">--atom pa2 = power(a,2),
-- pb2a211 = 11*pa2*power(b,2),
-- pb4121 = 121*power(b,4),
-- pb6 = power(b,6),
-- pb855 = 5.5*power(b,8),
-- f_ab = 333.75 * pb6 + pa2 * (pb2a211 - pb6 - pb4121 - 2) + pb855 + a/(2*b)
--printf(1,"f(%d, %d) = %.15f\n\n", {a, b, f_ab})</span>
<span style="color: #000000;">bigatom</span> <span style="color: #000000;">pa2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pb2a211</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pa2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))),</span>
<span style="color: #000000;">pb4121</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">121</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">pb6</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pa2mid</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pa2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pb2a211</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pb6</span><span style="color: #0000FF;">),</span><span style="color: #000000;">pb4121</span><span style="color: #0000FF;">),</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">pb633375</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">333.75</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pb6</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pb855</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5.5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">f_ab</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ba_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ba_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pb633375</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pa2mid</span><span style="color: #0000FF;">),</span><span style="color: #000000;">pb855</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ba_divide</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ba_multiply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"f(%d, %d) = %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ba_sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%.15B"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f_ab</span><span style="color: #0000FF;">)})</span>
<!--

View file

@ -0,0 +1,79 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpfr_set_default_prec[ision] has been renamed)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Task 1\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fns</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fdp</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">24</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">50</span><span style="color: #0000FF;">,</span><span style="color: #000000;">40</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">78</span><span style="color: #0000FF;">}})</span>
<span style="color: #7060A8;">mpfr_set_default_precision</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">196</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)}</span>
<span style="color: #004080;">mpfr</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #000080;font-style:italic;">-- v = append(v,111 - 1130/v[n-1] + 3000/(v[n-1]*v[n-2]))</span>
<span style="color: #7060A8;">mpfr_set_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1130</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpfr_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
<span style="color: #7060A8;">mpfr_si_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">111</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpfr</span> <span style="color: #000000;">t2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<span style="color: #7060A8;">mpfr_si_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpfr_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">9</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- printf(1,"n = %-3d %20.16f\n", {n, v[n]})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"n = %-3d %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">],</span><span style="color: #000000;">fdp</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fns</span><span style="color: #0000FF;">)])})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nTask 2\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--atom balance = exp(1)-1
--for i=1 to 25 do balance = balance*i-1 end for
--printf(1,"\nTask 2\nBalance after 25 years: $%12.10f", balance)</span>
<span style="color: #7060A8;">mpfr_set_default_precision</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">41</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpfr</span> <span style="color: #000000;">balance</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.71828182845904523536028747135266249775724709369995"</span><span style="color: #0000FF;">&</span>
<span style="color: #008000;">"95749669676277240766303535475945713821785251664274"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">25</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpfr_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">balance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">balance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpfr_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">balance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">balance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Balance after 25 years: $%s\n\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">balance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Task 3\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpfr_set_default_precision</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">36</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">77617</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">33096</span>
<span style="color: #000080;font-style:italic;">--atom pa2 = power(a,2),
-- pb2a211 = 11*pa2*power(b,2),
-- pb4121 = 121*power(b,4),
-- pb6 = power(b,6),
-- pb855 = 5.5*power(b,8),
-- f_ab = 333.75 * pb6 + pa2 * (pb2a211 - pb6 - pb4121 - 2) + pb855 + a/(2*b)
--printf(1,"f(%d, %d) = %.15f\n\n", {a, b, f_ab})
-- (translation of FreeBASIC)</span>
<span style="color: #004080;">mpfr</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpfr_set_d</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- a</span>
<span style="color: #7060A8;">mpfr_set_d</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- b </span>
<span style="color: #7060A8;">mpfr_set_d</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">333.75</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 333.75</span>
<span style="color: #7060A8;">mpfr_pow_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- b ^ 6</span>
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 333.75 * b^6</span>
<span style="color: #7060A8;">mpfr_pow_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- a^2</span>
<span style="color: #7060A8;">mpfr_pow_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- b^2</span>
<span style="color: #7060A8;">mpfr_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">11</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 11 * a^2</span>
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t6</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 11 * a^2 * b^2</span>
<span style="color: #7060A8;">mpfr_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 11 * a^2 * b^2 - b^6</span>
<span style="color: #7060A8;">mpfr_pow_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- b^4</span>
<span style="color: #7060A8;">mpfr_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">121</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 121 * b^4</span>
<span style="color: #7060A8;">mpfr_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 11 * a^2 * b^2 - b^6 - 121 * b^4</span>
<span style="color: #7060A8;">mpfr_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 11 * a^2 * b^2 - b^6 - 121 * b^4 - 2</span>
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2</span>
<span style="color: #7060A8;">mpfr_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t7</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2</span>
<span style="color: #7060A8;">mpfr_set_d</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5.5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 5.5</span>
<span style="color: #7060A8;">mpfr_pow_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- b^8 </span>
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 5.5 * b^8</span>
<span style="color: #7060A8;">mpfr_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 + 5.5 * b^8</span>
<span style="color: #7060A8;">mpfr_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 2 * b</span>
<span style="color: #7060A8;">mpfr_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- a / (2 * b)</span>
<span style="color: #7060A8;">mpfr_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 + 5.5 * b^8 + a / (2 * b)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"f(%d, %d) = %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)})</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t7</span><span style="color: #0000FF;">})</span>
<!--

View file

@ -0,0 +1,51 @@
(scl 150)
(de task1 (N)
(cache '(NIL) N
(cond
((= N 1) 2.0)
((= N 2) -4.0)
(T
(+
(- 111.0 (*/ 1.0 1130.0 (task1 (- N 1))))
(*/
1.0
3000.0
(*/
(task1 (- N 2))
(task1 (- N 1))
1.0 ) ) ) ) ) ) )
(for N (list 3 4 5 6 7 8 20 30 50 100)
(println 'N: N (round (task1 N) 20)) )
# task 2
(setq B (- 2.7182818284590452353602874713526624977572470 1.0))
(for N 25
(setq B
(-
(* N B)
1.0 ) ) )
(prinl "bank balance after 25 years: " (round B 20))
# task 3
(de pow (A B) # fixedpoint
(*/ 1.0 (** A B) (** 1.0 B)) )
(de task3 (A B)
(let
(A2 (pow A 2)
B2 (pow B 2)
B4 (pow B 4)
B6 (pow B 6)
B8 (pow B 8) )
(+
(*/ 333.75 B6 1.0)
(*/
A2
(-
(*/ 11.0 A2 B2 (** 1.0 2))
B6
(* 121 B4)
2.0 )
1.0 )
(*/ 5.5 B8 1.0)
(*/ 1.0 A (*/ 2.0 B 1.0)) ) ) )
(prinl "Rump's example: " (round (task3 77617.0 33096.0) 20))

View file

@ -0,0 +1,12 @@
from fractions import Fraction
def muller_seq(n:int) -> float:
seq = [Fraction(0), Fraction(2), Fraction(-4)]
for i in range(3, n+1):
next_value = (111 - 1130/seq[i-1]
+ 3000/(seq[i-1]*seq[i-2]))
seq.append(next_value)
return float(seq[n])
for n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]:
print("{:4d} -> {}".format(n, muller_seq(n)))

View file

@ -0,0 +1,16 @@
from decimal import Decimal, getcontext
def bank(years:int) -> float:
"""
Warning: still will diverge and return incorrect results after 250 years
the higher the precision, the more years will cover
"""
getcontext().prec = 500
# standard math.e has not enough precision
e = Decimal('2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351')
decimal_balance = e - 1
for year in range(1, years+1):
decimal_balance = decimal_balance * year - 1
return(float(decimal_balance))
print("Bank balance after 25 years = ", bank(25))

View file

@ -0,0 +1,2 @@
for year in range(200, 256, 5):
print(year, '->', bank(year))

View file

@ -0,0 +1,11 @@
from fractions import Fraction
def rump(generic_a, generic_b) -> float:
a = Fraction('{}'.format(generic_a))
b = Fraction('{}'.format(generic_b))
fractional_result = Fraction('333.75') * b**6 \
+ a**2 * ( 11 * a**2 * b**2 - b**6 - 121 * b**4 - 2 ) \
+ Fraction('5.5') * b**8 + a / (2 * b)
return(float(fractional_result))
print("rump(77617, 33096) = ", rump(77617.0, 33096.0))

View file

@ -0,0 +1,15 @@
/*REXX pgm (pathological FP problem): a sequence that might converge to a wrong limit. */
parse arg digs show . /*obtain optional arguments from the CL*/
if digs=='' | digs=="," then digs= 150 /*Not specified? Then use the default.*/
if show=='' | show=="," then show= 20 /* " " " " " " */
numeric digits digs /*have REXX use "digs" decimal digits. */
#= 2 4 5 6 7 8 9 20 30 50 100 /*the indices to display value of V.n */
fin= word(#, words(#) ) /*find the last (largest) index number.*/
w= length(fin) /* " " length (in dec digs) of FIN.*/
v.1= 2 /*the value of the first V element. */
v.2=-4 /* " " " " second " " */
do n=3 to fin; nm1= n-1; nm2= n-2 /*compute some values of the V elements*/
v.n= 111 - 1130/v.nm1 + 3000/(v.nm1*v.nm2) /* " a value of a " element.*/
/*display digs past the dec. point───┐ */
if wordpos(n, #)\==0 then say 'v.'left(n, w) "=" format(v.n, , show)
end /*n*/ /*stick a fork in it, we're all done. */

View file

@ -0,0 +1,18 @@
/*REXX pgm (pathological FP problem): the chaotic bank society offering a new investment*/
e=2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713,
||8217852516642742746639193200305992181741359662904357290033429526059563073813232862794,
||3490763233829880753195251019011573834187930702154089149934884167509244761460668082264,
||8001684774118537423454424371075390777449920695517027618386062613313845830007520449338
d = length(e) - length(.) /*subtract one for the decimal point. */
parse arg digs show y . /*obtain optional arguments from the CL*/
if digs=='' | digs=="," then digs= d /*Not specified? Then use the default.*/
if show=='' | show=="," then show= 20 /* " " " " " " */
if y=='' | y=="," then y= 25 /* " " " " " " */
numeric digits digs /*have REXX use "digs" decimal digits. */
$= e - 1 /*subtract $1 from e, that's da deposit*/
/* [↑] value of newly opened account. */
do n=1 for y /*compute the value of the account/year*/
$= $*n - 1 /* " " " " " account now.*/
end /*n*/
@@@= 'With ' d " decimal digits, the balance after " y ' years is: '
say @@@ '$'format($, , show) / 1 /*stick a fork in it, we're all done. */

View file

@ -0,0 +1,13 @@
/*REXX pgm (pathological FP problem): the Siegfried Rump's example (problem dated 1988).*/
parse arg digs show . /*obtain optional arguments from the CL*/
if digs=='' | digs=="," then digs=150 /*Not specified? Then use the default.*/
if show=='' | show=="," then show= 20 /* " " " " " " */
numeric digits digs /*have REXX use "digs" decimal digits. */
a= 77617.0 /*initialize A to it's defined value.*/
b= 33096.0 /* " B " " " " */
/*display SHOW digits past the dec. pt.*/
say 'f(a,b)=' format( f(a,b), , show) /*display result from the F function.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
f: procedure; parse arg a,b; return 333.75* b**6 + a**2 * (11* a**2* b**2 - b**6,
- 121*b**4 - 2) + 5.5*b**8 + a / (2*b)

View file

@ -0,0 +1,48 @@
#lang racket
(define current-do-exact-calculations? (make-parameter exact->inexact))
(define (x n) (if (current-do-exact-calculations?) n (exact->inexact n)))
(define (decimal.18 n)
(regexp-replace #px"0+$" (real->decimal-string n 18) ""))
(define (task-1 n)
(let ((c_1 (x 111)) (c_2 (x -1130)) (c_3 (x 3000)))
(let loop ((v_n-2 (x 2)) (v_n-1 (x -4)) (n (- n 2)))
(if (= n 0) v_n-1 (loop v_n-1 (+ c_1 (/ c_2 v_n-1) (/ c_3 (* v_n-1 v_n-2))) (- n 1))))))
(define (task-2) ; chaotic bank
(define e (if (current-do-exact-calculations?)
#e2.71828182845904523536028747135266249775724709369995
(exp 1)))
(for/fold ((b (- e 1))) ((y (in-range 1 26))) (- (* b y) 1)))
(define (task-3 a b)
(+ (* (x #e333.75) (expt b 6))
(* (expt a 2) (- (* 11 (expt a 2) (expt b 2)) (expt b 6) (* 121 (expt b 4)) 2))
(* (x #e5.5) (expt b 8))
(/ a (* b 2))))
(define (all-tests)
(let ((classic-sum (+ (x #e0.2) (x #e0.1))))
(printf "Classic example: ~a = ~a~%" classic-sum (decimal.18 classic-sum)))
(displayln "TASK 1")
(for ((n (in-list '(3 4 5 6 7 8 20 30 50 100))))
(printf "n=~a\t~a~%" n (decimal.18 (task-1 n))))
(printf "TASK 2: balance after 25 years = ~a~%" (decimal.18 (task-2)))
(let ((t3 (task-3 77617 33096)))
(printf "TASK 3: f(77617, 33096) = ~a = ~a~%" t3 (decimal.18 t3))))
(module+ main
(displayln "INEXACT (Floating Point) NUMBERS")
(parameterize ([current-do-exact-calculations? #f])
(all-tests))
(newline)
(displayln "EXACT (Rational) NUMBERS")
(parameterize ([current-do-exact-calculations? #t])
(all-tests)))

View file

@ -0,0 +1,15 @@
say '1st: Convergent series';
my @series = 2.FatRat, -4, { 111 - 1130 / $^v + 3000 / ( $^v * $^u ) } ... *;
for flat 3..8, 20, 30, 50, 100 -> $n {say "n = {$n.fmt("%3d")} @series[$n-1]"};
say "\n2nd: Chaotic bank society";
sub postfix:<!> (Int $n) { [*] 2..$n } # factorial operator
my $years = 25;
my $balance = sum map { 1 / FatRat.new($_!) }, 1 .. $years + 15; # Generate e-1 to sufficient precision with a Taylor series
put "Starting balance, \$(e-1): \$$balance";
for 1..$years -> $i { $balance = $i * $balance - 1 }
printf("After year %d, you will have \$%1.16g in your account.\n", $years, $balance);
print "\n3rd: Rump's example: f(77617.0, 33096.0) = ";
sub f (\a, \b) { 333.75*b+ a²*( 11*a²*b² - b- 121*b- 2 ) + 5.5*b+ a/(2*b) }
say f(77617.0, 33096.0).fmt("%0.16g");

View file

@ -0,0 +1,12 @@
# Project : Pathological floating point problems
decimals(8)
v = list(100)
v[1] = 2
v[2] = -4
for n = 3 to 100
v[n] = (111 - 1130 / v[n-1]) + 3000 / (v[n-1] * v[n-2])
if n < 9 or n = 20 or n = 30 or n = 50 or n = 100
see "n = " + n + " " + v[n] + nl
ok
next

View file

@ -0,0 +1,6 @@
ar = [0, 2, -4]
100.times{ar << (111 - 1130.quo(ar[-1])+ 3000.quo(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

View file

@ -0,0 +1,4 @@
require 'bigdecimal/math'
balance = BigMath.E(50) - 1
1.upto(25){|y| balance = balance * y - 1}
puts "Bank balance after 25 years = #{balance.to_f}"

View file

@ -0,0 +1,6 @@
def rump(a,b)
a, b = a.to_r, b.to_r
333.75r * b**6 + a**2 * ( 11 * a**2 * b**2 - b**6 - 121 * b**4 - 2 ) + 5.5r * b**8 + a / (2 * b)
end
puts "rump(77617, 33096) = #{rump(77617, 33096).to_f}"

View file

@ -0,0 +1,9 @@
func series (n) {
var (u, v) = (2, -4)
(n-2).times { (u, v) = (v, 111 - 1130/v + 3000/(v * u)) }
return v
}
[(3..8)..., 20, 30, 50, 100].each {|n|
printf("n = %3d -> %s\n", n, series(n))
}

View file

@ -0,0 +1,5 @@
var years = 25
var balance = (1 .. years+15 -> sum_by {|n| 1 / n! })
say "Starting balance, $(e-1): $#{balance}"
for i in (1..years) { balance = (i*balance - 1) }
printf("After year %d, you will have $%1.16g in your account.\n", years, balance)

View file

@ -0,0 +1,6 @@
func f (a, b) {
(333.75 * b**6) + (a**2 * ((11 * a**2 * b**2) -
b**6 - (121 * b**4) - 2)) + (5.5 * b**8) + a/(2*b)
}
say f(77617.0, 33096.0)

View file

@ -0,0 +1,9 @@
clear
set obs 100
gen n=_n
gen v=.
replace v=2 in 1
replace v=-4 in 2
replace v=111-1130/v[_n-1]+3000/(v[_n-1]*v[_n-2]) in 3/l
format %20.16f v
list if inlist(n,3,4,5,6,7,8,20,30,50,100), noobs

View file

@ -0,0 +1,6 @@
clear
set obs 26
gen year=_n-1
gen balance=exp(1)-1 in 1
replace balance=year*balance[_n-1]-1 in 2/l
list balance if year==25, noobs

View file

@ -0,0 +1,6 @@
clear
set obs 26
gen year=_n-1
gen balance=1.71828182845904523 in 1
replace balance=year*balance[_n-1]-1 in 2/l
list balance if year==25, noobs

View file

@ -0,0 +1,2 @@
di %21x exp(1)-1
di %21x 1.71828182845904523

View file

@ -0,0 +1,97 @@
extension Numeric where Self: Strideable {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
protocol PathologicalFloat: SignedNumeric, Strideable, ExpressibleByFloatLiteral {
static var e: Self { get }
static func /(_ lhs: Self, _ rhs: Self) -> Self
}
extension Double: PathologicalFloat {
static var e: Double { Double("2.71828182845904523536028747135266249")! }
}
extension Float: PathologicalFloat {
static var e: Float { Float("2.7182818284590")! }
}
extension Decimal: PathologicalFloat {
static var e: Decimal { Decimal(string: "2.71828182845904523536028747135266249")! }
}
extension BDouble: PathologicalFloat {
static var e: BDouble { BDouble("2.71828182845904523536028747135266249")! }
public func advanced(by n: BDouble) -> BDouble { self + n }
public func distance(to other: BDouble) -> BDouble { abs(self - other) }
}
func badSequence<T: PathologicalFloat>(n: Int) -> T {
guard n != 1 else { return 2 }
guard n != 2 else { return -4 }
var a: T = 2, b: T = -4
for _ in stride(from: 2, to: n, by: 1) {
(a, b) = (b, 111 - 1130 / b + 3000 / (a * b))
}
return b
}
func chaoticBank<T: PathologicalFloat>(years: T) -> T {
var balance = T.e - 1
for year: T in stride(from: 1, through: 25, by: 1) {
balance = (balance * year) - 1
}
return balance
}
func rumpFunction<T: PathologicalFloat>(_ a: T, _ b: T) -> T {
let aSquared = a.power(2)
let bSix = b.power(6)
let f1 = 333.75 * bSix
let f2 = aSquared * (11 * aSquared * b.power(2) - bSix - 121 * b.power(4) - 2)
let f3 = 5.5 * b.power(8) + a / (2 * b)
return f1 + f2 + f3
}
func fmt<T: CVarArg>(_ n: T) -> String { String(format: "%16.16f", n) }
print("Bad sequence")
for i in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] {
let vFloat: Float = badSequence(n: i)
let vDouble: Double = badSequence(n: i)
let vDecimal: Decimal = badSequence(n: i)
let vBigDouble: BDouble = badSequence(n: i)
print("v(\(i)) as Float \(fmt(vFloat)); as Double = \(fmt(vDouble)); as Decimal = \(vDecimal); as BDouble = \(vBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false))")
}
let bankFloat: Float = chaoticBank(years: 25)
let bankDouble: Double = chaoticBank(years: 25)
let bankDecimal: Decimal = chaoticBank(years: 25)
let bankBigDouble: BDouble = chaoticBank(years: 25)
print("\nChaotic bank")
print("After 25 years your bank will be \(bankFloat) if stored as a Float")
print("After 25 years your bank will be \(bankDouble) if stored as a Double")
print("After 25 years your bank will be \(bankDecimal) if stored as a Decimal")
print("After 25 years your bank will be \(bankBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false)) if stored as a BigDouble")
let rumpFloat: Float = rumpFunction(77617.0, 33096.0)
let rumpDouble: Double = rumpFunction(77617.0, 33096.0)
let rumpDecimal: Decimal = rumpFunction(77617.0, 33096.0)
let rumpBigDouble: BDouble = rumpFunction(77617.0, 33096.0)
print("\nRump's function")
print("rump(77617.0, 33096.0) as Float \(rumpFloat); as Double = \(rumpDouble); as Decimal = \(rumpDecimal); as BDouble = \(rumpBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false))")

View file

@ -0,0 +1,3 @@
nMin=1
u(n)=111-1130/u(n-1) + 3000/(u(n-1)*u(n-2))
u(nMin)={-4;2}

View file

@ -0,0 +1,54 @@
Imports System.Globalization
Imports System.Numerics
Imports Numerics
#Const USE_BIGRATIONAL = True
#Const BANDED_ROWS = True
#Const INCREASED_LIMITS = True
#If Not USE_BIGRATIONAL Then
' Mock structure to make test code work.
Structure BigRational
Overrides Function ToString() As String
Return "NOT USING BIGRATIONAL"
End Function
Shared Narrowing Operator CType(value As BigRational) As Decimal
Return -1
End Operator
End Structure
#End If
Module Common
Public Const FMT_STR = "{0,4} {1,-15:G9} {2,-24:G17} {3,-32} {4,-32}"
Public ReadOnly Property Headings As String =
String.Format(CultureInfo.InvariantCulture,
FMT_STR,
{"N", "Single", "Double", "Decimal", "BigRational (rounded as decimal)"})
<Conditional("BANDED_ROWS")>
Sub SetConsoleFormat(n As Integer)
If n Mod 2 = 0 Then
Console.BackgroundColor = ConsoleColor.Black
Console.ForegroundColor = ConsoleColor.White
Else
Console.BackgroundColor = ConsoleColor.White
Console.ForegroundColor = ConsoleColor.Black
End If
End Sub
Function FormatOutput(n As Integer, x As (sn As Single, db As Double, dm As Decimal, br As BigRational)) As String
SetConsoleFormat(n)
Return String.Format(CultureInfo.CurrentCulture, FMT_STR, n, x.sn, x.db, x.dm, CDec(x.br))
End Function
Sub Main()
WrongConvergence()
Console.WriteLine()
ChaoticBankSociety()
Console.WriteLine()
SiegfriedRump()
SetConsoleFormat(0)
End Sub
End Module

View file

@ -0,0 +1,107 @@
Module Task1
Iterator Function SequenceSingle() As IEnumerable(Of Single)
' n, n-1, and n-2
Dim vn, vn_1, vn_2 As Single
vn_2 = 2
vn_1 = -4
Do
Yield vn_2
vn = 111 - (1130 / vn_1) + (3000 / (vn_1 * vn_2))
vn_2 = vn_1
vn_1 = vn
Loop
End Function
Iterator Function SequenceDouble() As IEnumerable(Of Double)
' n, n-1, and n-2
Dim vn, vn_1, vn_2 As Double
vn_2 = 2
vn_1 = -4
Do
Yield vn_2
vn = 111 - (1130 / vn_1) + (3000 / (vn_1 * vn_2))
vn_2 = vn_1
vn_1 = vn
Loop
End Function
Iterator Function SequenceDecimal() As IEnumerable(Of Decimal)
' n, n-1, and n-2
Dim vn, vn_1, vn_2 As Decimal
vn_2 = 2
vn_1 = -4
' Use constants to avoid calling the Decimal constructor in the loop.
Const i11 As Decimal = 111
Const i130 As Decimal = 1130
Const E000 As Decimal = 3000
Do
Yield vn_2
vn = i11 - (i130 / vn_1) + (E000 / (vn_1 * vn_2))
vn_2 = vn_1
vn_1 = vn
Loop
End Function
#If USE_BIGRATIONAL Then
Iterator Function SequenceRational() As IEnumerable(Of BigRational)
' n, n-1, and n-2
Dim vn, vn_1, vn_2 As BigRational
vn_2 = 2
vn_1 = -4
' Same reasoning as for Decimal.
Dim i11 As BigRational = 111
Dim i130 As BigRational = 1130
Dim E000 As BigRational = 3000
Do
Yield vn_2
vn = i11 - (i130 / vn_1) + (E000 / (vn_1 * vn_2))
vn_2 = vn_1
vn_1 = vn
Loop
End Function
#Else
Iterator Function SequenceRational() As IEnumerable(Of BigRational)
Do
Yield Nothing
Loop
End Function
#End If
<Conditional("INCREASED_LIMITS")>
Sub IncreaseMaxN(ByRef arr As Integer())
ReDim Preserve arr(arr.Length)
arr(arr.Length - 1) = 1000
End Sub
Sub WrongConvergence()
Console.WriteLine("Wrong Convergence Sequence:")
Dim displayedIndices As Integer() = {3, 4, 5, 6, 7, 8, 20, 30, 50, 100}
IncreaseMaxN(displayedIndices)
Dim indicesSet As New HashSet(Of Integer)(displayedIndices)
Console.WriteLine(Headings)
Dim n As Integer = 1
' Enumerate the implementations in parallel as tuples.
For Each x In SequenceSingle().
Zip(SequenceDouble(), Function(sn, db) (sn, db)).
Zip(SequenceDecimal(), Function(a, dm) (a.sn, a.db, dm)).
Zip(SequenceRational(), Function(a, br) (a.sn, a.db, a.dm, br))
If n > displayedIndices.Max() Then Exit For
If indicesSet.Contains(n) Then
Console.WriteLine(FormatOutput(n, x))
End If
n += 1
Next
End Sub
End Module

View file

@ -0,0 +1,103 @@
Module Task2
Iterator Function ChaoticBankSocietySingle() As IEnumerable(Of Single)
Dim balance As Single = Math.E - 1
Dim year As Integer = 1
Do
balance = (balance * year) - 1
Yield balance
year += 1
Loop
End Function
Iterator Function ChaoticBankSocietyDouble() As IEnumerable(Of Double)
Dim balance As Double = Math.E - 1
Dim year As Integer = 1
Do
balance = (balance * year) - 1
Yield balance
year += 1
Loop
End Function
Iterator Function ChaoticBankSocietyDecimal() As IEnumerable(Of Decimal)
' 27! is the largest factorial decimal can represent.
Dim balance As Decimal = CalculateEDecimal(27) - Decimal.One
Dim year As Integer = 1
Do
balance = (balance * year) - Decimal.One
Yield balance
year += 1
Loop
End Function
#If USE_BIGRATIONAL Then
Iterator Function ChaoticBankSocietyRational() As IEnumerable(Of BigRational)
' 100 iterations is precise enough for 25 years.
Dim balance As BigRational = CalculateEBigRational(100) - BigRational.One
Dim year As Integer = 1
Do
balance = (balance * year) - BigRational.One
Yield balance
year += 1
Loop
End Function
#Else
Iterator Function ChaoticBankSocietyRational() As IEnumerable(Of BigRational)
Do
Yield Nothing
Loop
End Function
#End If
Function CalculateEDecimal(terms As Integer) As Decimal
Dim e As Decimal = 1
Dim fact As Decimal = 1
For i As Integer = 1 To terms
fact *= i
e += Decimal.One / fact
Next
Return e
End Function
#If USE_BIGRATIONAL Then
Function CalculateEBigRational(terms As Integer) As BigRational
Dim e As BigRational = 1
Dim fact As BigInteger = 1
For i As Integer = 1 To terms
fact *= i
e += BigRational.Invert(fact)
Next
Return e
End Function
#End If
<Conditional("INCREASED_LIMITS")>
Sub IncreaseMaxYear(ByRef year As Integer)
year = 40
End Sub
Sub ChaoticBankSociety()
Console.WriteLine("Chaotic Bank Society:")
Console.WriteLine(Headings)
Dim maxYear As Integer = 25
IncreaseMaxYear(maxYear)
Dim i As Integer = 0
For Each x In ChaoticBankSocietySingle().
Zip(ChaoticBankSocietyDouble(), Function(sn, db) (sn, db)).
Zip(ChaoticBankSocietyDecimal(), Function(a, dm) (a.sn, a.db, dm)).
Zip(ChaoticBankSocietyRational(), Function(a, br) (a.sn, a.db, a.dm, br))
If i >= maxYear Then Exit For
Console.WriteLine(FormatOutput(i + 1, x))
i += 1
Next
End Sub
End Module

View file

@ -0,0 +1,109 @@
Module Task3
Function SiegfriedRumpSingle(a As Single, b As Single) As Single
Dim a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
' Non-integral literals must be coerced to Single using the type suffix.
Return 333.75F * b6 +
(a2 * (
11 * a2 * b2 -
b6 -
121 * b4 -
2)) +
5.5F * b4 * b4 +
a / (2 * b)
End Function
Function SiegfriedRumpDouble(a As Double, b As Double) As Double
Dim a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
' Non-integral literals are Doubles by default.
Return 333.75 * b6 +
(a2 * (
11 * a2 * b2 -
b6 -
121 * b4 -
2)) +
5.5 * b4 * b4 +
a / (2 * b)
End Function
Function SiegfriedRumpDecimal(a As Decimal, b As Decimal) As Decimal
Dim a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
' The same applies for Decimal.
Return 333.75D * b6 +
(a2 * (
11 * a2 * b2 -
b6 -
121 * b4 -
2)) +
5.5D * b4 * b4 +
a / (2 * b)
End Function
#If USE_BIGRATIONAL Then
Function SiegfriedRumpRational(a As BigRational, b As BigRational) As BigRational
' Use mixed number constructor to maintain exact precision (333+3/4, 5+1/2).
Dim c1 As New BigRational(333, 3, 4)
Dim c2 As New BigRational(5, 1, 2)
Dim a2 = a * a,
b2 = b * b,
b4 = b2 * b2,
b6 = b4 * b2
Return c1 * b6 +
(a2 * (
11 * a2 * b2 -
b6 -
121 * b4 -
2)) +
c2 * b4 * b4 +
a / (2 * b)
End Function
#Else
Function SiegfriedRumpRational(a As Integer, b As Integer) As BigRational
Return Nothing
End Function
#End If
Sub SiegfriedRump()
Console.WriteLine("Siegfried Rump Formula:")
Dim a As Integer = 77617
Dim b As Integer = 33096
Console.Write("Single: ")
Dim sn As Single = SiegfriedRumpSingle(a, b)
Console.WriteLine("{0:G9}", sn)
Console.WriteLine()
Console.Write("Double: ")
Dim db As Double = SiegfriedRumpDouble(a, b)
Console.WriteLine("{0:G17}", db)
Console.WriteLine()
Console.WriteLine("Decimal:")
Dim dm As Decimal
Try
dm = SiegfriedRumpDecimal(a, b)
Catch ex As OverflowException
Console.WriteLine("Exception: " + ex.Message)
End Try
Console.WriteLine($" {dm}")
Console.WriteLine()
Console.WriteLine("BigRational:")
Dim br As BigRational = SiegfriedRumpRational(a, b)
Console.WriteLine($" Rounded: {CDec(br)}")
Console.WriteLine($" Exact: {br}")
End Sub
End Module

View file

@ -0,0 +1,35 @@
import "/big" for BigRat
import "/fmt" for Fmt
var LIMIT = 100
var bigE = BigRat.fromDecimal("2.71828182845904523536028747135266249775724709369995")
// v(n) sequence task
var c1 = BigRat.new(111)
var c2 = BigRat.new(1130)
var c3 = BigRat.new(3000)
var v1 = BigRat.two
var v2 = BigRat.new(-4)
for (i in 3..LIMIT) {
var v3 = c1 - c2/v2 + c3/(v2*v1)
Fmt.print("$3d : $19s", i, v3.toDecimal(16, true, true))
v1 = v2
v2 = v3
}
// Chaotic Building Society task
var balance = bigE - 1
for (year in 1..25) balance = balance * year - 1
System.print("\nBalance after 25 years is %(balance.toDecimal(16))")
// Siegfried Rump task
var a = BigRat.new(77617)
var b = BigRat.new(33096)
var c4 = BigRat.new(33375, 100)
var c5 = BigRat.new(11)
var c6 = BigRat.new(121)
var c7 = BigRat.new(11, 2)
var f = c4 * b.pow(6) + c7 * b.pow(8) + a/(b*2)
var c8 = c5 * a.pow(2) * b.pow(2) - b.pow(6) - c6 * b.pow(4) - 2
f = f + c8 * a.pow(2)
System.print("\nf(77617.0, 33096.0) is %(f.toDecimal(16))")

View file

@ -0,0 +1,30 @@
func real F(A, B);
real A, B;
return 333.75*Pow(B,6.) +
A*A*(11.*A*A*B*B - Pow(B,6.) - 121.*Pow(B,4.) - 2.) +
5.5*Pow(B,8.) + A/(2.*B);
real V1, V2, V3, Bal;
int N, Year;
[V1:= 2.; V2:= -4.; \task 1
for N:= 3 to 100 do
[V3:= 111. - 1130./V2 + 3000./(V1*V2);
case N of
3,4,5,6,7,8,20,30,50,100:
[Format(3, 0); RlOut(0, float(N));
Format(5, 16); RlOut(0, V3); CrLf(0);
]
other [];
V1:= V2; V2:= V3;
];
CrLf(0); \task 2
Bal:= Exp(1.) - 1.;
for Year:= 1 to 25 do
[Bal:= Bal*float(Year) - 1.;
Format(2, 0); RlOut(0, float(Year));
Format(12, 16); RlOut(0, Bal); CrLf(0);
];
CrLf(0); \task 3
RlOut(0, F(77617., 33096.));
CrLf(0);
]

View file

@ -0,0 +1,3 @@
Series:=Walker(fcn(vs){ // just keep appending new values to a list
vs.append(111.0 - 1130.0/vs[-1] + 3000.0/(vs[-1]*vs[-2])) }.fp(List(2,-4)));
series:=Series.drop(100).value;

View file

@ -0,0 +1,19 @@
var BN=Import("zklBigNum"), ten2n=BN(10).pow(64);
fcn u(n){ // use formula to create a fraction of big ints
const B=-3, Y=4;
N:=BN(6).pow(n+1)*B + BN(5).pow(n+1)*Y;
D:=BN(6).pow(n)*B + BN(5).pow(n)*Y;
tostr(N*ten2n/D,64,32)
}
fcn tostr(bn,m,r){ // convert big int (*10^m) to float string with len r remainder, flakey
str,d:=bn.toString(), str.len()-m;
if(d<0) String(".","0"*-d,str[0,r]);
else String(str[0,d],".",str[d,r]);
}
println("1st: Convergent series");
foreach n in (T(3,4,5,6,7,8,20,30,50,100)){
"n =%3d; %3.20F %s".fmt(n,series[n-1],u(n-1)).println();
}

View file

@ -0,0 +1,7 @@
println("\n2nd: Chaotic banking society");
e:="271828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723069697720931014169283681902551510865746377211125238978442505695369677078544996996794686445490598793163688923009879312";
var en=(e.len()-1), tenEN=BN(10).pow(en);
years,balance:=25, BN(e).sub(tenEN); // in place math
balance=[1..years].reduce(fcn(balance,i){ balance*i - tenEN },balance);
balance=tostr(balance,en,2);
println("After year %d, you will have $%s in your account.".fmt(years,balance));

View file

@ -0,0 +1,8 @@
fcn rump(a,b){ b=BN(b);
b2,b4,b6,b8:=b.pow(2),b.pow(4),b.pow(6),b.pow(8);
a2:=BN(a).pow(2);
r:=( b6*33375 + a2*(a2*b2*11 - b6 - b4*121 - 2)*100 + b8*550 )*ten2n;
r+=BN(a)*ten2n*100/(2*b);
tostr(r,66,32)
}
println("\n3rd: Rump's example: f(77617.0, 33096.0) = ",rump(77617,33096));