jueves, 28 de julio de 2011

Implementing Horner Algorithm for Polynomial Evaluation in C#


Horner Algorith is considered one of the best(if not the best) methods for evaluating polynomials in monomial form. This algorithm is very efficient because it allows for quickly and very precise evaluations, saving lots of processor cycles.
 Best way to understand this method is by checking out one numerical example, the example consists of making lots of factorization of one function, until you can't anymore, then solve the factorized function for a given x value :
f(x) = 4x3 + 3x2 + 2x + 1
f(x) = (4x2 + 3x + 2)x + 1
f(x) = ((4x + 3)x + 2)x + 1
f(x) = (((4)x + 3)x + 2)x + 1
Now, let's evaluate function for x = 3:
f(x) =(((4)(3) + 3)(3) + 2)(3) + 1
f(x) = ((12 + 3)(3) + 2)(3) + 1
f(x) = ((15)(3) + 2)(3) + 1
f(x) = (45 + 2)(3) + 1
f(x) = (47)(3) + 1
f(x) = 141 + 1
f(x) = 142
Our coefficients are N1 = 4, N2 = 3, N3 = 2, N4 = 1. It was important to put all mathematical procedure in this example, because we must observe that if we factorize our function and evaluate with the resulting function, we'll do it by first multiplying N1 coefficient by x, then summing this product with N2 coefficient , multiply this sum by x again, sum this product with N3 coefficient, multiply this sum by x, and finally sum N4 coefficient and we have our result. This procedure is repetitive, it means we can easily turn it into one fully functional algorithm.
For efficient programming in C# it's a good idea to store all coefficients in one array. For example, for the given example our array would be something like: [ 4, 3, 2, 1]. Let's check out C# code:
//Made by Henry Serrano 28/7/2011
//You can use/modify code in any way you like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HornerAlgorithm
{
    class Program
    {
        static void Main(string[] args)
        {
            //coefficients of our polynomial
            //f(x) = 4x^3 + 3x^2 + 2x + 1
            double[] coefficients = new double[] { 4, 3, 2, 1};

            Console.WriteLine(horner(coefficients, 3));

            Console.ReadLine();
        }

        static double horner(double[] coefficients, double x)
        {
            double result = 0;

            //horner algorithm
            //------------------
            result = coefficients[0] * x;
            for (int i = 1; i < (coefficients.Length - 1); i++)
            {
                result += coefficients[i];
                result *= x;
            }
            result += coefficients[coefficients.Length - 1];
            //------------------

            return result;
        }
    }
}

Function "horner" is the implementation of Horner Algorithm, only requires one coefficient array and x value. There is no limit for the polynomial grade with the horner algorithm, the only trouble would be getting its coefficients. I'll attach the full project for download:

miércoles, 27 de julio de 2011

Serial Port Communication using C#


Today we'll see a very simple example of how to open a serial port , using C# and Visual Studio 2010. The example is a console program, so you won't be seeing nice user interface. It's very easy to open a serial communication, first of all, we must define which serial device we want to interact with, by example let's say we want to talk via a serial port with an Arduino board. Now, we need to define communication settings such as:
·         Baud Rate
·         Parity
·         Bit Format
·         Stop Bits
·         Port Name
Let's say we want our Baud Rate to be 9600 bps, none parity, 8-bit format, 1 stop bit. Port name is always assigned by the host computer, the name has always this format : "COMn", where "n" is the port number, automatically assigned by our computer. Because of this, it's possibly to find several serial ports assigned by our computer. So, our program will first check out all available serial ports, and let us choose which to open.  After opening the port we will be able to send text to it, just by writing our message in the console, while doing this our program can asynchronously receive data from or serial device.
The code is as follows:
//Made by Henry Serrano 27/7/2011
//You can use/modify the code in any way you like,
//just remember to share it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports; //required for SerialPort class

namespace SerialPortCommunicationExample
{
    class Program
    {
        static SerialPort port1;
        static Boolean portstate = false;

        static void Main(string[] args)
        {
            Console.WriteLine("SerialPort Communication Example\n");
            Console.WriteLine("Open a port communication,");
            Console.WriteLine("then, start sending or receiving messages\n");

            chooseSerialPort();
            while (portstate == true)
            {
                port1.WriteLine(Console.ReadLine());
            }
            Console.ReadLine();
        }

        static void chooseSerialPort()
        {
            //store all available port names
            string[] ports = SerialPort.GetPortNames();
            int i = 1;

            Console.WriteLine("Choose Serial Port");
            foreach (string portname in ports)
            {
                //write all available port names
                Console.WriteLine(i.ToString() + " " + portname);
                i++;
            }

            Console.WriteLine("\nWrite number corresponding to SerialPort");

            i = Convert.ToInt16(Console.ReadLine());

            try
            {
                //create serial port as configured below
                //BaudRate = 9600 bps, Parity:None, 8-bit data, 1 Stop-bit
                port1 = new SerialPort(ports[i - 1], 9600, Parity.None, 8, StopBits.One);

                //create asynchronous event(it's a secondary threat of the main program)
                //will activate every time our serial device sends data to computer
                port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);
                //finally open port
                port1.Open();
                portstate = true;
                Console.WriteLine(ports[i-1] + " is now open");
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open Port");
            }
           
        }

        static void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Console.WriteLine("Received: " + port1.ReadLine());
        }
    }

This is a functional Arduino code for using with this program:
//Made by Henry Serrano 27/7/2011
//You can use/modify the code in any way you like,
//just remember to share it

const int buffersize = 64;
unsigned char buffer[buffersize]; //64 character buffer

void setup(){
  Serial.begin(9600);
}

void loop(){
  if(Serial.available() > 0){
    int i = 0;
    unsigned char data = 0;
     while(Serial.available() > 0){
       data = Serial.read();
       if(i < buffersize){
        buffer[i] = data; //put all data into buffer until if fills
        i++;
       }
     }
     for(int j = 0; j < i; j++){
       Serial.print(buffer[j]); //print buffer characters
     }
  }
  //delay(10);
}
Code is considerably commented, I'll add here the full project for download. I'll also add the Arduino sketch for quickly use with this program. It's considerably easy and recommended to optimize this code for your personal goals.