mathnet / mathnet-symbolics

Math.NET Symbolics
http://symbolics.mathdotnet.com
MIT License
341 stars 66 forks source link

How to define complex-valued functions? #67

Closed sadqiang closed 5 years ago

sadqiang commented 5 years ago

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?

cdrnet commented 5 years ago

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));
        }
    }
}
sadqiang commented 5 years ago

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