Skip to content

Archive

Category: Mathematics

A prime number is any number that can only be evenly divided by itself and 1. So for example 2, 3 and 5 are prime, but 6 and 9 are not.

Now, to find all the prime numbers that are factors in a number, we need to first fcheck if the number is even. If it is , then 2 is a factor, and then we keep dividing until the number is odd.

Then, starting at 3, and counting up in 2′s, we try and find a number which divides into the number, each time dividing by the divisor if a match is found.

 using System.Collections;

       public static int[] PrimeFactors(int num)
        {
            ArrayList factors = new ArrayList();

            bool alreadyCounted = false;
            while (num % 2 == 0)
            {
                if (alreadyCounted == false)
                {
                    factors.Add(2);
                    alreadyCounted = true;
                }
                num = num / 2;
            }

            int divisor = 3;
            alreadyCounted = false;
            while (divisor <= num)
            {
                if (num % divisor == 0)
                {
                    if (alreadyCounted == false)
                    {
                        factors.Add(divisor);
                        alreadyCounted = true;
                    }
                    num = num / divisor;
                }
                else
                {
                    alreadyCounted = false;
                    divisor += 2;
                }
            }

            int[] returnFactors = (int[])factors.ToArray(typeof(int));
     

            return returnFactors;
        }

Share

Factorials are defined as a number that is multiplied by every positive number below it, and is denoted by an exclamation mark, ie n! = n * (n – 1) * (n – 2) … 2 * 1.

This is a very easy function to write.

        public static long Factorial(int num)
        {
            long fact = 1;
            for (int i = 2; i <= num; i++)
            {
                fact = fact * i;
            }
            return fact;
        }

Combinations in Combinatorics (a branch of mathematics covering combinations and permutations) gives you the number of combinations that exist for a given sample. With combinations, items selected cannot be repeated, much like selecting names out of a hat, and then after taking one out, you do not put it back in again, and then select again until you have required amount.

So, given a set of values of size n, if you select r items from the set, the number of different combinations which you can select is given by the formula
C = n! / r!(n - r)!

Here is the code to calculate this. The MathExt class is just the name of the class containing these functions, so you can replace that with wherever you have defined the factorial function.

        public static int Combination(int n, int r)
        {
            int Comb = 0;
            Comb = (int)(MathExt.Factorial(n) / (MathExt.Factorial(r) * MathExt.Factorial(n - r)));
            return Comb;
        }

Permutations are a little simpler than combinations. In this case, you still selecting r items out of a set of n items, however, you are able to pull out the same item more than once. Much like pulling a name out of a hat, and then putting it back in before putting another name out of the hat.
C = n! / (n - r)!

        public static int Permutation(int n, int r)
        {
            int Perm = 0;
            Perm = (int)(MathExt.Factorial(n) / MathExt.Factorial(n - r));
            return Perm;
        }
Share

A vector is simply a 1-dimensional array of numbers that often refer to coordinates, or directions. The theory of vectors is best left to wikipedia.

Implementing a vector class in C# is pretty easy.

The vector is stored as an array within the class. The constructor can either set this array directly, or initialises it to a particular size.

The Zero() function sets the entire vector to 0.

The Abs() function calculates the absolute value of the vector, which is the square root of the sum of the squares of the components of the vector.

The Dot() function returns the dot product of the vector, with another vector. The dot product is the sum of the products of each component in the vectors.

The Scale() function scales the vector by the scaling factor supplied.

The + and - operators are overloaded to make it easy to add and subtract vectors.

Each component of first vector is added (or subtracted) to the equivalent component of the second vector, and then the resulting vector is returned.

continue reading…

Share

Matrices are a very useful thing in computer programming – especially in 3D graphics programming. Out of all the mathematics I learned at University, matrices are the one thing that keep rearing their head over and over.

I am not going to go into major detail over what a matrix is – wikipedia can tell you that much better than I can – so will focus mainly on how to implement one in C#.

Essentially, a matrix is a 2-dimensional array of numbers, often representing a set of equations. The number of columns and rows is flexible.

Using the Matrix class below, the constructor can either take an x and y value or an array to determine how big to make the internal array for the matrix.

The Zero() function sets all entries in the matrix to zero by looping through the entire array.

The SetIdentity() function makes the matrix an identity matrix, which means that all the values are 0, except for the values along the diagonal from top left to bottom right being set to 1.

The Transpose function transforms the columns of the matrix into the rows, and vice versa.

The Scale function multiplies each value in the matrix by a scaling factor.

The determinant of an array is found by adding all the products of the entries of each diagonal sloping in a right direction, and subtracting the products of the entries of each diagonal sloping in a opposite direction. This is done with the Determinant function

The Trace function returns the sum of the main diagonal of the matrix.

The matrix class has also got a few overloaded operators, to make handling matrices easier.

The + operator is overloaded so that when passed two matrices, each value in the one matrix is added to the equivalent value in the second matrix. Both matrices need to be the same size for this to work.

A second overload for the + operator takes a scalar value and adds it to the matrix, which just adds that value to each value in the matrix.

The - operator performs identically to the + operator, except that it subtracts instead of adds the matrices.

The * operator multiplies the two matrices together, which is a little more involved than addition.

continue reading…

Share

Finding the roots of a quadratic equation (which is where it crosses the x axis) can be a rather involved calculation. I remember in school having to do them, and the equations they gave usually worked out to nice numbers. Often in the real world, it is not quite so easy.

Fortunately, computers are not scared by numbers that are difficult, and can solve quadratics quite well.

The function below solves quadratics in the form of Ax2 + Bx + C = 0. Providing A, B and C, the function finds the two roots of the equation, and also determines whether the roots are real, real repeating or complex roots.

		public static void SolveQuadratic(double A, double B, double C, ref double X1Real, ref double X1Im, ref double X2Real, ref double X2Im, ref int Type)
		{
			//Type: 1 = real, 2 = repeating, 3 = complex
			double Z = 0;

			Z = Math.Pow(B, 2) - (4 * A * C);
			Z = Math.Floor(100 * Z + 0.5) / 100.0;
			
			if (Z < 0)
			{
				X1Real = (-1) * B / (2.0 * A);
				X1Real = Math.Floor(100 * X1Real + 0.5) / 100.0;
				X2Real = X1Real;

				X1Im = Math.Sqrt(Math.Abs(Z)) / (2.9 * A);
				X1Im = Math.Floor(100 * X1Im + 0.5) / 100.0;
				X2Im = (-1) * X1Im;

				Type = 3;
			}
			else if(Z == 0)
			{
				X1Real = (-1) * B / (2.0 * A);
				X1Real = Math.Floor(100 * X1Real + 0.5) / 100.0;
				X2Real = X1Real;

				X1Im = 0.0;
				X2Im = 0.0;

				Type = 2;
			}
			else
			{
				X1Real = (((-1) * B) + Math.Sqrt(Z)) / (2.0 * A);
				X1Real = Math.Floor(100 * X1Real + 0.5) / 100.0;

				X2Real = (((-1) * B) - Math.Sqrt(Z)) / (2.0 * A);
				X2Real = Math.Floor(100 * X2Real + 0.5) / 100.0;

				X1Im = 0.0;
				X2Im = 0.0;

				Type = 1;
			}
		}
Share

We have already looked at several other ways of doing a least squares fit to find an quation representing a set of data. We now look at the least squares fit using full logs, which tries to match the data with the equation y = B*xM, using the least squares method.

As with the previous least squares functions, the function below returns the calculated values for M and B, and if no solution exists returns 0 for both of them.

		public static void LeastSquaresFitLogFull(Pnt[] points, int numPoints, ref double M, ref double B)
		{
			//Gives best fit of data to curve Y = B*X^M

			double x1, y1, xy, x2, J;
			double[] LX = new double[numPoints];
			double[] LY = new double[numPoints];
			int i;

			x1 = 0.0;
			y1 = 0.0;
			xy = 0.0;
			x2 = 0.0;

			for (i = 0; i < numPoints; i++)
			{
				LX[i] = Math.Log10(points[i].X);
				LY[i] = Math.Log10(points[i].Y);
				x1 = x1 + LX[i];
				y1 = y1 + LY[i];
				xy = xy + LY[i] * LX[i];
				x2 = x2 + LX[i] * LX[i];
			}

			J = ((double)numPoints * x2) - (x1 * x1);
			if (J != 0.0)
			{
				M = (((double)numPoints * xy) - (x1 * y1)) / J;
				M = Math.Floor(1.0E3 * M + 0.5) / 1.0E3;
				B = ((y1 * x2) - (x1 * xy)) / J;
				B = Math.Floor(1.0E3 * B + 0.5) / 1.0E3;
			}
			else
			{
				M = 0;
				B = 0;
			}
		}
Share

This algorithm for the least squares fit uses a logarithmic abscissa, and tries to find an equation matching the data set with the form y = M * log(X)/log(10) + B, using the least squares method.

The function below finds M and B, and if no solution exists, it returns 0 for both these values.

		public static void LeastSquaresFitLogAbscissa(Pnt[] points, int numPoints, ref double M, ref double B)
		{
			//Gives best fit of data to curve Y = M*log(X)/log(10) + B

			double x1, y1, xy, x2, J, LX;
			int i;

			x1 = 0.0;
			y1 = 0.0;
			xy = 0.0;
			x2 = 0.0;

			for (i = 0; i < numPoints; i++)
			{
				LX = Math.Log10(points[i].X);
				x1 = x1 + LX;
				y1 = y1 + points[i].Y;
				xy = xy + points[i].Y * LX;
				x2 = x2 + LX * LX;
			}

			J = ((double)numPoints * x2) - (x1 * x1);
			if (J != 0.0)
			{
				M = (((double)numPoints * xy) - (x1 * y1)) / J;
				M = Math.Floor(1.0E3 * M + 0.5) / 1.0E3;
				B = ((y1 * x2) - (x1 * xy)) / J;
				B = Math.Floor(1.0E3 * B + 0.5) / 1.0E3;
			}
			else
			{
				M = 0;
				B = 0;
			}
		}
Share