WeixiangYan/CodeTransOcean huggingface dataset:
Task: Create an object at a given address




Go: package main

import(
	"fmt"
	"unsafe"
	"reflect"
)

func pointer() {
	fmt.Printf("Pointer:\n")

	
	
	
	
	var i int
	p := &i

	fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)

	*p = 3

	fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}

func slice() {
	fmt.Printf("Slice:\n")

	var a [10]byte

	
	
	
	
	
	var h reflect.SliceHeader
	h.Data = uintptr(unsafe.Pointer(&a)) 
	h.Len = len(a)
	h.Cap = len(a)

	
	s := *(*[]byte)(unsafe.Pointer(&h))

	fmt.Printf("Before:\n\ts: %v\n\ta: %v\n", s, a)

	
	
	copy(s, "A string.")

	fmt.Printf("After:\n\ts: %v\n\ta: %v\n", s, a)
}

func main() {
	pointer()
	fmt.Println()

	slice()
}
Task: Find square difference




Go: package main

import (
    "fmt"
    "math"
)

func squareDiff(k int) int {
    return int(math.Ceil(float64(k+1) * 0.5))
}

func main() {
    fmt.Println(squareDiff(1000))
}
Task: Benford's law




Go: package main

import (
    "fmt"
    "math"
)

func Fib1000() []float64 {
    a, b, r := 0., 1., [1000]float64{}
    for i := range r {
        r[i], a, b = b, b, b+a
    }
    return r[:]
}

func main() {
    show(Fib1000(), "First 1000 Fibonacci numbers")
}

func show(c []float64, title string) {
    var f [9]int
    for _, v := range c {
        f[fmt.Sprintf("%g", v)[0]-'1']++
    }
    fmt.Println(title)
    fmt.Println("Digit  Observed  Predicted")
    for i, n := range f {
        fmt.Printf("  %d  %9.3f  %8.3f\n", i+1, float64(n)/float64(len(c)),
            math.Log10(1+1/float64(i+1)))
    }
}
Task: Additive primes




Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func sumDigits(n int) int {
    sum := 0
    for n > 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}

func main() {
    fmt.Println("Additive primes less than 500:")
    i := 2
    count := 0
    for {
        if isPrime(i) && isPrime(sumDigits(i)) {
            count++
            fmt.Printf("%3d  ", i)
            if count%10 == 0 {
                fmt.Println()
            }
        }
        if i > 2 {
            i += 2
        } else {
            i++
        }
        if i > 499 {
            break
        }
    }
    fmt.Printf("\n\n%d additive primes found.\n", count)
}
Task: Extra primes




Go: package main

import "fmt"

func isPrime(n int) bool {
    if n < 2 {
        return false
    }
    if n%2 == 0 {
        return n == 2
    }
    if n%3 == 0 {
        return n == 3
    }
    d := 5
    for d*d <= n {
        if n%d == 0 {
            return false
        }
        d += 2
        if n%d == 0 {
            return false
        }
        d += 4
    }
    return true
}

func main() {
    digits := [4]int{2, 3, 5, 7}                      
    digits2 := [2]int{3, 7}                           
    cands := [][2]int{{2, 2}, {3, 3}, {5, 5}, {7, 7}} 

    for _, a := range digits {
        for _, b := range digits2 {
            cands = append(cands, [2]int{10*a + b, a + b})
        }
    }

    for _, a := range digits {
        for _, b := range digits {
            for _, c := range digits2 {
                cands = append(cands, [2]int{100*a + 10*b + c, a + b + c})
            }
        }
    }

    for _, a := range digits {
        for _, b := range digits {
            for _, c := range digits {
                for _, d := range digits2 {
                    cands = append(cands, [2]int{1000*a + 100*b + 10*c + d, a + b + c + d})
                }
            }
        }
    }

    fmt.Println("The extra primes under 10,000 are:")
    count := 0
    for _, cand := range cands {
        if isPrime(cand[0]) && isPrime(cand[1]) {
            count++
            fmt.Printf("%2d: %4d\n", count, cand[0])
        }
    }
}
Task: Start from a main routine




Go: package main

import "fmt"

var count = 0

func foo() {
    fmt.Println("foo called")
}

func init() {
    fmt.Println("first init called")
    foo()
}

func init() {
    fmt.Println("second init called")
    main()
}

func main() {
    count++
    fmt.Println("main called when count is", count)
}
Task: Largest proper divisor of n




Go: package main

import "fmt"

func largestProperDivisor(n int) int {
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            return n / i
        }
    }
    return 1
}

func main() {
    fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
    fmt.Print(" 1  ")
    for n := 2; n <= 100; n++ {
        if n%2 == 0 {
            fmt.Printf("%2d  ", n/2)
        } else {
            fmt.Printf("%2d  ", largestProperDivisor(n))
        }
        if n%10 == 0 {
            fmt.Println()
        }
    }
}
Task: Pseudo-random numbers_Combined recursive generator MRG32k3a




Go: package main

import (
    "fmt"
    "log"
    "math"
)

var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}

const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1


func mod(x, y int64) int64 {
    m := x % y
    if m < 0 {
        if y < 0 {
            return m - y
        } else {
            return m + y
        }
    }
    return m
}

type MRG32k3a struct{ x1, x2 [3]int64 }

func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }

func (mrg *MRG32k3a) seed(seedState int64) {
    if seedState <= 0 || seedState >= d {
        log.Fatalf("Argument must be in the range [0, %d].\n", d)
    }
    mrg.x1 = [3]int64{seedState, 0, 0}
    mrg.x2 = [3]int64{seedState, 0, 0}
}

func (mrg *MRG32k3a) nextInt() int64 {
    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} 
    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} 
    return mod(x1i-x2i, m1) + 1
}

func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }

func main() {
    randomGen := MRG32k3aNew()
    randomGen.seed(1234567)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}
Task: Abbreviations, simple








VB: Private Function ValidateUserWords(userstring As String) As String
    Dim s As String
    Dim user_words() As String
    Dim command_table As Scripting.Dictionary
    Set command_table = New Scripting.Dictionary
    Dim abbreviations As Scripting.Dictionary
    Set abbreviations = New Scripting.Dictionary
    abbreviations.CompareMode = TextCompare
    Dim commandtable() As String
    Dim commands As String
    s = s & "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 "
    s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate "
    s = s & "3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
    s = s & "forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load "
    s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 "
    s = s & "msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 "
    s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
    s = s & "2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 "
    commandtable = Split(s, " ")
    Dim i As Integer, word As Variant, number As Integer
    For i = LBound(commandtable) To UBound(commandtable)
        word = commandtable(i)
        If Len(word) > 0 Then
            i = i + 1
            Do While Len(commandtable(i)) = 0: i = i + 1: Loop
            number = Val(commandtable(i))
            If number > 0 Then
                command_table.Add Key:=word, Item:=number
            Else
                command_table.Add Key:=word, Item:=Len(word)
                i = i - 1
            End If
        End If
    Next i
    For Each word In command_table
        For i = command_table(word) To Len(word)
            On Error Resume Next
            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
        Next i
    Next word
    user_words() = Split(userstring, " ")
    For Each word In user_words
        If Len(word) > 0 Then
            If abbreviations.exists(word) Then
                commands = commands & abbreviations(word) & " "
            Else
                commands = commands & "*error* "
            End If
        End If
    Next word
    ValidateUserWords = commands
End Function
Public Sub program()
    Dim guserstring As String
    guserstring = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    Debug.Print "user words:", guserstring
    Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
Task: Pseudo-random numbers_Middle-square method








VB: global semilla
semilla = 675248
for i = 1 to 5
	print i; ": "; Random()
next i
end

function Random()
	semilla = floor((semilla*semilla/1e3) mod 1e6)
	return int(semilla)
end function
Task: Draw a pixel








VB: Sub draw()
    Dim sh As Shape, sl As Shape
    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)
    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)
    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)
End Sub
Task: Ray-casting algorithm








VB: Imports System.Math

Module RayCasting

    Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}
    Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}
    Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}
    Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}
    Private shapes As Integer()()() = {square, squareHole, strange, hexagon}

    Public Sub Main()
        Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}

        For Each shape As Integer()() In shapes
            For Each point As Double() In testPoints
                Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7)))
            Next
            Console.WriteLine()
        Next
    End Sub

    Private Function Contains(shape As Integer()(), point As Double()) As Boolean

        Dim inside As Boolean = False
        Dim length As Integer = shape.Length

        For i As Integer = 0 To length - 1
            If Intersects(shape(i), shape((i + 1) Mod length), point) Then
                inside = Not inside
            End If
        Next

        Return inside
    End Function

    Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean

        If a(1) > b(1) Then Return Intersects(b, a, p)
        If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001
        If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False
        If p(0) < Min(a(0), b(0)) Then Return True
        Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))
        Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))

        Return red >= blue
    End Function
End Module
Task: Air mass




Go: package main

import (
    "fmt"
    "math"
)

const (
    RE  = 6371000 
    DD  = 0.001   
    FIN = 1e7     
)


func rho(a float64) float64 { return math.Exp(-a / 8500) }


func radians(degrees float64) float64 { return degrees * math.Pi / 180 }




func height(a, z, d float64) float64 {
    aa := RE + a
    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))
    return hh - RE
}


func columnDensity(a, z float64) float64 {
    sum := 0.0
    d := 0.0
    for d < FIN {
        delta := math.Max(DD, DD*d) 
        sum += rho(height(a, z, d+0.5*delta)) * delta
        d += delta
    }
    return sum
}

func airmass(a, z float64) float64 {
    return columnDensity(a, z) / columnDensity(a, 0)
}

func main() {
    fmt.Println("Angle     0 m              13700 m")
    fmt.Println("------------------------------------")
    for z := 0; z <= 90; z += 5 {
        fz := float64(z)
        fmt.Printf("%2d      %11.8f      %11.8f\n", z, airmass(0, fz), airmass(13700, fz))
    }
}
Task: FASTA format



C#: using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Program
{
    public class FastaEntry
    {
        public string Name { get; set; }
        public StringBuilder Sequence { get; set; }
    }

    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
    {
        FastaEntry f = null;
        string line;
        while ((line = fastaFile.ReadLine()) != null)
        {
            
            if (line.StartsWith(";"))
                continue;

            if (line.StartsWith(">"))
            {
                if (f != null)
                    yield return f;
                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
            }
            else if (f != null)
                f.Sequence.Append(line);
        }
        yield return f;
    }

    static void Main(string[] args)
    {
        try
        {
            using (var fastaFile = new StreamReader("fasta.txt"))
            {
                foreach (FastaEntry f in ParseFasta(fastaFile))
                    Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e);
        }
        Console.ReadLine();
    }
}









Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure Simple_FASTA is
   
   Current: Character;
   
begin 
   Get(Current); 
   if Current /= '>' then
      raise Constraint_Error with "'>' expected";
   end if;
   while not End_Of_File loop 
      Put(Get_Line & ": "); 
      Read_String:
      loop
	 exit Read_String when End_Of_File; 
	 Get(Current);
	 if Current = '>' then 
	    New_Line; 
	    exit Read_String;
	 else
	    Put(Current & Get_Line); 
	    
	 end if;
      end loop Read_String;
   end loop;

end Simple_FASTA;
Task: MAC vendor lookup



C#: using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task<string> LookupMac(string MacAddress)
    {
        var uri = new Uri("http:
        using (var wc = new HttpClient())
            return await wc.GetStringAsync(uri);
    }
    static void Main(string[] args)
    {
        foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" })
            Console.WriteLine(mac + "\t" + LookupMac(mac).Result);
        Console.ReadLine();
    }
}









Ada: with Ada.Text_IO;

with AWS.Client;
with AWS.Response;
with AWS.Messages;

procedure MAC_Vendor is

   procedure Lookup (MAC : in String) is
      use AWS.Response;
      use AWS.Messages;
      URL     : constant String := "http://api.macvendors.com/" & MAC;
      Page    : constant Data   := AWS.Client.Get (URL);
      use Ada.Text_IO;
   begin
      Put (MAC);
      Set_Col (20);
      case AWS.Response.Status_Code (Page) is
         when S200   => Put_Line (Message_Body (Page));
         when S404   => Put_Line ("N/A");
         when others => Put_Line ("Error");
      end case;
   end Lookup;

begin
   
   Lookup ("88:53:2E:67:07:BE");   delay 1.500;
   Lookup ("D4:F4:6F:C9:EF:8D");   delay 1.500;
   Lookup ("FC:FB:FB:01:FA:21");   delay 1.500;
   Lookup ("4c:72:b9:56:fe:bc");   delay 1.500;
   Lookup ("00-14-22-01-23-45");   delay 1.500;
   Lookup ("23-45-67");            delay 1.500;
   Lookup ("foobar");
end MAC_Vendor;
Task: Magic 8-ball



C#: using System;

namespace newProg
{

    class Program
    {
        static void Main(string[] args)
        {
            string[] answers =
            {
                "It is certain.",
                "It is decidedly so.",
                "Without a doubt.",
                "Yes – definitely.",
                "You may rely on it.",
                "As I see it, yes.",
                "Most likely.",
                "Outlook good.",
                "Yes.",
                "Signs point to yes.",
                "Reply hazy, try again.",
                "Ask again later",
                "Better not tell you now.",
                "Cannot predict now.",
                "Concentrate and ask again.",
                "Don't count on it.",
                "My reply is no.",
                "My sources say no.",
                "Outlook not so good.",
                "Very doubtful."
            };

            while (true)
            {
                Random rnd = new Random();
                int result = rnd.Next(0, 19);

                Console.WriteLine("Magic 8 Ball! Ask question and hit a key for the answer!");

                string inp = Console.ReadLine();
                
                Console.WriteLine(answers[result]);

            }
        }
    }
}









Ada: with Ada.Text_IO;  use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Numerics.Discrete_Random;


procedure Main is


   
   
   type Possible_Answers_Type is (It_Is_Certain, It_Is_Decidedly_So, Without_A_Doubt,
				  Yes_Definitely, You_May_Rely_On_It, As_I_See_It, Yes_Most_Likely,
				  Outlook_Good, Signs_Point_To_Yes, Yes_Reply_Hazy,
				  Try_Again, Ask_Again_Later, Better_Not_Tell_You_Now,
				  Cannot_Predict_Now, Concentrate_And_Ask_Again,
				  Dont_Bet_On_It, My_Reply_Is_No, My_Sources_Say_No,
				  Outlook_Not_So_Good, Very_Doubtful);
   


   
   Answer           : Possible_Answers_Type := Possible_Answers_Type'First;
   User_Question : String := " ";

   


   
   
   package Random_Answer is new Ada.Numerics.Discrete_Random (Possible_Answers_Type);
   use Random_Answer;
   G : Generator;

begin

   Reset (G); 

   
   Put_Line ("Welcome."); New_Line;

   Put_Line ("WARNING!!!  Please remember that there's no need to shake your device for this program to work, and shaking your device could damage it");
   New_Line;

   Put_Line ("What's your question? ");
   Get (Item => User_Question); New_Line;


   
   Answer := (Random (G)); 

   Put (Answer'Image); 

end Main;
Task: Cycle detection



C#: 


using System;

namespace DetectCycles
{
  
  
  
  public class Cycles<T> where T : IEquatable<T>
  {
    
    
    
    
    
    
    
    
    
    
    
    
    
    public static Tuple<int,int> FindCycle(T x0, Func<T,T> yielder)
    {
      int power, lambda;
      T tortoise, hare;
      power = lambda = 1;
      tortoise = x0;
      hare = yielder(x0);

      
      while (!tortoise.Equals (hare)) {
        if (power == lambda) {
          tortoise = hare;
          power *= 2;
          lambda = 0;  
        }
        hare = yielder (hare);
        lambda += 1;
      }

      
      var mu = 0;
      tortoise = hare = x0;
      for (var times = 0; times < lambda; times++) 
        hare = yielder (hare);
      
      while (!tortoise.Equals (hare)) 
      {
        tortoise = yielder (tortoise);
        hare = yielder (hare);
        mu += 1;
      }

      return new Tuple<int,int> (lambda, mu);
    }
  }
}



using System;

namespace DetectCycles
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			
			Func<int,int> sequence = (int _x) => (_x * _x + 1) % 255;

			
			var x = 3;
			Console.Write(x);
			for (var times = 0; times < 40; times++) 
			{
				x = sequence(x);
				Console.Write(String.Format(",{0}", x));
			}
			Console.WriteLine();

			
			var cycle = Cycles<int>.FindCycle(3, sequence);
			var clength = cycle.Item1;
			var cstart = cycle.Item2;
			Console.Write(String.Format("Cycle length = {0}\nStart index = {1}\n", clength, cstart));
		}
	}
}









Ada: generic
   type Element_Type is private;
package Brent is
   type Brent_Function is access function (X : Element_Type) return Element_Type;
   procedure Brent(F : Brent_Function; X0 : Element_Type; Lambda : out Integer; Mu : out Integer);
end Brent;
Task: Input_Output for pairs of numbers



C#: using System;
using static System.Linq.Enumerable;

public class Program
{
    static void Main(string[] args)
    {
	int count = Convert.ToInt32(Console.ReadLine());
	for (int line = 0; line < count; line++) {
            Console.WriteLine(Console.ReadLine().Split(' ').Sum(i => Convert.ToInt32(i)));
	}
    }
}









Ada: with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   count  : Integer;
   First  : Integer;
   Second : Integer;
begin
   Get (count);
   for I in 1 .. count loop
      Get (First);
      Get (Second);
      Put (Item => First + Second, Width => 1);
      New_Line;
   end loop;
end Main;
Task: Kahan summation



C#: using System;

namespace KahanSummation {
    class Program {
        static float KahanSum(params float[] fa) {
            float sum = 0.0f;
            float c = 0.0f;
            foreach (float f in fa) {
                float y = f - c;
                float t = sum + y;
                c = (t - sum) - y;
                sum = t;
            }

            return sum;
        }

        static float Epsilon() {
            float eps = 1.0f;
            while (1.0f + eps != 1.0f) eps /= 2.0f;
            return eps;
        }

        static void Main(string[] args) {
            float a = 1.0f;
            float b = Epsilon();
            float c = -b;
            Console.WriteLine("Epsilon      = {0}", b);
            Console.WriteLine("(a + b) + c  = {0}", (a + b) + c);
            Console.WriteLine("Kahan sum    = {0}", KahanSum(a, b, c));
        }
    }
}









Ada: with Ada.Text_Io; use Ada.Text_Io;

procedure Kahan is

   type Kahan_Summer is
      record
         Sum  : Float := 0.0;
         C    : Float := 0.0;
      end record;

   procedure Add (Acc : in out Kahan_Summer; Right : Float) is
      Y : constant Float := Right - Acc.C;
      T : constant Float := Acc.Sum + Y;
   begin
      Acc.C   := (T - Acc.Sum) - Y;
      acc.Sum := T;
   end Add;

   function Sum (Acc : Kahan_Summer) return Float
   is (Acc.Sum);

   function Epsilon return Float is
      E : Float := 1.000;
   begin
      while 1.0 + E /= 1.0 loop
         E := E / 2.0;
      end loop;
      return E;
   end Epsilon;

   A : constant Float := 1.000;
   B : constant Float := Epsilon;
   C : constant Float := -B;
   D : constant Float := (A + B) + C;
   K : Kahan_Summer;

   package Float_Io is new Ada.Text_Io.Float_Io (Float);
   use Float_Io;
begin
   Add (K, A);
   Add (K, B);
   Add (K, C);

   Default_Exp := 0;
   Default_Aft := 12;
   Put ("Epsilon     : "); Put (B); New_Line;
   Put ("(A + B) - C : "); Put (D); New_Line;
   Put ("Kahan sum   : "); Put (Sum (K)); New_Line;
end Kahan;