Double type returns -1.#IND/NaN error when calculating pi iteratively

Posted by Draak on Stack Overflow See other posts from Stack Overflow or by Draak
Published on 2010-06-13T00:29:38Z Indexed on 2010/06/13 0:32 UTC
Read the original article Hit count: 517

Filed under:
|
|
|
|

I am working through a problem for my MCTS certification. The program has to calculate pi until the user presses a key, at which point the thread is aborted, the result returned to the main thread and printed in the console. Simple enough, right? This exercise is really meant to be about threading, but I'm running into another problem. The procedure that calculates pi returns -1.#IND. I've read some of the material on the web about this error, but I'm still not sure how to fix it. When I change double to Decimal type, I unsurprisingly get Overflow Exception very quickly. So, the question is how do I store the numbers correctly? Do I have to create a class to somehow store parts of the number when it gets too big to be contained in a Decimal?

Class PiCalculator

Dim a As Double = 1
Dim b As Double = 1 / Math.Sqrt(2)
Dim t As Double = 1 / 4
Dim p As Double = 1
Dim pi As Double
Dim callback As DelegateResult

Sub New(ByVal _callback As DelegateResult)
    callback = _callback
End Sub

Sub Calculate()
    Try
        Do While True
            Dim a1 = (a + b) / 2
            Dim b1 = Math.Sqrt(a * b)
            Dim t1 = t - p * (a - a1) ^ 2
            Dim p1 = 2 * p

            a = a1
            b = b1
            t = t1
            p = p1

            pi = ((a + b) ^ 2) / (4 * t)
        Loop
    Catch ex As ThreadAbortException
    Finally
        callback(pi)
    End Try

End Sub

End Class

© Stack Overflow or respective owner

Related posts about .NET

Related posts about vb.net