After reading a post from Phil Haack on number systems I decided to start a little series on my favorite maths topic, complex numbers. Here is some basic info:
Real numbers are pretty much every number you can think of:
26, ⅘, √22, 11.23, 7² etc.
Think about that last number, as we know all squares are positive. In this case it would equal 49, if it was -7² it would still equal 49 (from basic maths: –ve * -ve = positive). So by extension -7 = 7 which is not true and √-49 cannot be calculated because you could never have had a –ve result. (try it in a calculator!)
Enter imaginary numbers: if you think about breaking real numbers into units of 1 the same can be done with imaginary numbers, √-1. We call this i and this is the basis for complex numbers. I.e. i = √-1
A complex number is a real number and an imaginary number together.
7 + 4i
An interesting thing here is that the imaginary part can be 0 so theoretically real numbers are also complex numbers – one of the many confusing by-products of mathematics. I.e. 7 + 0
Some real life uses -More to come in the next blog
• Differential equations – Electronics and engineering
• Fluid dynamics
• Any series or model that contains a value of √-1
Some fun uses:
The Mandelbrot Set is a fractal that when drawn looks amazing. It uses the simple formula:
The drawing engine:
namespace Mandlebrot { public interface IMandelBrot { Bitmap Draw(int width, int height, double rMin, double rMax, double imaginaryMin, double imaginaryMax); } public class MandelBrot : IMandelBrot { public Bitmap Draw(int width, int height, double realMin, double realMax, double imaginaryMin, double imaginaryMax) { var palette = GetPalette(); var img = new FastBitmap(width, height); //real number double real = (Math.Abs(realMin) + Math.Abs(realMax)) / width; //imaginary numbers double imaginary = (Math.Abs(imaginaryMin) + Math.Abs(imaginaryMax)) / height; for (int xCoordinate = 0; xCoordinate < width; xCoordinate++) { for (int yCoordinate=0; yCoordinate < height; yCoordinate++) { var complex = new Complex(xCoordinate * real + realMin, yCoordinate * imaginary + imaginaryMin); var z = complex; foreach (Color c in palette) { if (z.Magnitude >= 2.0) { img.SetPixel(xCoordinate, yCoordinate, c); break; } z = complex + Complex.Pow(z, 2); // Z = c + z^2 (Mandlebrot formula) } } } return img.Bitmap; } public List<Color> GetPalette() { var retVal = new List<Color>(); for (int i = 0; i <= 255; i++) { //I just stuff around here with the colors -have a play var alpha = i < 250 ? i + 4 : i; var red = i < 250 ? i + 4 : i; var green = i < 240 ? i + 14 : i; var blue = i < 200 ? i + 54 : i; ; retVal.Add(Color.FromArgb(alpha, red, green, blue)); } return retVal; } } } //call var bitmap = new MandelBrot().Draw(300, 300, -2.5, 1.0, -1.0, 1.0);
You will also need the SetPixel method which was a rewrite of the slow .Net one. (Thanks John Parsons)