views:

82

answers:

1

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
+2  A: 

p becomes inf at step 1025.

lhf
Why is the code returned #IND and not #INF then?
Antony Highsky
Because `pi` is calculated by dividing infinity by infinity, which is undefined.
Mike Seymour