Homework_14RA

SDE and methods for numerical solution.

A solution to an SDE is itself a stochastic function, which means that its value X(t) at any given time t is a random variable.

The Euler-Maruyama (EM) and Milstein methods

These methods are based on the truncated Ito-Taylor expansion.
Unfortunately, in many cases analytic solutions are not available for these equations, so we are required to use numerical methods to approximate the solution.

If we add a random element or elements to the deterministic differential equation, we have transition from an ordinary differential equation to SDE.

Some analytical and numerical solutions considered numerical approximations of random periodic solutions for SDEs. On the other hand, constructed a Milstein scheme by adding an error correction term for solving stiff SDEs.

Remember SDE form:
dX(t,w) = μ(t,X(t,w))dt + σ(t,X(t,w))dW(t,w) and X(t0,w) = X0(w)
where μ is the drift coefficient
where σ is the the diffusion coefficient

The Monte Carlo simulation:

Monte Carlo methods are numerical methods, where random numbers are used to conduct a computational experiment. Numerical solution of stochastic differential equations can be viewed as a type of Monte Carlo calculation.

In Monte Carlo simulation, the entire system is simulated a large number of times.
So, a set of suitable sample paths is produced on [t0,T].
Each simulation is equally likely, referred to as a realization of the system. For each realization, all of the uncertain parameters are sampled.

Stochastic Taylor series expansion for produce a sample path solution to the SDE on [t0,T].

The Taylor formula plays a very significant role in numerical analysis. We can obtain the approximation of a sufficiently smooth function in a neighborhood of a given point to any desired order of accuracy with the Taylor formula.

Ito-Taylor expansion obtained via Ito’s formula

First we can obtain an Ito-Taylor expansion for the stochastic case.

dX(t) = μ(X(t))dt + σ(X(t))dW(t)
where μ and σ satisfy a linear growth bound and are sufficiently smooth.

Once we have the Ito-Taylor expansion, we can construct numerical integration schemes for the proces.

Ito-Taylor expansion was based upon the use of multiple stochastic integrals. Itô–Taylor expansions are characterized by the choice of the multiple integrals which appear in them.

Euler-Maruyama method

The Milstein method is another technique for the approximate numerical solution of a stochastic differential equation.

If we truncate Ito’s formula of the stochastic Taylor series after the first order terms, we obtain the Euler method or Euler-Maruyama method.

Milstein method

If we truncate the stochastic Taylor series after second order terms, we obtain the Milstein method.

There are many other approximation schemes for SDEs, ie: Runge-Kutta method(which achieves the same convergence properties as the Milstein method, but without the need to compute derivatives of the σ(⋅) function.

What has been observed
(https://www.researchgate.net/publication/313191865_On_the_convergence_of_the_Euler-Maruyama_method_and_Milstein_scheme_for_the_solution_of_
stochastic_differential_equations
)

Milstein method is more accurate than its counterpart, Euler Maruyama method. For Milstein method, the errors decrease as N increases for all N values.
Overall, Milstein method performed consistently better than Euler Maruyama method with respect to accuracy.
Euler Maruyama method is the simplest numerical method for solving stochastic differential equation but has slow convergence.

https://www.sciencedirect.com/science/article/pii/S0377042703004643
https://en.wikipedia.org/wiki/Euler%E2%80%93Maruyama_method
https://advancesindifferenceequations.springeropen.com/articles/10.1186/s13662-018-1466-5

Recommended

https://hautahi.com/sde_simulation

Homework_12RA

Find out what you have just generated in exercise 18_A. How can you interpret what you see? Can you find out about all the well known distributions that “naturally (and “magically”) arise” in this process ?

Poisson Distribution

A Poisson Process is a model for a series of discrete event where the average time between events is known, but the exact timing of events is random.

A Poisson Process meets the following criteria

  1. Events are independent of each other. The occurrence of one event does not affect the probability another event will occur.
  2. The average rate (events per time period) is constant.
  3. Two events cannot occur at the same time.

A discrete random variable X is said to have a Poisson distribution with parameter λ > 0 if for k = 0, 1, 2, …, the probability mass function of X is given by:

k is the number of occurrences
λ = E(x) = Var(x)

Homework11_RA

Do a research about the random walk and its properties. Looking at your possible simulation in exercise 15_A, how would you describe the beaviour of the distribution of Y, as n increases ? What are mean and variance of Y at step n ?

The Random Walk

A random walk is a mathematical object, known as a stochastic or random process, that describes a path that consists of a succession of random steps on some mathematical space such as the integers.


More in general, a random walk refers to any process in which there is no observable pattern or trend; that is, where the movements of an object, or the values taken by a certain variable, are completely random. Certain real-life scenarios that could be modeled as random walks could be:

  • The movements of an animal foraging for food in the wilderness
  • The path traced by a molecule as it moves through a liquid or a gas (diffusion)
  • The price of a stock as it moves up and down
  • The path of a drunkard wandering through Greenwich Village
  • The financial status of a gambler at the roulette wheel in Las Vegas
A Fun Caveat on Random Walks: Monkeys and Typewriters

As n (steps) gets larger, we expect to get further and further from the origin. In fact, for an infinite number of random walks with an infinitely large number of steps, we will end up visiting every number on the number line.

This idea was illustrated quite vividly and humorously in the book Fooled by Randomness., by Nassim Nicholas Taleb In that book, Taleb posits the idea that:

if a sufficiently large group of monkeys were to type randomly on typewriters (a more complex variety of a random walk) for an infinite amount of time, one of those monkeys would necessarily compose The Iliad. And not only that—given infinite time, one of the monkeys who composes the Iliad will then go on to compose the Odyssey.

Distribution

The mean of the empirical distribution is an unbiased estimator (is the difference between this estimator’s expected value and the true value of the parameter being estimated. An estimator or decision rule with zero bias is called unbiased) of the mean of the population distribution.

When n increase, the mean is closer to the real value of theorical CDF.

The variance of the empirical distribution times n/n − 1 is an unbiased estimator of the variance of the population distribution.

https://en.wikipedia.org/wiki/Random_walk
https://en.wikipedia.org/wiki/Empirical_distribution_function
https://en.wikipedia.org/wiki/Bias_of_an_estimator
https://magoosh.com/statistics/what-is-random-walk-theory/

Homework10_RA

Do a research about the various methods proposed to compute the running median (one pass, online algorithms). Store (cite sources) the algorithm that you think is a good candidate and explaining briefly how it works and possibly show a quick demo.

The running median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value.

  • If we keep each number in a sorted sequence then cost of single entry is O(n) and finding median is O(n).
    A slight modification can be done by keeping the middle pointer and adjusting it based on the insertion on its left side and right side. In that case finding median after insertion is O(1). But the overall cost for finding median still remains O(n) as insertion in sorted sequence is necessary after each number is entered.
  • We can keep two heaps which divides the entered number in two almost equal halves. Half of the number would be greater than the median and the rest would be lesser. The upper half will be maintained in a min heap and the lower half will be maintained in a max heap. In this arrangement we can find out in O(1) time whether a new number would go to the upper half or lower half. All we need to do is to compare the new number with the head of two heaps. After deciding we can insert in a heap in O(log n) time. After this insertion if the heaps are unbalanced, we can just move from one heap to another. which is again of O(log n) complexity. And now we can find the median in O(1) time. If two heaps contain same number of elements then median is the average of the head of two heaps. If one is greater, then median is the head of the larger heap.
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;


public class RunningMedian
{
    PriorityQueue<Integer> upperQueue;
    PriorityQueue<Integer> lowerQueue;

    public RunningMedian()
    {
        lowerQueue=new PriorityQueue<Integer>(
          20,new Comparator<Integer>()
        {

            @Override
            public int compare(Integer o1, Integer o2)
            {

                return -o1.compareTo(o2);
            }

        });
        upperQueue=new PriorityQueue<Integer>();
        upperQueue.add(Integer.MAX_VALUE);
        lowerQueue.add(Integer.MIN_VALUE);
    }

    public double getMedian(int num)
    {
        //adding the number to proper heap
            if(num>=upperQueue.peek())
                upperQueue.add(num);
            else
                lowerQueue.add(num);
        //balancing the heaps
        if(upperQueue.size()-lowerQueue.size()==2)
            lowerQueue.add(upperQueue.poll());
        else if(lowerQueue.size()-upperQueue.size()==2)
            upperQueue.add(lowerQueue.poll());
        //returning the median
        if(upperQueue.size()==lowerQueue.size())
            return(upperQueue.peek()+lowerQueue.peek())/2.0;
        else if(upperQueue.size()>lowerQueue.size())
            return upperQueue.peek();
        else
            return lowerQueue.peek();

    }
    public static void main(String[] args)
    {
        Random random=new Random();
        RunningMedian runningMedian=new RunningMedian();
        System.out.println("num\tmedian");
        for(int i=0;i<50;++i)
        {
            int num=random.nextInt(100);
            System.out.print(num);
            System.out.print("\t");
            System.out.println(
              runningMedian.getMedian(num));
        }

    }

}

http://www.dsalgo.com/2013/02/RunningMedian.php.html

https://dcc-backup.ligo.org/public/0027/T030168/000/T030168-00.pdf

Homework9_RA

Do a research about the various methods to generate, from a Uniform([0,1)), all the most important random variables (discrete and continuous).

Random Variable

Informally is a variable that is described as a variable whose values depend on outcomes of a random phenomenon.

In formal a random variable is understood as a measurable function defined on a probability space that maps from the sample space to the real numbers.
So the random variable is defined as a function, that must be measurable, which performs the mapping of the outcomes of a random process to a numeric value.

Random variables can be either discrete or continuous.

Not long after research began at RAND in 1946, the need arose for random numbers that could be used to solve problems of various kinds of experimental probability procedures. These applications, called Monte Carlo methods(therefore, a class of techniques for randomly sampling a probability distribution), required a large supply of random digits and normal deviates of high quality.

Random number generators

The purpose of random number generators (RNGs) is to produce sequences of numbers that appear as if they were generated randomly from a specified probability distribution.


A random number generator produces truly random numbers (the results are unpredictable). These are generally produced by physical devices also known as noise generator which are coupled with a computer. In computing, an apparatus that produces random numbers from a physical process is called a hardware random number generator or TRNG (for true random number generator).
Computers are deterministic in nature so producing truly random numbers with a computer is challenging, which is why we generally resort to using noise generators if we need “true” randomness. However, what we can do on a computer, is develop some sort of algorithm for generating a sequence of numbers that approximates the properties of random numbers.
When numbers are produced by some sort of algorithm or formula that simulates the values of a random variable X, they are called pseudorandom numbers. And the algorithm is called a pseudorandom number generator (or PRNG). The term “simulate” here is important: it simply means that the algorithm can generate sequences of numbers which have statistical properties that are similar (and this can be tested) to that of the random variable we want to simulate. For instance if we need to simulate a random variable X with probability distribution D, then we will need to test whether the sequence of numbers produced by our PRNG has the same distribution.

For some applications, such as cryptography, it is necessary to have pseudo-random number sequences for which prediction is computationally infeasible.

Uniform random generator

  • The binomial distribution with parameters n and p is the discrete probability distribution of the number of successes in a sequence of n independent experiments, each asking a yes–no question, and each with its own Boolean-valued outcome: success/yes (with probability p) or failure/no(with probability q = 1 − p).
  • The Bernoulli distribution, (a special case of the binomial distribution where a single trial is conducted (so n would be 1 for such a binomial distribution)),

is the discrete probability distribution of a random variable which takes the value 1 with probability p and the value 0 with probability q = 1 − p.

  • The Poisson distribution is a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time or space if these events occur with a known constant mean rate and independently of the time since the last event. The Poisson distribution can also be used for the number of events in other specified intervals such as distance, area or volume.

The exponential distribution is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution. It is the continuous analogue of the geometric distribution, and it has the key property of being memoryless.

Image for post
The general form of Normal Distribution.
https://en.wikipedia.org/wiki/Normal_distribution

A normal (or Gaussian or Gauss or Laplace–Gauss) distribution is a type of continuous probability distribution for a real-valued random variable.

https://towardsdatascience.com/understanding-random-variable-a618a2e99b93
https://towardsdatascience.com/how-to-generate-random-variables-from-scratch-no-library-used-4b71eb3c8dc7
https://www.britannica.com/science/statistics/Random-variables-and-probability-distributions
https://statweb.stanford.edu/~owen/mc/Ch-unifrng.pdf
https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/monte-carlo-methods-in-practice/generating-random-numbers
https://machinelearningmastery.com/monte-carlo-sampling-for-probability/
https://en.wikipedia.org/wiki/Poisson_distribution

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