Here you go: a simple but mathematically rigorous implementation of complex numbers in one small C# library. No problem in square rooting negative numbers anymore!
- Absolute value
- Exponential function
- Hyperbolic functions (Sinh, Cosh, Tanh, Coth, Sech, Csch)
- Square root
Using the code
Either add a reference to CompLib.dll to your project, or directly use the class Complex.cs within your project.
The actual usage is intuitive:
Complex I = Complex.I; Complex a = new Complex(1, 3); Complex a2 = 1 + 3 * I;
Complex z = Complex.Pow((Complex.Sin(1/(1+I))), 1/3);
Points of interest
One more thing: Complex logarithm is not a unique operation; the main value is computed as is common in the CAS world. E.g., the equation z^4 = -1 has four complex solutions, but only one is returned when trying "
z = Complex.Sqrt(Complex.Sqrt(-1));" (as does Maple, for instance). This is due to the computation of the exponentiation:
Pow(a,b) := Exp(b * Log(a))
- init complex number with format string such as "3+4i" using regex.
Update July 3, 2007 #2
- Major bug in Arg() fixed (thanks Petr Stanislav!); this affects
Update July 3, 2007
- Added hyperbolic functions.
Update June 10, 2007
- Replaced ^-operator with "
public static Complex Pow", similar to
Update June 7, 2007
One as constants (e.g., use "
Complex z = Complex.One;" instead of "
Complex z = new Complex(1)").
- Major bug of division operation removed (using
a/b = a*Conj(b)*(1/(Abs(b)*Abs(b)) now).
ToString method bug fixed.