Homework7_RA

Do a research about the real world window to viewport transformation.

What is?

Window to Viewport Transformation is the process of transforming a 2D world-coordinate objects to device coordinates. Objects inside the world or clipping window are mapped to the viewport which is the area on the screen where world coordinates are mapped to be displayed.

General Terms:

  • World coordinate – It is the Cartesian coordinate w.r.t which we define the diagram, like Xwmin, Xwmax, Ywmin, Ywmax
  • Device Coordinate –It is the screen coordinate where the objects is to be displayed, like Xvmin, Xvmax, Yvmin, Yvmax
  • Window –It is the area on world coordinate selected for display.
  • ViewPort –It is the area on device coordinate where graphics is to be displayed.

Mathematical Calculation of Window to Viewport:

It may be possible that the size of the Viewport is much smaller or greater than the Window. In these cases, we have to increase or decrease the size of the Window according to the Viewport and for this, we need some mathematical calculations.

(xw, yw): A point on Window
(xv, yv): Corresponding  point on Viewport

Where Sx and Sy are the scaling factor.

Exemple in C#

Manual trasforming.

// C# program to implement 
// Window to ViewPort Transformation 
using System; 

class GFG 
{ 

// Function for window to viewport transformation 
static void WindowtoViewport(int x_w, int y_w, 
							int x_wmax, int y_wmax, 
							int x_wmin, int y_wmin, 
							int x_vmax, int y_vmax, 
							int x_vmin, int y_vmin) 
{ 
	// point on viewport 
	int x_v, y_v; 

	// scaling factors for x coordinate 
	// and y coordinate 
	float sx, sy; 

	// calculatng Sx and Sy 
	sx = (float)(x_vmax - x_vmin) / 
				(x_wmax - x_wmin); 
	sy = (float)(y_vmax - y_vmin) / 
				(y_wmax - y_wmin); 

	// calculating the point on viewport 
	x_v = (int) (x_vmin + 
		(float)((x_w - x_wmin) * sx)); 
	y_v = (int) (y_vmin + 
		(float)((y_w - y_wmin) * sy)); 

	Console.Write("The point on viewport: " + 
				"({0}, {1} )\n ", x_v, y_v); 
} 

// Driver Code 
public static void Main(String[] args) 
{ 

	// boundary values for window 
	int x_wmax = 80, y_wmax = 80, 
		x_wmin = 20, y_wmin = 40; 

	// boundary values for viewport 
	int x_vmax = 60, y_vmax = 60, 
		x_vmin = 30, y_vmin = 40; 

	// point on window 
	int x_w = 30, y_w = 80; 

	WindowtoViewport(30, 80, 80, 80, 20, 
					40, 60, 60, 30, 40); 
} 
} 

// This code is contributed by PrinciRaj1992 

https://www.geeksforgeeks.org/window-to-viewport-transformation-in-computer-graphics-with-implementation/
https://www.javatpoint.com/computer-graphics-window-to-viewport-co-ordinate-transformation

Homework8_RA(To be reviewed)

Do a research with examples about how matrices and homogeneous coordinates can be useful for graphics transformations and charts.

Homogeneous coordinates

In mathematics, homogeneous coordinates are a system of coordinates used in projective geometry, as Cartesian coordinates are used in Euclidean geometry.

They have the advantage that the coordinates of points, including points at infinity, can be represented using finite coordinates.
Formulas involving homogeneous coordinates are often simpler and more symmetric than their Cartesian counterparts.
Homogeneous coordinates have a range of applications, including computer graphics and 3D computer vision, where they allow affine transformations and, in general, projective transformations to be easily represented by a matrix.

  • Any point in the projective plane is represented by a triple (X, Y, Z), called the homogeneous coordinates or projective coordinates of the point, where X, Y and Z are not all 0.
  • The point represented by a given set of homogeneous coordinates is unchanged if the coordinates are multiplied by a common factor.
  • Conversely, two sets of homogeneous coordinates represent the same point if and only if one is obtained from the other by multiplying all the coordinates by the same non-zero constant.
  • When Z is not 0 the point represented is the point (X/Z, Y/Z) in the Euclidean plane.
  • When Z is 0 the point represented is a point at infinity.

Matrix and trasformation

Using homogeneous coordinates allows to use matrix multiplication to calculate transformations extremely efficient!

Since a 2×2 matrix representation of translation does not exist, by using a homogenous coordinate system, we can represent 2×2 translation transformation as a matrix multiplication.
A point (x, y) can be re-written in homogeneous coordinates as (xw, yw,w).
The homogeneous parameterw is a non-zero value such that x and y coordinates can easily be recovered by dividing the first and second numbers by the third.

Insights into geometry

http://precollegiate.stanford.edu/circle/math/notes06f/homogenous.pdf

https://en.wikipedia.org/wiki/Homogeneous_coordinates
https://uomustansiriyah.edu.iq/media/lectures/9/9_2019_04_24!06_36_54_PM.pdf

Homework6_RA

Do a comprehensive research about the GRAPHICS (GDI+ library) object and all its members.

Gaphics(GDI+ library)

Windows provides a variety of drawing tools to use in device contexts. It provides pens to draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object classes equivalent to the drawing tools in Windows. The table below shows the available classes and the equivalent Windows graphics device interface (GDI) handle types.

GDI+ is a wrapper-library for traditional GDI. Conventional wisdom dictates that whenever a wrapper class calls another class, it must be slower than just the native class on its own. This is true with GDI+ as well. However, GDI+ performs exceptionally well and is often comparable to GDI itself. In fact, some operations such as filling complex shapes with a gradient is faster in GDI+ than in traditional GDI. This is possible because GDI+ internally uses calls that GDI does not expose, requiring many extra steps to get the same result.

Each graphic-object class in the class library has a constructor that allows you to create graphic objects of that class, which you must then initialize with the appropriate create function.

The System.Drawing namespace contains all GDI+ functionality (as well as a few sub-namespaces). GDI+ provides all the basic drawing features, such as drawing lines, curves, circles, ellipses, strings, bitmaps, and more. GDI+ also gives developers the ability to fill areas with colors, patterns, and textures.

Graphics object has a large number of methods that encapsulate drawing operations on a drawing “canvas.”

GDI+ Class and Interfaces in .NET

In Microsoft .NET library, all classes (types) are grouped in namespaces. A namespace is nothing but a category of similar kind of classes.

GDI+ is defined in the Drawing namespace and its five sub namespaces:

  • System.Drawing Namespace
  • System.Drawing.Design Namespace
  • System.Drawing.Drawing2D Namespace
  • System.Drawing.Imaging Namespace
  • System.Drawing.Printing Namespace
  • System.Drawing.Text Namespace

https://docs.microsoft.com/en-us/cpp/mfc/graphic-objects?view=vs-2019
https://www.codemag.com/article/0305031
https://www.codeproject.com/Articles/4659/Introduction-to-GDI-in-NET

Homework5_RA

Do a research about Reflection and the type Type and make all examples that you deem to be useful.

Reflection

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies, modules and types.

… example in C#

By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime. The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. When writing a C# code that uses reflection, the coder can use the typeof operator to get the object’s type or use the getType() method to get the type of the current instance.

  • typeof only works on types, not on variables, is static and does its work at compile time instead of runtime.
  • getType() get the type at execution time
If you need information about a non-instantiated type, you may use the globally available typeof() method
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = "test";
            Console.WriteLine(test.GetType().FullName);//System.String
            Console.WriteLine(typeof(Int32).FullName);//System.Int32
            Console.ReadKey();
        }
    }
}
// TypePropertiesDemo.cs 
using System; 
using System.Text; 
using System.Reflection; 

namespace Reflection 
{ 
    class TypePropertiesDemo 
    { 
        static void Main() 
        { 
            // modify this line to retrieve details of any other data type 
            // Get name of type 
            Type t = typeof(Car); 
            GetTypeProperties(t); 
            Console.ReadLine(); 
        } 
        public static void GetTypeProperties(Type t) 
        { 
            StringBuilder OutputText = new StringBuilder(); 

            //properties retrieve the strings 
            OutputText.AppendLine("Analysis of type " + t.Name); 
            OutputText.AppendLine("Type Name: " + t.Name); 
            OutputText.AppendLine("Full Name: " + t.FullName); 
            OutputText.AppendLine("Namespace: " + t.Namespace); 

            //properties retrieve references        
            Type tBase = t.BaseType; 

            if (tBase != null) 
            { 
                OutputText.AppendLine("Base Type: " + tBase.Name); 
            } 

            Type tUnderlyingSystem = t.UnderlyingSystemType; 

            if (tUnderlyingSystem != null) 
            { 
                OutputText.AppendLine("UnderlyingSystem Type: " +
                    tUnderlyingSystem.Name); 
                //OutputText.AppendLine("UnderlyingSystem Type Assembly: " +
                //    tUnderlyingSystem.Assembly); 
            } 

            //properties retrieve boolean         
            OutputText.AppendLine("Is Abstract Class: " + t.IsAbstract); 
            OutputText.AppendLine("Is an Arry: " + t.IsArray); 
            OutputText.AppendLine("Is a Class: " + t.IsClass); 
            OutputText.AppendLine("Is a COM Object : " + t.IsCOMObject); 

            OutputText.AppendLine("\nPUBLIC MEMBERS:"); 
            MemberInfo[] Members = t.GetMembers(); 

            foreach (MemberInfo NextMember in Members) 
            { 
                OutputText.AppendLine(NextMember.DeclaringType + " " + 
                NextMember.MemberType + "  " + NextMember.Name); 
            } 
            Console.WriteLine(OutputText); 
        } 
    } 
}

Output:

Analysis of type Car 
Type Name: Car 
Full Name: Reflection.Car 
Namespace: Reflection 
Base Type: Object 
UnderlyingSystem Type: Car 
Is Abstract Class: False 
Is an Arry: False 
Is a Class: True 
Is a COM Object : False

… example in VB.Net

Try to instantiate an object from a dll without referencing it

Public Class Form1

Dim bytes() As Byte = System.IO.File.ReadAllBytes("\\path\directory\file.dll")
Dim assmb As System.Reflection.Assembly = System.Reflection.Assembly.Load(bytes)
'Load the assembly(a building block of a reusable common language runtime application) with a Common Object File Format (COFF) image containing a generated assembly. The assembly is loaded into the caller's application domain.

Dim myDllClass As Object = assmb.CreateInstance("myNamespace.myClass")

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim conStr As String = myDllClass.publicConString
    Dim dt As DataTable = myDllClass.MethodReturnsDatatable("select * from Part", conStr)
    DataGridView1.DataSource = dt

End Sub

https://docs.microsoft.com/it-it/dotnet/api/system.type.getfield?view=netcore-3.1
https://www.codeproject.com/Articles/55710/Reflection-in-NET
https://www.codemag.com/Article/0211161/Reflection-Part-1-Discovery-and-Execution
https://stackoverflow.com/questions/30128583/object-instantiation-using-reflection-works-in-vb-net-but-not-c-sharp

Homework4_RA

Find on the internet and document all possible ways you can infer a suitable data type, useful for statistical processing, when you are getting data points as a flow of alphanumeric strings ( https://en.wikipedia.org/wiki/Alphanumericc , https://stackoverflow.com/questions/5311699/get-datatype-from-values-passed-as-string/5325687. Be aware of possible format difference due to language.)

Type Inference

Type inference refers to the automatic detection of the type of an expression in a formal language. Such include programming languages, mathematical type systems but also natural languages in some branches of computer science and linguistic.

Types are a feature present in some strongly statically typed languages.
The majority of them use a simple form of type inference; the Hindley-Milner type system can provide more complete type inference. The ability to infer types automatically makes many programming tasks easier, leaving the programmer free to omit type annotations while still permitting type checking.

If the type of a value is known only at run-time, these languages are dynamically typed. In some languages, the type of an expression is known only at compile time; these languages are statically typed.
In most statically typed languages, the input and output types of functions and local variables ordinarily must be explicitly provided by type annotations. For example, in C:

int add_one(int x) {
    int result; /* declare integer result */

    result = x + 1;
    return result;
}

In a hypothetical language supporting type inference, the code might be written like this instead:

add_one(x) {
    var result;  /* inferred-type variable result */
    var result2; /* inferred-type variable result #2 */

    result = x + 1;
    result2 = x + 1.0;  /* this line won't work (in the proposed language) */
    return result;
}

So

  • Inferred type = set ONCE and at compile time. Actually the inferred part is only a time saver in that you don’t have to type the Typename IF the compiler can figure it out. Type Inference is often used in conjunction static typing (as is the case with swift)
var i = true; //compiler can infer that i most be of type Bool
i = "asdasdad" //invalid because compiler already inferred i is an Bool!
  • Dynamic type = no fixed Type -> type can change at runtime
id i = @YES; //NSNumber
i = @"lalala"; //NSString
i = @[@1] //NSArray

How infer when we have text data

Dim someVar = 5
someVar.GetType.ToString() '--> System.Int32
someVar = "5"
someVar.GetType.ToString() '--> System.String

Of course, there’s no definite way to do this, but something like this may do the trick

TryParse
object ParseString(string str)
{
    int intValue;
    double doubleValue;
    char charValue;
    bool boolValue;

    // Place checks higher if if-else statement to give higher priority to type.
    if (int.TryParse(str, out intValue))
        return intValue;
    else if (double.TryParse(str, out doubleValue))
        return doubleValue;
    else if (char.TryParse(str, out charValue))
        return charValue;
    else if (bool.TryParse(str, out boolValue))
        return boolValue;

    return null;
}
Regex
bool isInt = new Regex(@"^\d+$").IsMatch(str);
bool isDouble = !(isInt) && new Regex(@"^\d+\.\d+$").IsMatch(str);
bool isChar = !(isInt || isDouble) && new Regex(@"^.$").IsMatch(str);
bool isString = !(isInt || isDouble || isChar);

https://en.wikipedia.org/wiki/Type_inference
https://stackoverflow.com/questions/24598761/inferred-type-and-dynamic-typing
https://riptutorial.com/vb-net/example/17983/when-to-use-type-inference
https://stackoverflow.com/questions/606365/c-sharp-doubt-finding-the-datatype/606381#606381

Hindley–Milner type system

https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system

Homework7_A – Homework8_A

Create – in your preferred language C# or VB.NET – a program which is able to read ANY file CSV (or at least 99% of them), assuming no prior knowledge about its structure (do not even assume to that a first line with variable names is necessarily present in the CSV: when not present, clearly, do some useful automatic naming).
Also, some data preprocessing should be carried out on the data (or a suitable subset) in order to empirically establish the most suitable type of data of each field and, thus, give a preliminary tentative choice of data types for the variable fields to the program user (which he can, then, try to change on the GUI at his will before attempting to read the file)

OPT 8_A. In the previous program 7_A, as a verification, plug the code you have already developed for computing the mean and the (univariate) statistical distribution, and allow the user to select any variable and compute the arithmetic mean (only when it makes sense) and the distribution. [Make this general enough, in anticipation of next homework program, where we will also add bivariate distributions and, in general, multivariate distributions, with various charts.]

VB.Net code

Source(Application7_n file folder)

https://drive.google.com/file/d/1vF2iwXClFHLlPakOl7rq1nIPLShcjanC/view?usp=sharing

Solution txt format

https://drive.google.com/file/d/1tw9dYnnNOFm-DER0wALCu-jWjXn5IJYu/view?usp=sharing

A little explaination

Take data with dialog

Imports Microsoft.VisualBasic.FileIO
...
 Private Sub BtnDialog_Click(sender As Object, e As EventArgs) Handles BtnDialog.Click
        Dim o As New OpenFileDialog
        o.ShowDialog()
        If o.FileName IsNot Nothing Then
            Me.TxtFile.Text = o.FileName
        End If

    End Sub
...

Read the data.
First I read the first line

...
Public Sub Read_frist_line()
...

        Using reader As New TextFieldParser(path)

            reader.CommentTokens() = New String() {"#"}
            reader.Delimiters = New String() {","}
            reader.HasFieldsEnclosedInQuotes = True

            Dim values() As String = reader.ReadFields
            Dim i As Integer = 0
            For Each v In values
                TreeView1.Nodes(0).Nodes.Add(v).Tag = i
                dicOfType.Add(i, Choose_type(v.GetType.ToString))
                i += 1
            Next
...

        End Using


    End Sub
...

I store the information building a treeview, so for check about ‘metadata’ I work on it:

...
 Public Function Exist_metadata() As Boolean
        If Me.CheckBox1.Checked Then
            metadataFlag = False
            Return False
        Else
            For tagNode = 0 To TreeView1.Nodes(0).Nodes.Count - 1
                If Different_fromString(tagNode) Then
                    metadataFlag = False
                    Return False
                End If
            Next

        End If
        Return True

    End Function
...

If they don’t exist change the tree.

Csv without first line

For try to understand the right tipe, first of take all data i use

Empirically_type(reader) and Suitable_type()

when I read the first line.

...
    Public Sub Suitable_type()
        Dim nParent As Integer = Me.TreeView1.Nodes(0).Nodes.Count
        For n = 0 To nParent - 1
            Research_typeString(Me.TreeView1.Nodes(0).Nodes(n).Text, n)
        Next

    End Sub
...

With Research_typeString I try to understand information with some tipical name:

Imports System.Text.RegularExpressions
...
Public Sub Research_typeString(txt As String, n As Integer)
        Dim dateMatch As New Regex("(\w*time\w*)|(\w*date\w*)", RegexOptions.IgnoreCase)
        Dim soldMatch As New Regex("(\w*\$\w*)|(\w*\$\w*)", regexOptions.ignoreCase)
        Dim numberMatch As New Regex("(\w*number\w*)", RegexOptions.IgnoreCase)
        Dim unitMatch As New Regex("(\w*kg\w*)| (\w*cm\w*)|(\w*metre\w*)|(\w*height\w*)|(\w*weight\w*|(\w*length\w*)|(\w*width\w*))", RegexOptions.IgnoreCase)

If dateMatch.IsMatch(txt) Then
            Dic_containKey(dicOfSuitType, n)
            dicOfSuitType(n).Add(GetType(DateTime))
        End If
...

End Sub

Instead, with empirically_type, I try to understand reading the second line of file, parsando ogni elemento.

Public Sub Empirically_type(reader As TextFieldParser)

        Dim values() As String = reader.ReadFields()

        For v = 0 To values.Count - 1
            dicOfEmpType.Add(v, ParseString(values(v)).GetType)
        Next

    End Sub

dicoOfEmpType and dicOfSuitableType are used to store the recommended data, and then show it at the user when click on data.

Summing up, I read the first line, try to elaborate the data and only then do I read the other lines of the file, and complete the treeview.

I try also to write extra control for avoid bug or unexpected things.

Some controls

Choose a variables in treeview i try to calculate avg and freq. distribution:

Homework3_RA

Understand how the floating point representation works and describe systematically (possibly using categories) all the possible problems that can happen. Try to classify the various issues and limitations (representation, comparison, rounding, propagation, approximation, loss of significance, cancellation, etc.) and provide simple examples for each of the categories you have identified.

How it works

Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.

Since computer memory is limited, you cannot store numbers with infinite precision, no matter whether you use binary fractions or decimal ones, at some point you have to cut off.

The idea is to compose a number of two main parts:

  • A significand that contains the number’s digits. Negative significands represent negative numbers.
  • An exponent that says where the decimal (or binary) point is placed relative to the beginning of the significand. Negative exponents represent numbers that are very small (i.e. close to zero).

Nearly all hardware and programming languages use floating-point numbers in the same binary formats, which are defined in the IEEE 754 standard. The usual formats are 32 or 64 bits in total length.
So it allows us to represent very large numbers in a compact way, but also very small ones.

Issues

Representation

Representation error refers to the fact that some decimal fractions cannot be represented exactly as binary (base 2) fractions:

// 1/10 and 2/10 are not exactly representable as a binary 
// fraction.
0.1 + 0.2
0.30000000000000004

Rounding

How already said, since floating-point numbers have a limited number of digits, they cannot represent all real numbers accurately: when there are more digits than the format allows, the leftover ones are omitted – the number is rounded.

Cancellation

There are two kinds of cancellation: catastrophic and benign.

Catastrophic cancellation occurs when the operands are subject to rounding errors.
The subtraction of two numbers did not introduce any error, but rather exposed the error introduced in the earlier multiplications.

Benign cancellation occurs when subtracting exactly known quantities. If x and y have no rounding error if the subtraction is done with a guard digit, the difference x-y has a very small relative error.

Guard Digits

One method of computing the difference between two floating-point numbers is to compute the difference exactly and then round it to the nearest floating-point number:

x = 2.15 × 1012
y = .0000000000000000125 × 1012
xy = 2.1499999999999999875 × 1012 which rounds to 2.15 × 1012

But floating-point hardware normally operates on a fixed number of digits(cause is very expensive if the operands differ greatly in size):

x = 2.15 × 1012
y = 0.00 × 1012
xy = 2.15 × 1012

The answer is exactly the same as if the difference had been computed exactly and then rounded.

Observation

Since many floating-point numbers are merely approximations of the exact value this means that for a given approximation f of a real number r there can be infinitely many more real numbers r1, r2, … which map to exactly the same approximation. Those numbers lie in a certain interval.

https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples

This is an important phenomenon cause if you perform calculations on that number—adding, subtracting, multiplying, etc.—you lose precision. Every number is just an approximation, therefore you’re actually performing calculations with intervals.

There is a mathematical technique used to put bounds on rounding errors and measurement errors in mathematical computation:
Interval arithmetic (also known as interval mathematics, interval analysis, or interval computation)

A standard for interval arithmetic, IEEE Std 1788-2015, has been approved in June 2015. Two reference implementations are freely available. These have been developed by members of the standard’s working group: The libieeep1788 library for C++, and the interval package[ for GNU Octave.

Curiosity, real world example

https://en.wikipedia.org/wiki/Round-off_error#Real_world_example:_Patriot_missile_failure_due_to_magnification_of_roundoff_error

https://docs.python.org/2/tutorial/floatingpoint.html
https://floating-point-gui.de/errors/rounding/
https://floating-point-gui.de/formats/fp/
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
https://en.wikipedia.org/wiki/Interval_arithmetic#Application

Homework6_A

Create one or more simple sequences of numbers which clearly show the problem with the “naive” definition formula of the arithmetic mean, and explore possible ways to fix that.
Provide alternative algorithms to minimize problems with the floating point representation with simple demos with actual numbers.

Problems with floating representation

There are only a finite number of different floats and they are discrete but not equidistant.
The spacing between adjacent numbers jumps by a factor of two at every power of two larger than 0.25.
0.25 is the smallest normalised number in this representation (by modulus), and numbers between -0.25 and 0.25 are denormalised.

    'This Is one of the joke of numbers
    'The result of sum is 0.1 
    Public Function create_list() As List(Of Double)
        Dim possibleInput As New List(Of Double)
        possibleInput.Add(1E-350)
        possibleInput.Add(0.1)
        Return possibleInput
    End Function

    'This Is another one of the joke of numbers
    'The sum will be 0.19999
    Public Function create_list() As List(Of Double)
        Dim possibleInput As New List(Of Double)
        possibleInput.Add(10.2)
        possibleInput.Add(10.0)
        Return possibleInput
    End Function

Problems with naive alghoritm

vb.net

Public Class Form1

    Public CurrentArMean As Double = 0

    'not precision in naive method

    Public Function create_list() As List(Of Double)
        Dim possibleInput As New List(Of Double)
        possibleInput.Add(10000000000.0)
        possibleInput.Add(0.1)
        possibleInput.Add(-10000000000.0)
        possibleInput.Add(-0.0001)
        possibleInput.Add(0.1)
        possibleInput.Add(10000)
        Return possibleInput
    End Function

    'ok method also for naive

    'Public Function create_list() As List(Of Double)
    '    Dim possibleInput As New List(Of Double)
    '    possibleInput.Add(10000000000.0)
    '    possibleInput.Add(-10000000000.0)
    '    possibleInput.Add(0.1)
    '    Return possibleInput
    'End Function

    'This Is the joke of float numbers
    'Public Function create_list() As List(Of Double)
    '    Dim possibleInput As New List(Of Double)
    '    possibleInput.Add(10.2)
    '    possibleInput.Add(10.0)
    '    Return possibleInput
    'End Function

    Public Function do_data()
        Dim result As Double() = {
        naive_alg_mean(create_list),
        online_alg_mean(create_list),
        kahan_sum(create_list)
        }
        Return result
    End Function
    Public Sub print_data(result As Double())
        Me.RtxtB1.AppendText("Online Algo result: " & result(1) & Environment.NewLine & Environment.NewLine)
        Me.RtxtB1.AppendText("Kahan Algo result: " & result(2) & Environment.NewLine & Environment.NewLine)
        Me.RtxtB1.AppendText("Naive Algo result: " & result(0) & Environment.NewLine & Environment.NewLine)
    End Sub

    Private Sub BtnCalc_Click(sender As Object, e As EventArgs) Handles BtnCalc.Click

        Me.RtxtB1.Clear()
        Dim result As Double() = do_data()
        print_data(result)

    End Sub

    Private Function naive_alg_mean(Possibleinput As List(Of Double)) As Double
        Dim sum As Double = 0
        For Each i In Possibleinput
            Try
                sum += i
            Catch ex As OverflowException
                Me.RtxtB1.AppendText("Exception in naive method: " & ex.Message & Environment.NewLine)
            End Try
        Next
        Return sum / Possibleinput.Count
    End Function

    Private Function online_alg_mean(Possibleinput As List(Of Double)) As Double
        Dim count = 0
        For Each i In Possibleinput
            count += 1
            CurrentArMean = CurrentArMean + (i - CurrentArMean) / count
        Next
        Return CurrentArMean
    End Function


    Private Function better_alg_mean(Possibleinput As List(Of Double)) As Double
        Dim currentMean As Double = 0
        Dim c As Double = Possibleinput.Min
        For Each i In Possibleinput
            currentMean += i - c
        Next

        Return (currentMean / Possibleinput.Count) + c
    End Function

    Private Function kahan_sum(Possibleinput As List(Of Double)) As Double
        Dim sum As Double = 0
        Dim c As Double = 0
        For Each i In Possibleinput
            Dim y As Double = i - c
            Dim t As Double = sum + y
            c = (t - sum) - y
            sum = t
        Next
        Return sum / Possibleinput.Count
    End Function
End Class

The input in this case create problems in Naive Algoritm because two of the summands were much larger than the other.

Precision is lost most quickly when the magnitude of the two numbers to be added is most different. With summation, one of the operands is always the sum so far, and in general it is much larger than the numbers being added to it. This effect can be minimized by adding the numbers in order from the smallest to the largest.
(If the two numbers have sufficiently different exponents then some least significant digits will have to be discarded.)

Klein algorithm for sum is better of Kahan sum:

With this method, a correction is maintained along with the current running total, effectively increasing the precision. Each term is first corrected for the error that has accumulated so far. Then the new sum is calculated by adding this corrected term to the running total. Finally, a new correction term is calculated as the difference between the change in the sums and the corrected term.

 Public Function Klein_alg_mean(possibleInput As List(Of Double))
        Dim sum As Double = 0.0
        Dim cs As Double = 0.0
        Dim ccs As Double = 0.0
        Dim c As Double = 0.0
        Dim cc As Double = 0.0
        For Each i In possibleInput
            Dim t As Double = sum + i
            If Math.Abs(sum) >= Math.Abs(i) Then
                c = (sum - t) + i
            Else
                c = (i - t) + sum
            End If
            sum = t
            t = cs + c
            If Math.Abs(cs) >= Math.Abs(c) Then
                cc = (cs - t) + c
            Else
                cc = (c - t) + cs
            End If
            cs = t
            ccs = ccs + cc
        Next i
        Return (sum + cs + ccs) / possibleInput.Count
    End Function

There are also other methods for decrease loss of precision:

  1. sort your set
  2. split in groups of elements whose sum wouldn’t overflow – since they are sorted, this is fast and easy
  3. do the sum in each group – and divide by the group size
  4. do the sum of the group’s sum’s (possibly calling this same algorithm recursively) – be aware that if the groups will not be equally sized, you’ll have to weight them by their size

Moreover double can be divided by a power of 2 without loss of precision. So if your only problem if the absolute size of the sum you could try to pre-scale your numbers before summing them.

We can also use this trick:

mean(X) = sum(X[i] - c)  +  c
          -------------
                N

Such that rescale the value, c could be the min value in the input list.

https://www.volkerschatz.com/science/float.html
https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
https://www.drdobbs.com/floating-point-summation/184403224
https://www.xspdf.com/help/50835306.html

https://www.soa.org/news-and-publications/newsletters/compact/2014/may/com-2014-iss51/losing-my-precision-tips-for-handling-tricky-floating-point-arithmetic/

Homework4_A

Create – in both languages C# and VB.NET – a demonstrative program which computes the online arithmetic mean (if it’s a numeric variable) and the distribution for a discrete variable (can use values simulated with RANDOM object).

How i worked

In this application i used a class for store Dogs information, such as weight and breed.
I use Random method for data (i also searched for a database to capture the data, but i didnt’t find it).
I didn’t use a second class to represent the Frequency Distribution but i used a list to store the new dog instances and i used the override method for demostration purpose.

I tried to modulate the code and make it generic, so as to have it more robust and readable. Also for this reason the class has been put in a separate file.

   Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
 
        Dim Dog As Dog = new_dataset()
        ListOfDog.Add(Dog)
        print_Database(Dog)
        online_mean(Dog)
        print_OnArMean()
        discrete_distribution(DicOfBreed, Dog.Breed)
        discrete_distribution(DicOfAgeDistributio, Dog.Age)
    End Sub

Vb.Net

Form1.vb

Public Class Form1
    Public R As New Random

    'List for store the dog
    Public ListOfDog As New List(Of Dog)

    'Array of breed
    Public PossibleBreed() As String = {"German Shepherd", "Alaskan Malamute", "Beauceron", "Bernese Mountain Dog",
                                        "Black Russian Terrier", "Weimaraner", "Pointer", "Rottweiler", "Siberian Husky",
                                        "Afghan Hound", "Boxer", "Collie", "Weimaraner", "Dalmatian", "Golden Retriver",
                                        "Irish Setter", "Labrador Retriver"}

    Public Count As Integer
    Public CurrentArMean As Double

    'Dictionary for Frequence Distribution of the breed(Breed,count)
    Public DicOfBreed As New Dictionary(Of String, Integer)
    'Dictionary for Frequence Distribution of the age(Age,count)
    Public DicOfAgeDistributio As New Dictionary(Of Integer, Integer)


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        inizialized()
    End Sub
    Public Sub inizialized()
        Count = 0
        CurrentArMean = 0
        DicOfBreed.Clear()
        DicOfAgeDistributio.Clear()
        ListOfDog.Clear()
        Me.RTxTDatabase.Text = ("Breed:".PadRight(25) & "Weight:".PadRight(10) & "Age:" & Environment.NewLine & Environment.NewLine)
        Me.RTxtArOnMean.Text = ("Mean: " & Environment.NewLine & Environment.NewLine)
        Me.RTxtBreedDistribution.Text = "Distribution: " & Environment.NewLine & Environment.NewLine
    End Sub




    Public Sub online_mean(CollForMean As Dog)
        'Online algo for mean
        Count += 1
        CurrentArMean = CurrentArMean + (CollForMean.Age - CurrentArMean) / Count

    End Sub
    Public Overloads Sub discrete_distribution(dictionary As Dictionary(Of String, Integer),
                                     b As String)
        If (dictionary.ContainsKey(b)) Then
            dictionary(b) += 1
        Else
            dictionary.Add(b, 1)
        End If
    End Sub
    Public Overloads Sub discrete_distribution(dictionary As Dictionary(Of Integer, Integer), b As Integer)
        If (dictionary.ContainsKey(b)) Then
            dictionary(b) += 1
        Else
            dictionary.Add(b, 1)
        End If
    End Sub
    Public Sub print_OnArMean()
        Me.RTxtArOnMean.AppendText(CurrentArMean.ToString("N2") & Environment.NewLine)
    End Sub
    Public Sub print_Database(Dog As Dog)
        Me.RTxTDatabase.AppendText(Dog.Breed.PadRight(25) & Dog.Weight.ToString("N2").PadRight(12) & Dog.Age & Environment.NewLine)

    End Sub
    Public Overloads Sub print_Distribution(dictionary As Dictionary(Of String, Integer))
        Me.RTxtBreedDistribution.AppendText("Breed Distribution: " & Environment.NewLine & Environment.NewLine)
        Me.RTxtBreedDistribution.AppendText("Count:".PadRight(10).PadLeft(35) & "Relative Freq:".PadRight(18) & "Percentage:" & Environment.NewLine & Environment.NewLine)
        For Each k As KeyValuePair(Of String, Integer) In dictionary
            Dim RelFreq = k.Value / ListOfDog.Count
            Me.RTxtBreedDistribution.AppendText(k.Key.PadRight(30) & k.Value.ToString.PadRight(10) & RelFreq.ToString("N2").PadRight(15) &
                                                 (RelFreq * 100).ToString("N2") & " %" & Environment.NewLine)
        Next
    End Sub
    Public Overloads Sub print_Distribution(dictionary As Dictionary(Of Integer, Integer))
        Me.RTxtBreedDistribution.AppendText(Environment.NewLine & Environment.NewLine & "Age Distribution: " & Environment.NewLine & Environment.NewLine)
        Me.RTxtBreedDistribution.AppendText("Count:".PadRight(10).PadLeft(35) & "Relative Freq:".PadRight(18) & "Percentage:" & Environment.NewLine & Environment.NewLine)
        For Each k As KeyValuePair(Of Integer, Integer) In dictionary
            Dim RelFreq = k.Value / ListOfDog.Count
            Me.RTxtBreedDistribution.AppendText(k.Key.ToString.PadRight(30) & k.Value.ToString.PadRight(10) & RelFreq.ToString("N2").PadRight(15) &
                                                 (RelFreq * 100).ToString("N2") & " %" & Environment.NewLine)
        Next

    End Sub
    Public Function new_dataset() As Dog
        'Large Dog breed Weight's is between 30 and 50kg
        'And can be old max(usually) 12 years (used for discrete mean exercise's)
        'We consider dogs only over 1 year old
        Dim Dog As New Dog With {
            .Breed = PossibleBreed(R.Next(0, PossibleBreed.Length)),
            .Weight = R.NextDouble * 20 + 30,
            .Age = R.Next(1, 13)
        }
        Return Dog
    End Function
    Private Sub BtnGo_Click(sender As Object, e As EventArgs) Handles BtnGo.Click
        Me.Timer.Start()
    End Sub

    Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick

        Dim Dog As Dog = new_dataset()
        ListOfDog.Add(Dog)
        print_Database(Dog)
        online_mean(Dog)
        print_OnArMean()
        discrete_distribution(DicOfBreed, Dog.Breed)
        discrete_distribution(DicOfAgeDistributio, Dog.Age)
    End Sub

    Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click
        Me.Timer.Stop()
        Me.RTxtArOnMean.AppendText(Environment.NewLine & ListOfDog.Count & " occurrences" & Environment.NewLine)
    End Sub



    Private Sub BtnDistribution_Click(sender As Object, e As EventArgs) Handles BtnDistribution.Click
        Me.RTxtBreedDistribution.Clear()
        print_Distribution(DicOfBreed)
        print_Distribution(DicOfAgeDistributio)
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        inizialized()
    End Sub
End Class

Dog.vb

Public Class Dog
    Public Breed As String
    Public Age As Integer
    'Public Height As Double
    Public Weight As Double
    'Public Footage As Double

    Public Overrides Function ToString() As String
        Return Breed & " " & Age & " " & Weight
    End Function
End Class

C#

form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Application4_C
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            inizialized();
        }
        public Random R = new Random();

        // List for store the dog
        public List<Dog> ListOfDog = new List<Dog>();

        // Array of breed
        public string[] PossibleBreed = new[] { "German Shepherd", "Alaskan Malamute", "Beauceron", "Bernese Mountain Dog", "Black Russian Terrier", "Weimaraner", "Pointer", "Rottweiler", "Siberian Husky", "Afghan Hound", "Boxer", "Collie", "Weimaraner", "Dalmatian", "Golden Retriver", "Irish Setter", "Labrador Retriver" };

        public int Count;
        public double CurrentArMean;

        // Dictionary for Frequence Distribution of the breed(Breed,count)
        public Dictionary<string, int> DicOfBreed = new Dictionary<string, int>();
        // Dictionary for Frequence Distribution of the age(Age,count)
        public Dictionary<int, int> DicOfAgeDistributio = new Dictionary<int, int>();


        public void inizialized()
        {
            Count = 0;
            CurrentArMean = 0;
            DicOfBreed.Clear();
            DicOfAgeDistributio.Clear();
            ListOfDog.Clear();
            this.RTxTDatabase.Text = ("Breed:".PadRight(25) + "Weight:".PadRight(10) + "Age:" + Environment.NewLine + Environment.NewLine);
            this.RTxtArOnMean.Text = ("Mean: " + Environment.NewLine + Environment.NewLine);
            this.RTxtBreedDistribution.Text = "Distribution: " + Environment.NewLine + Environment.NewLine;
        }




        public void online_mean(Dog CollForMean)
        {
            // Online algo for mean
            Count += 1;
            CurrentArMean = CurrentArMean + (CollForMean.Age - CurrentArMean) / Count;
        }
        public void discrete_distribution(Dictionary<string, int> dictionary, string b)
        {
            if ((dictionary.ContainsKey(b)))
                dictionary[b] += 1;
            else
                dictionary.Add(b, 1);
        }
        public void discrete_distribution(Dictionary<int, int> dictionary, int b)
        {
            if ((dictionary.ContainsKey(b)))
                dictionary[b] += 1;
            else
                dictionary.Add(b, 1);
        }
        public void print_OnArMean()
        {
            this.RTxtArOnMean.AppendText(CurrentArMean.ToString("N2") + Environment.NewLine);
        }
        public void print_Database(Dog Dog)
        {
            this.RTxTDatabase.AppendText(Dog.Breed.PadRight(25) + Dog.Weight.ToString("N2").PadRight(12) + Dog.Age + Environment.NewLine);
        }
        public void print_Distribution(Dictionary<string, int> dictionary)
        {
            this.RTxtBreedDistribution.AppendText("Breed Distribution: " + Environment.NewLine + Environment.NewLine);
            this.RTxtBreedDistribution.AppendText("Count:".PadRight(10).PadLeft(35) + "Relative Freq:".PadRight(18) + "Percentage:" + Environment.NewLine + Environment.NewLine);
            foreach (KeyValuePair<string, int> k in dictionary)
            {
                var RelFreq = k.Value / (double)ListOfDog.Count;
                this.RTxtBreedDistribution.AppendText(k.Key.PadRight(30) + k.Value.ToString().PadRight(10) + RelFreq.ToString("N2").PadRight(15) + (RelFreq * 100).ToString("N2") + " %" + Environment.NewLine);
            }
        }
        public void print_Distribution(Dictionary<int, int> dictionary)
        {
            this.RTxtBreedDistribution.AppendText(Environment.NewLine + Environment.NewLine + "Age Distribution: " + Environment.NewLine + Environment.NewLine);
            this.RTxtBreedDistribution.AppendText("Count:".PadRight(10).PadLeft(35) + "Relative Freq:".PadRight(18) + "Percentage:" + Environment.NewLine + Environment.NewLine);
            foreach (KeyValuePair<int, int> k in dictionary)
            {
                var RelFreq = k.Value / (double)ListOfDog.Count;
                this.RTxtBreedDistribution.AppendText(k.Key.ToString().PadRight(30) + k.Value.ToString().PadRight(10) + RelFreq.ToString("N2").PadRight(15) + (RelFreq * 100).ToString("N2") + " %" + Environment.NewLine);
            }
        }
        public Dog new_dataset()
        {
            // Large Dog breed Weight's is between 30 and 50kg
            // And can be old max(usually) 12 years (used for discrete mean exercise's)
            // We consider dogs only over 1 year old
            Dog Dog = new Dog()
            {
                Breed = PossibleBreed[R.Next(0, PossibleBreed.Length)],
                Weight = R.NextDouble() * 20 + 30,
                Age = R.Next(1, 13)
            };
            return Dog;
        }
        private void BtnGo_Click_1(object sender, EventArgs e)
        {
            Timer.Start();
        }


        private void BtnStop_Click_1(object sender, EventArgs e)
        {
            this.Timer.Stop();
            this.RTxtArOnMean.AppendText(Environment.NewLine + ListOfDog.Count + " occurrences" + Environment.NewLine);
        }



        private void BtnDistribution_Click_1(object sender, EventArgs e)
        {
            this.RTxtBreedDistribution.Clear();
            print_Distribution(DicOfBreed);
            print_Distribution(DicOfAgeDistributio);
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            inizialized();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            Dog Dog = new_dataset();
            ListOfDog.Add(Dog);
            print_Database(Dog);
            online_mean(Dog);
            print_OnArMean();
            discrete_distribution(DicOfBreed, Dog.Breed);
            discrete_distribution(DicOfAgeDistributio, Dog.Age);
        }
    }
}

Dog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application4_C
{
    public class Dog
    {
        public string Breed;
        public int Age;
        // Public Height As Double
        //public double Weight;
        // Public Footage As Double

        public override string ToString()
        {
            return Breed + " " + Age + " " + Weight;
        }
    }
}

Homework5_A

Create – in your preferred language C# or VB.NET – a demonstrative program which computes the online arithmetic mean (or “running mean”) and distribution for a continuous variable (can use random simulated values). Make the code as general and reusable as possible, as it must be used in your next applications and exam.

How i worked

I tried to modulate the code, so as to have it more robust and readable. Also for this reason the class has been put in a separate file.

   Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
 
        Dim Dog As Dog = new_dataset()
        ListOfDog.Add(Dog)
        print_Database(Dog)
        online_mean(Dog.Weight)
        print_OnArMean()
        discrete_distribution(DicOfBreed, Dog.Breed)
        discrete_distribution(DicOfAgeDistributio, Dog.Age)
    End Sub

Vb.Net

Form1.vb

Public Class Form1
    Public R As New Random

    'List for store the dog
    Public ListOfDog As New List(Of Dog)

    'Array of breed
    Public PossibleBreed() As String = {"German Shepherd", "Alaskan Malamute", "Beauceron", "Bernese Mountain Dog",
                                        "Black Russian Terrier", "Weimaraner", "Pointer", "Rottweiler", "Siberian Husky",
                                        "Afghan Hound", "Boxer", "Collie", "Weimaraner", "Dalmatian", "Golden Retriver",
                                        "Irish Setter", "Labrador Retriver"}

    Public Count As Integer
    Public CurrentArMean As Double

    Dim listOfIntervals As New List(Of Interval)


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        inizialized()
    End Sub
    Public Sub inizialized()
        Count = 0
        CurrentArMean = 0
        ListOfDog.Clear()
        listOfIntervals.Clear()
        Me.RTxTDatabase.Text = ("Breed:".PadRight(25) & "Weight:".PadRight(10) & "Time:".PadRight(12) & "Age:" & Environment.NewLine & Environment.NewLine)
        Me.RTxtArOnMean.Text = ("Mean: " & Environment.NewLine & Environment.NewLine)
        Me.RTxtBreedDistribution.Text = "Distribution: " & Environment.NewLine & Environment.NewLine
    End Sub



    'Online algo for mean
    Public Sub online_mean(mean As Double)
        Count += 1
        CurrentArMean = CurrentArMean + (mean - CurrentArMean) / Count
    End Sub
    Public Overloads Sub discrete_distribution(dictionary As Dictionary(Of String, Integer),
                                     b As String)
        If (dictionary.ContainsKey(b)) Then
            dictionary(b) += 1
        Else
            dictionary.Add(b, 1)
        End If
    End Sub
    Public Overloads Sub discrete_distribution(dictionary As Dictionary(Of Integer, Integer), b As Integer)
        If (dictionary.ContainsKey(b)) Then
            dictionary(b) += 1
        Else
            dictionary.Add(b, 1)
        End If
    End Sub
    Public Sub print_OnArMean(type As String)
        Me.RTxtArOnMean.AppendText(type & ": " & CurrentArMean.ToString("N2") & Environment.NewLine)
    End Sub
    Public Sub print_Database(Dog As Dog)
        Me.RTxTDatabase.AppendText(Dog.Breed.PadRight(25) & Dog.Weight.ToString.PadRight(10) & Dog.Time.ToString.PadRight(12) & Dog.Age & Environment.NewLine)

    End Sub

    Public Sub print_continue_distr()
        Me.RTxtBreedDistribution.AppendText("Continue time Distribution: " & Environment.NewLine & Environment.NewLine)
        Me.RTxtBreedDistribution.AppendText("Count:".PadRight(10).PadLeft(25) & "Relative Freq:".PadRight(18) & "Percentage:" & Environment.NewLine & Environment.NewLine)
        For Each i In listOfIntervals
            Me.RTxtBreedDistribution.AppendText(i.lowerEnd & " - " & i.upperEnd.ToString.PadRight(15) & i.count.ToString.PadRight(13) & i.relativeFreq.ToString("N2").PadRight(10) & i.percentage.ToString("N2") & " %" & Environment.NewLine)
        Next
    End Sub
    Public Function new_dataset() As Dog
        Dim minTime As Integer = 10
        Dim maxTime As Integer = 120
        Dim maxWeight As Integer = 50
        Dim minWeight As Integer = 30
        'Time to complete a race can be between 10 and 120 minutes

        Dim Dog As New Dog With {
            .Breed = PossibleBreed(R.Next(0, PossibleBreed.Length)),
            .Time = Math.Round(R.NextDouble * (maxTime - minTime) + minTime, 2),
            .Weight = Math.Round(R.NextDouble * (maxWeight - minWeight) + minWeight, 2),
            .Age = R.Next(1, 13)
        }
        Return Dog
    End Function
    Private Sub BtnGo_Click(sender As Object, e As EventArgs) Handles BtnGo.Click
        Me.Timer.Start()
    End Sub

    Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick

        Dim Dog As Dog = new_dataset()
        ListOfDog.Add(Dog)
        print_Database(Dog)
        online_mean(Dog.Weight)
        print_OnArMean("Weight mean")
        Count = 0
        CurrentArMean = 0
        online_mean(Dog.Time)
        print_OnArMean("Time mean")
        create_interval(Dog)
        continue_distribution()
    End Sub

    Public Sub continue_distribution()
        For Each i In listOfIntervals
            i.relativeFreq = i.count / listOfIntervals.Count
            i.percentage = i.relativeFreq * 100
        Next
    End Sub

    Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click
        Me.Timer.Stop()
        Me.RTxtArOnMean.AppendText(Environment.NewLine & ListOfDog.Count & " occurrences" & Environment.NewLine)
    End Sub



    Private Sub BtnDistribution_Click(sender As Object, e As EventArgs) Handles BtnDistribution.Click
        Me.RTxtBreedDistribution.Clear()
        print_continue_distr()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        inizialized()
    End Sub

    'interval
    Public Function interval_Correct(d As Dog, i As Interval) As Boolean
        Return d.Time > i.lowerEnd AndAlso d.Time <= i.upperEnd
    End Function

    Public Function interval_isLeft(d As Dog) As Boolean
        Return d.Time <= listOfIntervals(0).lowerEnd
    End Function
    Public Function interval_isRight(d As Dog) As Boolean
        Return d.Time > listOfIntervals(listOfIntervals.Count - 1).upperEnd
    End Function

    Public Sub inizialized_list(intervalSize As Double)
        Dim startingEndPoint As Double = 40
        Dim interval_0 As New Interval
        interval_0.lowerEnd = startingEndPoint
        interval_0.upperEnd = interval_0.lowerEnd + intervalSize
        listOfIntervals.Add(interval_0)
    End Sub
    Public Sub create_interval(d As Dog)
        Dim intervalSize As Double = 5

        If listOfIntervals.Count = 0 Then
            inizialized_list(intervalSize)
        End If


        Dim dogAlloc As Boolean = False

        For Each i In listOfIntervals
            If interval_Correct(d, i) Then
                i.count += 1
                dogAlloc = True
                Exit For
            End If
        Next
        If dogAlloc Then
            Exit Sub
        End If
        If interval_isLeft(d) Then

            newLeftInterval(intervalSize, d)

        ElseIf interval_isRight(d) Then
            newRightInterval(intervalSize, d)
        End If
    End Sub

    Public Sub newLeftInterval(intervalSize As Integer, d As Dog)

        Do
            Dim newLeftIn As New Interval
            newLeftIn.upperEnd = listOfIntervals(0).lowerEnd
            newLeftIn.lowerEnd = newLeftIn.upperEnd - intervalSize

            listOfIntervals.Insert(0, newLeftIn)

            If interval_Correct(d, newLeftIn) Then
                newLeftIn.count += 1
                Exit Do
            End If
        Loop
    End Sub

    Public Sub newRightInterval(intervalSize As Integer, d As Dog)
        Do
            Dim newRightIn As New Interval
            newRightIn.lowerEnd = listOfIntervals(listOfIntervals.Count - 1).upperEnd
            newRightIn.upperEnd = newRightIn.lowerEnd + intervalSize
            listOfIntervals.Add(newRightIn)

            If interval_Correct(d, newRightIn) Then
                newRightIn.count += 1
                Exit Do
            End If
        Loop
    End Sub
End Class

Dog.vb

Public Class Dog
    Public Breed As String
    Public Age As Integer
    Public Time As Double
    Public Weight As Double

    Public Overrides Function ToString() As String
        Return Breed & " " & Age & " " & Weight & " " & Time
    End Function
End Class

Interval.vb

Public Class Interval
    Public lowerEnd As Double
    Public upperEnd As Double
    Public count As Integer
    Public relativeFreq As Double
    Public percentage As Double
End Class