迭代计算pi时,Double类型返回-1。#IND / NaN错误

时间:2010-06-13 00:29:38

标签: .net math floating-point types numbers

我正在解决我的MCTS认证问题。程序必须计算pi,直到用户按下一个键,此时线程被中止,结果返回主线程并打印在控制台中。很简单吧?这个练习实际上是关于线程的,但我遇到了另一个问题。计算pi的过程返回-1。#IND。我已经阅读了web关于此错误的一些材料,但我仍然不确定如何修复它。当我将double更改为Decimal类型时,我毫不奇怪地很快得到Overflow Exception。那么,问题是如何正确存储数字?当它变得太大而无法包含在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

1 个答案:

答案 0 :(得分:2)

p在步骤1025变为inf