Skip to content

Newton Fractal

Portalez Régis edited this page May 11, 2026 · 18 revisions

Newton Fractal

Newton's method applied to f(z) = z³ − 1 to find cubic roots of unity. The rendered image shows convergence basins per root.

Source: src/3.Maths/Newton/Program.cs

The sample demonstrates:

  • int2 packed return values (root id + iteration count)
  • [IntrinsicFunction("…")] to bind a managed wrapper to a CUDA intrinsic (fabsf, sqrtf)
  • 2D grid distribution over a complex plane
[EntryPoint]
public static void Run(int2[] results, int lineFrom, int lineTo)
{
    for (int i = lineFrom + threadIdx.y + blockIdx.y * blockDim.y; i < lineTo; i += blockDim.y * gridDim.y)
    for (int j = threadIdx.x + blockIdx.x * blockDim.x; j < N;        j += blockDim.x * gridDim.x)
    {
        float x = fromX + i * h, y = fromY + j * h;
        IterCount(ref results[i * N + j], x, y);
    }
}
[MethodImpl(MethodImplOptions.AggressiveInlining), IntrinsicFunction("fabsf")]
private static float fabsf(float a) => (float) Math.Abs(a);

[MethodImpl(MethodImplOptions.AggressiveInlining), IntrinsicFunction("sqrtf")]
private static float sqrtf(float a) => (float) Math.Sqrt(a);

Because .NET only exposes Math.Abs/Math.Sqrt in double, redirecting to single-precision CUDA intrinsics avoids the implicit promotion and the round-trip through 64-bit FP units. Output is a 4096² PNG; darker pixels converged faster.

Clone this wiki locally