Class that handles complex numbers?

Hi, I searched the Unity docs for complex numbers and couldn’t find any class that handled them. I wanted to build a mandelbrot set within unity using one of the many ready-made algorithms found online. Problem is they use complex numbers in their calculations.

I tried importing the .Net Systems.Numeric namespace which has a complex numbers class but apparently this namespace is not compatible with Unity.

Any help is appreciated.

System.Numerics is .Net 4.0 and newer. Unity supports .Net 3.5 equivalent (mono).

There are third party implementations of complex numbers out there. Don’t search with Unity, just search with ‘mono’ or ‘.net’ in mind.

Such as this one:
http://numerics.mathdotnet.com/

1 Like

You can make mandelbrot without complex numbers, just treat i as -1

    Texture2D tex;
    int texSize = 512;

    //to navigate the number space
    Vector2 center;
    float size;

    void UpdateTex () {
        float xStep = size * 2 / texSize;
        float yStep = size * 2 / texSize;

        int minIteration = int.MaxValue;
        int maxInteration = 0;

        Color32[] cols = new Color32[texSize * texSize];

        for ( int y = 0; y < texSize; y++ ) {
            double Y = center.y - size + y * yStep;
            for ( int x = 0; x < texSize; x++ ) {
                double X = center.x - size + x * xStep;

                double x0 = 0;
                double y0 = 0;

                byte iteration = 0;
                int max_iteration = 255;
                while ( x0 * x0 + y0 * y0 < 4 && iteration < max_iteration ) {
                    double xtemp = x0 * x0 - y0 * y0 + X;
                    y0 = 2 * x0 * y0 + Y;
                    x0 = xtemp;
                    iteration++;
                }

                if ( iteration < minIteration ) minIteration = iteration;
                if ( iteration > maxInteration ) maxInteration = iteration;

                cols[y * texSize + x].r = iteration;
            }
        }

        float range = maxInteration - minIteration;

        //normalise and colorize
        for ( int y = 0; y < texSize; y++ ) {
            for ( int x = 0; x < texSize; x++ ) {

                r = ( cols[y * texSize + x].r - minIteration ) / range;

                //greyscale
                cols[y * texSize + x].r = (byte) ( r * 255 );
                cols[y * texSize + x].g = (byte) ( r * 255 );
                cols[y * texSize + x].b = (byte) ( r * 255 );

                //rainbows
                //cols[y * texSize + x].r = (byte) ( Mathf.Sin( ( r + 0.5f ) * Mathf.PI ) * 255);
                //cols[y * texSize + x].g = (byte) ( Mathf.Sin( ( r ) * Mathf.PI ) * 255 );
                //cols[y * texSize + x].b = (byte) ( Mathf.Sin( ( r - 0.5f ) * Mathf.PI ) * 255 );
            }
        }
        tex.SetPixels32( cols );
        tex.Apply( false );
    }
1 Like

Thanks to both your replies. I will do both options.