<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Centre of the Universe &#187; Mathematics</title>
	<atom:link href="http://www.sergemeunier.com/blog/category/mathematics/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sergemeunier.com/blog</link>
	<description>The musings of a mad software developer</description>
	<lastBuildDate>Tue, 01 Jun 2010 20:26:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A mathematical graphing application in C#</title>
		<link>http://www.sergemeunier.com/blog/a-mathematical-graphing-application-in-c-sharp/</link>
		<comments>http://www.sergemeunier.com/blog/a-mathematical-graphing-application-in-c-sharp/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 12:27:16 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1197</guid>
		<description><![CDATA[Creating 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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.sergemeunier.com/blog/wp-content/uploads/2009/10/grapher-289x300.jpg" alt="Grapher" title="Grapher" width="289" height="300" class="alignright size-medium wp-image-1199" />Creating an application to draw graphs of mathematical equations has two components to it, namely, parsing the equation and drawing the results.</p>
<p>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 <a href="http://www.codeplex.com/dotMath"></a>. Rather than write my own library, I used this library to do all the parsing for me.</p>
<p>The fun part &#8211; for me anyway &#8211; 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.</p>
<p>The actual generation of the image we are going to draw happens using a <strong>Bitmap</strong> object. </p>
<p>We set up the pens and brushes we need for the axis, graph, grid and background using the configuration settings that the class contains.</p>
<p>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.</p>
<p>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.</p>
<p>Drawing the axes and grid works by taking the centre point and working out along each axis to the end of the screen.</p>
<p>Now that we have set everything up, we can draw the graph.</p>
<p>Here is where we use the <strong>dotMath</strong> class to parse our equation we want to draw. </p>
<p>So given an example equation of something like &#8220;x*x + 3 * X + 23&#8243; or &#8220;sin(x)&#8221;, we iterate through each pixel, and get the value of x at that pixel based on the scale and offset.</p>
<p>We then replace the character &#8220;x&#8221; in the equation with our value for x, and pass the string to the equation parser, which then calculates the y value.</p>
<p>From this we can, again using the scale and offset, determine the y value of the coordinate we need.</p>
<p>To actually draw the point, we draw a line from the previous pixel to the current pixel which we have calculated.<br />
<span id="more-1197"></span></p>
<p>Here is the code for the graph drawing class. The full code is available <a href="http://www.sergemeunier.com/blog/downloads/GrapherSource.zip">here</a></p>
<pre name="code" class="c-sharp">
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace EquationGrapher
{
    public partial class Graph : UserControl
    {
        public Color axisColor = Color.Black;
        public Color drawColor = Color.Red;
        public Color gridColor = Color.LightGray;
        public Color backgroundColor = Color.White;
        public int axisFontSize = 5;
        public Boolean drawAxes = true;
        public Boolean drawGrid = true;

        public Graph()
        {
            InitializeComponent();
        }

        public Bitmap GenerateGraph(string equation, double xScale, double yScale, double xOffset, double yOffset, double xLabelIncrement, double yLabelIncrement, int width, int height)
        {
            Bitmap image = new Bitmap(width, height);
            int midX = width / 2;
            int midY = height / 2;

            Graphics g = Graphics.FromImage(image);
            SolidBrush backgroundBrush = new SolidBrush(backgroundColor);
            SolidBrush axisBrush = new SolidBrush(axisColor);
            SolidBrush drawBrush = new SolidBrush(drawColor);
            SolidBrush gridBrush = new SolidBrush(gridColor);

            Pen drawPen = new Pen(drawColor);
            Pen axisPen = new Pen(axisColor);
            Pen gridPen = new Pen(gridColor);
            Font axisFont = new Font(FontFamily.GenericSansSerif, axisFontSize);
            //Clear background
            g.FillRectangle(backgroundBrush, 0, 0, width, height);

            //Draw Axes
            if (drawAxes)
            {
                g.DrawLine(axisPen, 0, midY, width, midY);
                g.DrawLine(axisPen, midX, 0, midX, height);

                //draw labels
                float xIncrementSize = (float)(xScale * xLabelIncrement);

                float curX = midX;
                while (curX < width)
                {
                    if (curX != midX)
                    {
                        if (drawGrid)
                        {
                            g.DrawLine(gridPen, curX, 0, curX, height);
                        }
                        g.DrawLine(axisPen, curX, midY, curX, midY + 3);
                        g.DrawString(Math.Round((curX - midX) * xScale + xOffset, 2).ToString(), axisFont, axisBrush, curX - 3, midY + 5);
                    }
                    curX += xIncrementSize;
                }
                curX = midX;
                while (curX > 0)
                {
                    if (curX != midX)
                    {
                        if (drawGrid)
                        {
                            g.DrawLine(gridPen, curX, 0, curX, height);
                        }
                        g.DrawLine(axisPen, curX, midY, curX, midY + 3);
                        g.DrawString(Math.Round((curX - midX) * xScale + xOffset, 2).ToString(), axisFont, axisBrush, curX - 3, midY + 5);
                    }
                    curX -= xIncrementSize;

                }

                float yIncrementSize = (float)(yScale * yLabelIncrement);

                float curY = midY;
                while (curY < height)
                {
                    if (curY != midY)
                    {
                        if (drawGrid)
                        {
                            g.DrawLine(gridPen, 0, curY, width, curY);
                        }
                        g.DrawLine(axisPen, midX, curY, midX + 3, curY);
                        g.DrawString(Math.Round(((curY - midY) * yScale + yOffset) * -1, 2).ToString(), axisFont, axisBrush, midX + 5, curY - 3);
                    }
                    curY += yIncrementSize;
                }
                curY = midY;
                while (curY > 0)
                {
                    if (curY != midY)
                    {
                        if (drawGrid)
                        {
                            g.DrawLine(gridPen, 0, curY, width, curY);
                        }
                        g.DrawLine(axisPen, midX, curY, midX + 3, curY);
                        g.DrawString(Math.Round(((curY - midY) * yScale + yOffset) * -1, 2).ToString(), axisFont, axisBrush, midX + 5, curY - 3);
                    }
                    curY -= yIncrementSize;
                }

            }

            //Draw graph
            float prevX = 0;
            float prevY = 0;
            double x = 0;
            double y = 0;
            float xImage = 0;
            float yImage = 0;
            string filledEquation = "";

            for (int i = 0; i < width; i++)
            {
                x = ((double)(i - midX) * xScale) + xOffset;

                filledEquation = equation.Replace("x", x.ToString());
                dotMath.EqCompiler equationCompiler = new dotMath.EqCompiler(filledEquation, true);
                equationCompiler.Compile();
                y = equationCompiler.Calculate() + yOffset;

                xImage = i;
                yImage = (int)(y * (-1) / yScale) + midY;
                if (i > 0)
                {
                    g.DrawLine(drawPen, prevX, prevY, xImage, yImage);
                }
                prevX = xImage;
                prevY = yImage;
            }
            return image;
        }
        public void DrawGraph(string equation, double xScale, double yScale, double xOffset, double yOffset, double xLabelIncrement, double yLabelIncrement)
        {
            picGraph.Image = GenerateGraph(equation, xScale, yScale, xOffset, yOffset, xLabelIncrement, yLabelIncrement, picGraph.Width, picGraph.Height);
        }
    }
}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fa-mathematical-graphing-application-in-c-sharp%2F&amp;linkname=A%20mathematical%20graphing%20application%20in%20C%23"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/t-square-fractals/' rel='bookmark' title='Permanent Link: Fractals in C#: T-Square fractals'>Fractals in C#: T-Square fractals</a> <small>A T-Square fractal is a relatively simple affair. The procedure...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/a-mathematical-graphing-application-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mathematical algorithms in c#: Finding the greatest common divisor</title>
		<link>http://www.sergemeunier.com/blog/mathematical-algorithms-in-c-sharp-finding-the-greatest-common-divisor/</link>
		<comments>http://www.sergemeunier.com/blog/mathematical-algorithms-in-c-sharp-finding-the-greatest-common-divisor/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 06:10:05 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1141</guid>
		<description><![CDATA[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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/finding-the-prime-factors-of-a-number-in-c-sharp/' rel='bookmark' title='Permanent Link: Finding the prime factors of a number in C#'>Finding the prime factors of a number in C#</a> <small>A prime number is any number that can only be...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-median/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The median'>Maths algorithms in C#: The median</a> <small>The median is defined as the data point that falls...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-geometric-mean/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The geometric mean'>Maths algorithms in C#: The geometric mean</a> <small>The geometric mean is similar to the arithmetic mean in...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>The greatest common divisor of two numbers is the largest number that divides evenly into both numbers.</p>
<p>The method of calculating this is is to use a little bit of recursion.</p>
<p>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.</p>
<p>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.</p>
<p>If both numbers are odd, then call the GCS function with the average of the two numbers and the second number as the parameters.</p>
<p>If the numbers are equal then return that number, and if either number is equal to  then return 1.</p>
<p>By the time execution reached the top again after the recursion, you should have the greatest common divisor as your resulting number.</p>
<pre name="code" class="c-sharp">
        public static int GCD(int A, int B)
        {
            if (A == B)
            {
                return A;
            }
            if ((A == 1) || (B == 1))
            {
                return 1;
            }
            if ((A % 2 == 0) &#038;&#038; (B % 2 == 0))
            {
                return 2 * GCD(A / 2, B / 2);
            }
            else if ((A % 2 == 0) &#038;&#038; (B % 2 != 0))
            {
                return GCD(A / 2, B);
            }
            else if ((A % 2 != 0) &#038;&#038; (B % 2 == 0))
            {
                return GCD(A, B / 2);
            }
            else
            {
                return GCD(Math.Abs(A - B) / 2, B);
            }

        }
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fmathematical-algorithms-in-c-sharp-finding-the-greatest-common-divisor%2F&amp;linkname=Mathematical%20algorithms%20in%20c%23%3A%20Finding%20the%20greatest%20common%20divisor"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/finding-the-prime-factors-of-a-number-in-c-sharp/' rel='bookmark' title='Permanent Link: Finding the prime factors of a number in C#'>Finding the prime factors of a number in C#</a> <small>A prime number is any number that can only be...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-median/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The median'>Maths algorithms in C#: The median</a> <small>The median is defined as the data point that falls...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-geometric-mean/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The geometric mean'>Maths algorithms in C#: The geometric mean</a> <small>The geometric mean is similar to the arithmetic mean in...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/mathematical-algorithms-in-c-sharp-finding-the-greatest-common-divisor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finding the prime factors of a number in C#</title>
		<link>http://www.sergemeunier.com/blog/finding-the-prime-factors-of-a-number-in-c-sharp/</link>
		<comments>http://www.sergemeunier.com/blog/finding-the-prime-factors-of-a-number-in-c-sharp/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 11:15:35 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1121</guid>
		<description><![CDATA[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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mathematical-algorithms-in-c-sharp-finding-the-greatest-common-divisor/' rel='bookmark' title='Permanent Link: Mathematical algorithms in c#: Finding the greatest common divisor'>Mathematical algorithms in c#: Finding the greatest common divisor</a> <small>The greatest common divisor of two numbers is the largest...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-bearing-between-two-gps-coordinates/' rel='bookmark' title='Permanent Link: Finding the bearing between two GPS coordinates'>Finding the bearing between two GPS coordinates</a> <small>Don&#8217;t you think it would be really great to be...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-midpoint-of-two-coordinates/' rel='bookmark' title='Permanent Link: Finding the midpoint of two coordinates'>Finding the midpoint of two coordinates</a> <small>Previously I showed how to find the distance between coordinates...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<p>Then, starting at 3, and counting up in 2&#8217;s, we try and find a number which divides into the number, each time dividing by the divisor if a match is found.</p>
<pre name="code" class="c-sharp">
 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;
        }
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Ffinding-the-prime-factors-of-a-number-in-c-sharp%2F&amp;linkname=Finding%20the%20prime%20factors%20of%20a%20number%20in%20C%23"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/mathematical-algorithms-in-c-sharp-finding-the-greatest-common-divisor/' rel='bookmark' title='Permanent Link: Mathematical algorithms in c#: Finding the greatest common divisor'>Mathematical algorithms in c#: Finding the greatest common divisor</a> <small>The greatest common divisor of two numbers is the largest...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-bearing-between-two-gps-coordinates/' rel='bookmark' title='Permanent Link: Finding the bearing between two GPS coordinates'>Finding the bearing between two GPS coordinates</a> <small>Don&#8217;t you think it would be really great to be...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-midpoint-of-two-coordinates/' rel='bookmark' title='Permanent Link: Finding the midpoint of two coordinates'>Finding the midpoint of two coordinates</a> <small>Previously I showed how to find the distance between coordinates...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/finding-the-prime-factors-of-a-number-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Combinations, permutations and factorials in C#</title>
		<link>http://www.sergemeunier.com/blog/combinations-permutations-and-factorials-in-c-sharp/</link>
		<comments>http://www.sergemeunier.com/blog/combinations-permutations-and-factorials-in-c-sharp/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 06:46:37 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1113</guid>
		<description><![CDATA[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 &#8211; 1) * (n &#8211; 2) &#8230; 2 * 1.
This is a very easy function to write.

        public static long [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-arithmetic-mean/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The Arithmetic mean'>Maths algorithms in C#: The Arithmetic mean</a> <small>The arithmetic mean is defined as the average of a...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-median/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The median'>Maths algorithms in C#: The median</a> <small>The median is defined as the data point that falls...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Factorials are defined as a number that is multiplied by every positive number below it, and is denoted by an exclamation mark, ie <em>n! = n * (n &#8211; 1) * (n &#8211; 2) &#8230; 2 * 1</em>.</p>
<p>This is a very easy function to write.</p>
<pre name="code" class="c-sharp">
        public static long Factorial(int num)
        {
            long fact = 1;
            for (int i = 2; i <= num; i++)
            {
                fact = fact * i;
            }
            return fact;
        }
</pre>
<p>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.</p>
<p>So, given a set of values of size <em>n</em>, if you select <em>r</em> items from the set, the number of different combinations which you can select is given by the formula<br />
<em>C = n! / r!(n - r)!</e></p>
<p>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.</p>
<pre name="code" class="c-sharp">
        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;
        }
</pre>
<p>Permutations are a little simpler than combinations. In this case, you still selecting <em>r</em> items out of a set of <em>n</em> 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.<br />
<em>C = n! / (n - r)!</e></p>
<pre name="code" class="c-sharp">
        public static int Permutation(int n, int r)
        {
            int Perm = 0;
            Perm = (int)(MathExt.Factorial(n) / MathExt.Factorial(n - r));
            return Perm;
        }
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fcombinations-permutations-and-factorials-in-c-sharp%2F&amp;linkname=Combinations%2C%20permutations%20and%20factorials%20in%20C%23"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-arithmetic-mean/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The Arithmetic mean'>Maths algorithms in C#: The Arithmetic mean</a> <small>The arithmetic mean is defined as the average of a...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-the-median/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: The median'>Maths algorithms in C#: The median</a> <small>The median is defined as the data point that falls...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/combinations-permutations-and-factorials-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Vectors in C#</title>
		<link>http://www.sergemeunier.com/blog/vectors-in-c-sharp/</link>
		<comments>http://www.sergemeunier.com/blog/vectors-in-c-sharp/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 06:11:00 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1108</guid>
		<description><![CDATA[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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/matrices-in-c-sharp/' rel='bookmark' title='Permanent Link: Matrices in C#'>Matrices in C#</a> <small>Matrices are a very useful thing in computer programming &#8211;...</small></li>
<li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-bearing-between-two-gps-coordinates/' rel='bookmark' title='Permanent Link: Finding the bearing between two GPS coordinates'>Finding the bearing between two GPS coordinates</a> <small>Don&#8217;t you think it would be really great to be...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://en.wikipedia.org/wiki/Vector_%28mathematics_and_physics%29">wikipedia</a>.</p>
<p>Implementing a vector class in C# is pretty easy.</p>
<p>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.</p>
<p>The <strong>Zero()</strong> function sets the entire vector to 0.</p>
<p>The <strong>Abs()</strong> 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.</p>
<p>The <strong>Dot()</strong> 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.</p>
<p>The <strong>Scale()</strong> function scales the vector by the scaling factor supplied.</p>
<p>The <strong>+</strong> and <strong>-</strong> operators are overloaded to make it easy to add and subtract vectors.</p>
<p>Each component of first vector is added (or subtracted) to the equivalent component of the second vector, and then the resulting vector is returned.</p>
<p><span id="more-1108"></span></p>
<pre name="code" class="c-sharp">
namespace MathLib
{
    public class Vector
    {
        public double[] vectorArray;
        public int Dimension;

        public Vector(double[] Values)
        {
            vectorArray = Values;
            Dimension = vectorArray.GetLength(0);
        }

        public Vector(int dim)
        {
            vectorArray = new double[dim];
            Dimension = dim;
            Zero();
        }

        public void Zero()
        {
            for(int i = 0; i < Dimension; i++)
            {
                vectorArray[i] = 0;
            }
        }

        public double Abs()
        {
            double abs = 0;

            for (int i = 0; i < Dimension; i++)
            {
                abs += vectorArray[i] * vectorArray[i];
            }
            return Math.Sqrt(abs);
        }

        public double Dot(Vector vector)
        {
            if (vector.Dimension != Dimension)
            {
                return 0;
            }
            double dotProd = 0;
            for (int i = 0; i < Dimension; i++)
            {
                dotProd += vectorArray[i] * vector.vectorArray[i];
            }
            return dotProd;
        }

        public Vector Scale(double factor)
        {
            double[] values = new double[Dimension];

            for (int i = 0; i < Dimension; i++)
            {
                values[i] = vectorArray[i] * factor;
            }
            return new Vector(values);
        }

        public override string ToString()
        {
            string str = "";
            for (int i = 0; i < Dimension; i++)
            {
                if (i != 0)
                {
                    str += ", ";
                }
                str += vectorArray[i];
            }
            return "(" + str + ")";
        }

        public static Vector operator +(Vector left, Vector right)
        {
            if (left.Dimension != right.Dimension)
            {
                return left;
            }
            double[] values = new double[left.Dimension];

            for (int i = 0; i < left.Dimension; i++)
            {
                values[i] = left.vectorArray[i] + right.vectorArray[i];
            }
            return (new Vector(values));
        }

        public static Vector operator -(Vector left, Vector right)
        {
            if (left.Dimension != right.Dimension)
            {
                return left;
            }
            double[] values = new double[left.Dimension];

            for (int i = 0; i < left.Dimension; i++)
            {
                values[i] = left.vectorArray[i] - right.vectorArray[i];
            }
            return (new Vector(values));
        }

    }
}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fvectors-in-c-sharp%2F&amp;linkname=Vectors%20in%20C%23"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/matrices-in-c-sharp/' rel='bookmark' title='Permanent Link: Matrices in C#'>Matrices in C#</a> <small>Matrices are a very useful thing in computer programming &#8211;...</small></li>
<li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-bearing-between-two-gps-coordinates/' rel='bookmark' title='Permanent Link: Finding the bearing between two GPS coordinates'>Finding the bearing between two GPS coordinates</a> <small>Don&#8217;t you think it would be really great to be...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/vectors-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Matrices in C#</title>
		<link>http://www.sergemeunier.com/blog/matrices-in-c-sharp/</link>
		<comments>http://www.sergemeunier.com/blog/matrices-in-c-sharp/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 05:10:04 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1103</guid>
		<description><![CDATA[Matrices are a very useful thing in computer programming &#8211; 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 &#8211; wikipedia can tell you [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/vectors-in-c-sharp/' rel='bookmark' title='Permanent Link: Vectors in C#'>Vectors in C#</a> <small>A vector is simply a 1-dimensional array of numbers that...</small></li>
<li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-bearing-between-two-gps-coordinates/' rel='bookmark' title='Permanent Link: Finding the bearing between two GPS coordinates'>Finding the bearing between two GPS coordinates</a> <small>Don&#8217;t you think it would be really great to be...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Matrices are a very useful thing in computer programming &#8211; 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.</p>
<p>I am not going to go into major detail over what a matrix is &#8211; <a href="http://en.wikipedia.org/wiki/Matrix_%28mathematics%29">wikipedia</a> can tell you that much better than I can &#8211; so will focus mainly on how to implement one in C#.</p>
<p>Essentially, a matrix is a 2-dimensional array of numbers, often representing a set of equations. The number of columns and rows is flexible.</p>
<p>Using the <strong>Matrix</strong> 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.</p>
<p>The <strong>Zero()</strong> function sets all entries in the matrix to zero by looping through the entire array.</p>
<p>The <strong>SetIdentity()</strong> 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.</p>
<p>The <strong>Transpose</strong> function transforms the columns of the matrix into the rows, and vice versa. </p>
<p>The <strong>Scale</strong> function multiplies each value in the matrix by a scaling factor.</p>
<p>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 <strong>Determinant</strong> function</p>
<p>The <strong>Trace</strong> function returns the sum of the main diagonal of the matrix.</p>
<p>The matrix class has also got a few overloaded operators, to make handling matrices easier.</p>
<p>The <strong>+</strong> 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.</p>
<p>A second overload for the <strong>+</strong> operator takes a scalar value and adds it to the matrix, which just adds that value to each value in the matrix.</p>
<p>The <strong>-</strong> operator performs identically to the + operator, except that it subtracts instead of adds the matrices.</p>
<p>The <strong>*</strong> operator multiplies the two matrices together, which is a little more involved than addition. </p>
<p><span id="more-1103"></span></p>
<pre name="code" class="c-sharp">
namespace MathLib
{
    public class Matrix
    {
        public double[,] val;
        public int Cols;
        public int Rows;

        public Matrix(int X, int Y)
        {
            Cols = X;
            Rows = Y;
            val = new double[Rows, Cols];
            Zero();
        }

        public Matrix(double[,] array)
        {
            val = array;
            Cols = val.GetLength(1);
            Rows = val.GetLength(0);
        }

        public void Zero()
        {
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    val[i, j] = 0;
                }
            }
        }
        public void SetIdentity()
        {
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    if (i == j)
                    {
                        val[i, j] = 1;
                    }
                    else
                    {
                        val[i, j] = 0;
                    }
                }
            }
        }
        public Matrix Transpose()
        {
            double[,] values = new double[Cols, Rows];
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    values[j, i] = val[i, j];
                }
            }
            return new Matrix(values);
        }

        public Matrix Scale(double factor)
        {
            double[,] values = new double[Rows, Cols];
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    values[i, j] = factor * val[i, j];
                }
            }
            return new Matrix(values);
        }

        public double Determinant()
        {
            double det = 0;
            int colIndex = 0;
            double dval = 1;
            int k;
            for (int i = 0; i < Cols; i++)
            {
                k = 0;
                dval = 1;
                for (int j = 0; j < Cols; j++)
                {
                    colIndex = (i + j) % 3;
                    dval *= val[colIndex, k];
                    k++;
                }
                det += dval;
            }
            for (int i = 0; i < Cols; i++)
            {
                k = 0;
                dval = 1;
                for (int j = Cols-1; j >= 0; j--)
                {
                    colIndex = (i + j) % 3;
                    val *= dval[colIndex, k];
                    k++;
                }
                det -= dval;
            }

            return det;
        }
        public double Trace()
        {
            if (Rows != Cols)
            {
                return 0;
            }
            double trace = 0;
            for (int i = 0; i < Rows; i++)
            {

               trace += val[i, i];
            }
            return trace;
        }

        public override string ToString()
        {
            string str = "";
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    str += val[i, j].ToString() + ",";
                }
                str += Environment.NewLine;
            }
            return str;
        }

        public static Matrix operator +(Matrix left, Matrix right)
        {
            if ((left.Cols != right.Cols) || (left.Rows != right.Rows))
            {
                return left;
            }
            double[,] values = new double[left.Rows, left.Cols];

            for (int i = 0; i < left.Rows; i++)
            {
                for (int j = 0; j < left.Cols; j++)
                {
                    values[i,j] = left.val[i,j] + right.val[i,j];
                }
            }
            return (new Matrix(values));
        }

        public static Matrix operator +(double left, Matrix right)
        {
            double[,] values = new double[right.Rows, right.Cols];

            for (int i = 0; i < right.Rows; i++)
            {
                for (int j = 0; j < right.Cols; j++)
                {
                    values[i, j] = left + right.val[i, j];
                }
            }
            return (new Matrix(values));
        }

        public static Matrix operator -(Matrix left, Matrix right)
        {
            if ((left.Cols != right.Cols) || (left.Rows != right.Rows))
            {
                return left;
            }
            double[,] values = new double[left.Cols, left.Rows];

            for (int i = 0; i < left.Rows; i++)
            {
                for (int j = 0; j < left.Cols; j++)
                {
                    values[i, j] = left.val[i, j] - right.val[i, j];
                }
            }
            return (new Matrix(values));
        }

        public static Matrix operator *(Matrix left, Matrix right)
        {
            double[,] values = new double[left.Rows, right.Cols];

            for (int h = 0; h < left.Rows; h++)
            {
                for (int i = 0; i < right.Cols; i++)
                {
                    for (int j = 0; j < left.Cols; j++)
                    {
                            values[h, i] += left.val[h, j] * right.val[j, i];
                    }
                }
            }
            return (new Matrix(values));
        }

    }
}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fmatrices-in-c-sharp%2F&amp;linkname=Matrices%20in%20C%23"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/vectors-in-c-sharp/' rel='bookmark' title='Permanent Link: Vectors in C#'>Vectors in C#</a> <small>A vector is simply a 1-dimensional array of numbers that...</small></li>
<li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/finding-the-bearing-between-two-gps-coordinates/' rel='bookmark' title='Permanent Link: Finding the bearing between two GPS coordinates'>Finding the bearing between two GPS coordinates</a> <small>Don&#8217;t you think it would be really great to be...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/matrices-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solving quadratic equation roots in C#</title>
		<link>http://www.sergemeunier.com/blog/solving-quadratic-equation-roots-in-c-sharp/</link>
		<comments>http://www.sergemeunier.com/blog/solving-quadratic-equation-roots-in-c-sharp/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 05:50:03 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1100</guid>
		<description><![CDATA[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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>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. </p>
<p>Fortunately, computers are not scared by numbers that are difficult, and can solve quadratics quite well.</p>
<p>The function below solves quadratics in the form of Ax<sup>2</sip> + 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.</p>
<pre name="code" class="c-sharp">
		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;
			}
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fsolving-quadratic-equation-roots-in-c-sharp%2F&amp;linkname=Solving%20quadratic%20equation%20roots%20in%20C%23"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/complex-numbers-in-c-sharp/' rel='bookmark' title='Permanent Link: Complex numbers in C#'>Complex numbers in C#</a> <small>Complex numbers are a vital part of many mathematical calculations,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/solving-quadratic-equation-roots-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maths alogrithms in C#: Least squares fit using full logs</title>
		<link>http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/</link>
		<comments>http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 05:31:40 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1096</guid>
		<description><![CDATA[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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log ordinate'>Maths algorithms in C#: Least squares fit with a log ordinate</a> <small>We have already looked at the linear least squares fit,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>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*x<sup>M</sup>, using the least squares method.</p>
<p>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.</p>
<pre name="code" class="c-sharp">
		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;
			}
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fmaths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs%2F&amp;linkname=Maths%20alogrithms%20in%20C%23%3A%20Least%20squares%20fit%20using%20full%20logs"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log ordinate'>Maths algorithms in C#: Least squares fit with a log ordinate</a> <small>We have already looked at the linear least squares fit,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Maths algorithms in C#: Least squares fit with a log abscissa</title>
		<link>http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/</link>
		<comments>http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 05:25:30 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1094</guid>
		<description><![CDATA[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 [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log ordinate'>Maths algorithms in C#: Least squares fit with a log ordinate</a> <small>We have already looked at the linear least squares fit,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>The function below finds M and B, and if no solution exists, it returns 0 for both these values.</p>
<pre name="code" class="c-sharp">
		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;
			}
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fmaths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa%2F&amp;linkname=Maths%20algorithms%20in%20C%23%3A%20Least%20squares%20fit%20with%20a%20log%20abscissa"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log ordinate'>Maths algorithms in C#: Least squares fit with a log ordinate</a> <small>We have already looked at the linear least squares fit,...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Maths algorithms in C#: Least squares fit with a log ordinate</title>
		<link>http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/</link>
		<comments>http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 05:21:00 +0000</pubDate>
		<dc:creator>Serge Meunier</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.sergemeunier.com/blog/?p=1090</guid>
		<description><![CDATA[We have already looked at the linear least squares fit, but that does not always produces a nice fit to the data. The least squares fit with a log ordinate tries to match up the data to the equation y  = B * 10Mx using the least squares method.
In the code below, if there [...]


Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
</ol>

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>We have already looked at the <a href="http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/">linear least squares fit</a>, but that does not always produces a nice fit to the data. The least squares fit with a log ordinate tries to match up the data to the equation y  = B * 10<sup>M<sup>x</sup></sup> using the least squares method.</p>
<p>In the code below, if there is no solution, the function returns M and B as 0.</p>
<pre name="code" class="c-sharp">
		public static void LeastSquaresFitLogOrdinate(Pnt[] points, int numPoints, ref double M, ref double B)
		{
			//Gives best fit of data to curve Y = B*(10^M)^X

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

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

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

			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;
			}
		}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.sergemeunier.com%2Fblog%2Fmaths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate%2F&amp;linkname=Maths%20algorithms%20in%20C%23%3A%20Least%20squares%20fit%20with%20a%20log%20ordinate"><img src="http://www.sergemeunier.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-abscissa/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Least squares fit with a log abscissa'>Maths algorithms in C#: Least squares fit with a log abscissa</a> <small>This algorithm for the least squares fit uses a logarithmic...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/' rel='bookmark' title='Permanent Link: Maths algorithms in C#: Linear least squares fit'>Maths algorithms in C#: Linear least squares fit</a> <small>When analysing data it is often useful to find an...</small></li>
<li><a href='http://www.sergemeunier.com/blog/maths-alogrithms-in-c-sharp-least-squares-fit-using-full-logs/' rel='bookmark' title='Permanent Link: Maths alogrithms in C#: Least squares fit using full logs'>Maths alogrithms in C#: Least squares fit using full logs</a> <small>We have already looked at several other ways of doing...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.sergemeunier.com/blog/maths-algorithms-in-c-sharp-least-squares-fit-with-a-log-ordinate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
