An ASP.Net Linear Regression Function

Inspired by my PHP linear regression function:

    Function LinearRegression(ByVal dblX() As Double, ByVal dblY() As Double) As Array

        ' Calculates the slope and intercept of a set of coordinates

        'number of points
        Dim intN As Integer = dblX.Length

        'check both arrays are same size
        If intN <> dblY.Length Then

            Err.Raise(vbObjectError + 1, , "Array sizes do not match")

        End If

        'calculate sums
        Dim dblXSum As Double = 0
        Dim dblYSum As Double = 0

        Dim dblXXSum As Double = 0
        Dim dblXYSum As Double = 0

        Dim intIndex As Integer

        For intIndex = 0 To intN - 1

            dblXSum += dblX(intIndex)
            dblYSum += dblY(intIndex)

            dblXXSum += dblX(intIndex) * dblX(intIndex)
            dblXYSum += dblX(intIndex) * dblY(intIndex)


        'calculate slope
        Dim dblM As Double = ((intN * dblXYSum) - (dblXSum * dblYSum)) / ((intN * dblXXSum) - (dblXSum * dblXSum))

        'calculate intercept
        Dim dblB As Double = (dblYSum - (dblM * dblXSum)) / intN

        Dim dblResult() As Double = {dblM, dblB}

        Return dblResult

    End Function

Software developer by day, scale model builder and wargamer by night.

Posted in ASP.NET

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: