t-sqlcode-golffractals

How to generate a Mandelbrot with T-SQL?


Learning a little about T-SQL, and thought an interesting exercise would be to generate a Mandelbrot set with it.

Turns out someone already has (and recently, it appears). I'll let someone else post it as an answer, but I'm curious what optimizations can be made.

Alternately, what would you do to make the code more readable?

I'll select the most readable (yet reasonably compact) version as the accepted answer (too bad we don't have rep bounties yet!) unless someone really comes along with a great optimization.

Bonus points to those answers that teach me a little something about T-SQL.

-Adam


Solution

  • Create PROCEDURE dbo.mandlebrot
    @left float,
    @right float,
    @Top float,
    @Bottom float,
    @Res float,
    @MaxIterations Integer = 500
    As
    Set NoCount On
    
    Declare @Grid Table (
        X float Not Null, 
        Y float Not Null,
        InSet Bit
       Primary Key (X, Y))
    
    Declare @Xo float, @Yo float, @Abs float
    Declare @PtX Float, @PtY Float
    Declare @Iteration Integer Set @Iteration = 0
    Select @Xo = @Left, @Yo = @Bottom
    
    While @Yo <= @Top Begin
        While @Xo <= @Right Begin
            Select @PtX = @Xo, @PtY = @Yo
            While @Iteration < @MaxIterations 
                And (Square(@PtX) + Square(@PtY)) < 4.0 Begin
                Select @PtX = Square(@PtX) - Square(@PtY) + @Xo,
                       @PtY = 2* @PtX * @PtY + @Yo
                Select @Iteration, @PtX, @PtY
                Set @Iteration = @Iteration + 1
            End
            Insert @Grid(X, Y, InSet) 
            Values(@Xo, @Yo, Case 
                When @Iteration < @MaxIterations
                        Then 1 Else 0 End)
            Set @Xo = @Xo + @res
            Set @Iteration = 0
        End
        Select @Xo = @Left, 
               @Yo = @Yo + @Res
    End
    
    Select * From @Grid