mathnet/mathnet-symbolics

How to define complex-valued functions?

sadqiang opened this issue · 2 comments

I want to create a fractal generator that works on complex values.

        var z = Expr.Variable("z");
        Func<Complex32, Complex32> f = (z * z + z - 6*cos(z*z+z-1)).Compile("z");
        Complex32 z = 2 + 3 * Complex32.ImaginaryOne;
        Console.WriteLine(f(z));

Is there any workaround to handle this?

There is a separate compilation function to compile to a function operating on complex values. Currently this only supports double precision complex numbers Complex, not single precision Complex32, but it would certainly be possible to extend the library to support also single precision in the future. This is what works for me:

using System;
using Complex = System.Numerics.Complex;
using Expr = MathNet.Symbolics.SymbolicExpression;

namespace MathNetSymbolicsCompile
{
    class Program
    {
        static void Main(string[] args)
        {
            var z = Expr.Variable("z");
            Func<Complex, Complex> f = (z * z + z - 6 * (z * z + z - 1).Cos()).CompileComplex("z");
            Complex c = 2 + 3 * Complex.ImaginaryOne;
            Console.WriteLine(f(c));
        }
    }
}

Double precision is much much better. Thank you for replying. An excellent answer!