Skip to content

Archive

Category: Mathematics

GrapherCreating an application to draw graphs of mathematical equations has two components to it, namely, parsing the equation and drawing the results.

Parsing an equation is quite a complicated endeavor. However, I found on the internet a very useful C# library that parses equations very well called dotMath by Steve Hebert. You can visit the website for the library at . Rather than write my own library, I used this library to do all the parsing for me.

The fun part – for me anyway – is trying to draw the graph of an expression. I created a Windows Forms control that contains a picture box that fills the entire control. This picture box will contain the graph that we draw.

The actual generation of the image we are going to draw happens using a Bitmap object.

We set up the pens and brushes we need for the axis, graph, grid and background using the configuration settings that the class contains.

If the flag to draw the axes is set, we first draw the x and y axes, and then label it, using the scale we specify. The offset allows us to move the graph so that the centre of the screen does not need to be the position (0,0), which is the default. The LabelIncrement determines how many pixels apart the labels need to be.

If we set the draw grid flag to true, we also draw a grid, which will make it easier to see what value the graph shows.

Drawing the axes and grid works by taking the centre point and working out along each axis to the end of the screen.

Now that we have set everything up, we can draw the graph.

Here is where we use the dotMath class to parse our equation we want to draw.

So given an example equation of something like “x*x + 3 * X + 23″ or “sin(x)”, we iterate through each pixel, and get the value of x at that pixel based on the scale and offset.

We then replace the character “x” in the equation with our value for x, and pass the string to the equation parser, which then calculates the y value.

From this we can, again using the scale and offset, determine the y value of the coordinate we need.

To actually draw the point, we draw a line from the previous pixel to the current pixel which we have calculated.
continue reading…

  • Share/Bookmark

The greatest common divisor of two numbers is the largest number that divides evenly into both numbers.

The method of calculating this is is to use a little bit of recursion.

If the numbers are even, then work out the GCD by dividing both numbers by 2 and passing as parameters to the GCD function recursively, multiplying the result by 2.

If only one number is even, then pass that number divided by 2, and the whole second number to the GCD function to get the GCD.

If both numbers are odd, then call the GCS function with the average of the two numbers and the second number as the parameters.

If the numbers are equal then return that number, and if either number is equal to then return 1.

By the time execution reached the top again after the recursion, you should have the greatest common divisor as your resulting number.

        public static int GCD(int A, int B)
        {
            if (A == B)
            {
                return A;
            }
            if ((A == 1) || (B == 1))
            {
                return 1;
            }
            if ((A % 2 == 0) && (B % 2 == 0))
            {
                return 2 * GCD(A / 2, B / 2);
            }
            else if ((A % 2 == 0) && (B % 2 != 0))
            {
                return GCD(A / 2, B);
            }
            else if ((A % 2 != 0) && (B % 2 == 0))
            {
                return GCD(A, B / 2);
            }
            else
            {
                return GCD(Math.Abs(A - B) / 2, B);
            }

        }
  • Share/Bookmark

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/Bookmark

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/Bookmark

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/Bookmark

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/Bookmark

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/Bookmark