Maths Algorithms in C#: Variance

I talked a bit about variance in the post on standard deviation, so this is a little bit a rehash from what I said there.

The variance is obtained by calculating the data set consisting of each data point in the original data set subtracting the arithmetic mean for the data set, and then squaring it.

We then take the arithmetic mean of the deviations, which gives us the variance for our data set.
Read More »

Maths Algorithms in C#: Standard Deviation

Standard deviation is a very common calculation in statistical analysis, and is formally defined as the square root of the variance of the data set.

The variance of a data set is how much the data varies from the mean.

So then, in simple terms, what we do is for each data point in the data set, we take the value at that point, subtracting the mean from it, and then squaring it.

Once we have the data set of deviations, we can then find the arithmetic mean of this, which is the variance.

The final step here is to find the squareroot of this which gives us the standard deviation.

public static double StandardDeviation(List<double> values)
{
	double standardDeviation, mean, deviationMean;
	List<double> deviation = new List<double>();
	
	mean = ArithmeticMean(values);

	foreach(double value in values)
	{
		deviation.Add(Math.Pow((value - mean), 2));
	}

	deviationMean = ArithmeticMean(deviation);
	standardDeviation = Math.Sqrt(deviationMean);

	return standardDeviation;
}

The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib

Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009

Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library


Read More »

Maths Algorithms in C#: The Median

The median is defined as the data point that falls exactly at the midpoint of a set of data points. If there is an even number of points, then the average is taken of the middle two points.

There is one consideration though – the data points sent through to this function needs to be sorted, otherwise it will return garbage data.

public static double Median(List<double> values)
{
	int mid;
	double median;

	values.Sort();

	if (MathExt.IsEven(values.Count))
	{
		mid = (values.Count / 2) - 1;
		median = (values[mid] + values[mid + 1]) / 2.0;
	}
	else
	{
		mid = (values.Count / 2);
		median = values[mid];
	}

	return median;
}

The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib

Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009

Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library


Read More »

Maths Algorithms in C#: The Geometric Mean

The geometric mean is similar to the arithmetic mean in that it is a type of average for the data, except it has a rather different way of calculating it.

The geometric mean is defined as the n-th root of the product of each value in the data set, where n is the number of data points in the set. This makes it useful for describing things such as percentage growth.

public static double GeometricMean(List<double> values)
{
	double geometricMean, product;

	product = 1.0;
	foreach(double value in values)
	{
		product *= value;
	}

	geometricMean =  Math.Pow(product, (1.0 / (double)values.Count));
	return geometricMean;
}

The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib

Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009

Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library


Read More »

Maths Algorithms in C#: The Arithmetic Mean

The arithmetic mean is defined as the average of a set of data. It is found by taking the sum of each value in the data set, and then dividing by the total number of data points.

public static double ArithmeticMean(List<double> values)
{
	double mean, sum;

	sum = 0.0;
	foreach (double value in values)
	{
		sum += value;
	}

	mean =  sum / (double)values.Count;
	return mean;
}

The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib

Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009

Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library


Read More »

Finding the Midpoint Between Two GPS Coordinates

Previously I showed how to find the distance between coordinates and the bearing, but what if you want to find the midpoint of two coordinates.

The code in C# is rather straightforward – that is, if you know a little bit of trigonometry.
Read More »

Finding the Bearing Between Two GPS Coordinates

Don’t you think it would be really great to be able to work out the precise bearing of a place in relation to where you are now? The calculation for this is rather simple if you have the geographical coordinates of the two points that you would like to find the bearing of.

The code below calculates the angle between the two coordinates. The last function call to ConvertToBearing puts the value into the right range. The atan function returns a value back (converted to degrees), which is in the range of -180 to 180 degrees, whereas, bearing is normally given in the range 0 - 360 degrees.
Read More »

Finding the Distance Between Two GPS Coordinates

With the advent of GPS systems, adn mapping systems like Google Earth, it has become rather useful to be able to calculate the distance (as the crow flies) between two points on the earth.

One method to do so is known as the Haversine formula.

Taking the longitude and latitude of two points, and then converting them to radians, since the C# trig functions take values in radians, not in degrees.

We then take the difference of latitude and longitude of the two points. Applying the Haversine formula needed and then multiplying by the radius of the earth gives us the distance in kilometres of the two points.

a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) c = 2.atan2(√a, √(1−a)) Distance = (radius of earth) * c

This method of calculating the distance is not entirely accurate though, but will suffice for all but the most exacting of applications. For every kilometer, there is an average error of 3 meters, or roughly a 0.3-0.5% error. This error creeps in because the formula assumes a perfectly spherical earth, whereas the earth is slightly ellipsoid, so the radius around the equator is slightly bigger than the radius around the poles.
Read More »

Generating Various Audio Waveforms in C#

I did a little bit of tinkering with an audio application a while ago which generated a variety of different audio waveforms. It is surprisingly easy to generate quite a few of the more common ones such as white noise and sine waves, so here is a little howto to implement this in C#.

White noise is pure and simply just random data being played back. It is the sound of static and of waterfalls. In practice, white noise is very useful for muffling other sounds, which is why you sometimes see in movies, scenes where to beat bugs listening in on conversations, the actors turn on a tap before talking about some state secret. The white noise from the flowing water defeats the listening devices.

This is dreadfully easy to implement, and simply entails filling a buffer with random values between 0 and 255. The buffer can then be played back, or saved as an audio file.

private void GenerateWhiteNoise(ref byte[] SampleBuffer, int NumSamples)
{
	Random rnd1 = new System.Random();

	for (int i = 0; i < NumSamples; i++)
	{
		SampleBuffer[i] = (byte) rnd1.Next(255);
	}
}

The next wave to look at is the sine wave. This type of wave gives a pure sounding tone. Here, what we need is the number of samples, the desired frequency and the sample rate.
Read More »

Fractals in C#: The Lorenz Attractor

The Lorenz attractor is a fractal based on the Lorenz oscillator, which is a 3-dimensional chaotic system.

Lorenz Attractor

For a full explanation on the Lorentz attractor, you can read the wikipedia article.

The central equations needed for the Lorenz oscillator are: dx/dt = σ(y - x) dy/dt = x(ρ - z) - y dz/dt = xy - βz

σ is the Prandtl number, and is usually set to 10. ρ is the Rayleigh number and can be varied. β is set to 8/3.

Now, drawing the Lorenz attractor in C#, we are going to iterate a fixed number of times through these equations. In the code below, ρ is set to 28, and the number of iterations to 8000.

The code is able to draw the attractor in two dimensions or three dimensions, and the first part of the code calculates the transformations we will use later to transform the coordinates of attractor (which are in three dimensions) to screen coordinates.

We then iterate through each iteration, taking the x, y and z from the previous iteration, and running them through the Lorens oscillator equations to get our first set of derivatives.

We then add these to the previous x,y and z values, and then run them through the equations again, getting our second set of derivatives, and then add these to the x,y and z values as before. We repeat this until we get four sets of derivatives.

Once we have that we then add them together multiply by a scaling factor, and and them to x, y and z respectively.

Now that we have the new coordinates, we can plot a point at that position, applying our transformations to convert the three dimensional coordinates to screen coordinates.
Read More »

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)