Precision of Double Number Type

  • Thread starter Thread starter Devon_Nullman
  • Start date Start date
D

Devon_Nullman

Guest
I am trying to emulate the Nilakantha algorithm to calculate Pi. The formula is:
3 + 4/2×3×4 − 4/4×5×6 + 4/6×7×8 − 4/8×9×10, on and om as long as you can.

The issue I am having is that the value stops increasing after not too many iterations and there seems to a discrepancy between how Doubles are handled. below is a console app and a button click sub for a forms app. Any ideas as to why the results are different ?


Console App Code:
Module Program
Sub Main(args As String())
Dim S As Double = CDbl("21,798,337,296,137,393")
Dim DT As Double
Dim div As Double = S * (S + 1) * (S + 2)
DT = 4D / div
Console.WriteLine(div.ToString("F"))
Console.WriteLine(DT.ToString("N92"))
Console.ReadLine()
End Sub
End Module
Results:
10357861630648208103056607550533164991842751610880.00
0.00000000000000000000000000000000000000000000000038618009610828085951635166931754374121291552

Forms Code Button Click:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S As Double = CDbl("21,798,337,296,137,393")
Dim DT As Double
Dim div As Double = S * (S + 1) * (S + 2)
DT = 4D / div
TxtResults.AppendText(div.ToString("F") & vbNewLine)
TxtResults.AppendText(DT.ToString("N92"))
End Sub
Results:
10357861630648200000000000000000000000000000000000.00
0.00000000000000000000000000000000000000000000000038618009610828100000000000000000000000000000

The code that does the work is here (in a Background Worker)

Private Sub BGWCalcPi_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BGWCalcPi.DoWork
Dim ModVal As Long = Iterations \ 100
Dim Pi As Decimal = 3D
Dim Numerator As Decimal = 4D
Dim Denominator As Decimal = 2D
'Dim Denom As Decimal
Dim Result As Decimal
For Count As Long = 1 To Iterations
Result = Numerator / Denominator ' three lines below are
Result /= Denominator + 1 ' to avoid overflows
Result /= Denominator + 2

If Count Mod 2 = 1 Then
Pi += Result
Else
Pi -= Result
End If
Denominator += 2D
If Count Mod ModVal = 0 Then
BGWCalcPi.ReportProgress(CInt((Count * 100) / Iterations))
End If
Next
PiString = Pi.ToString("N64")
End Sub

The result does not change from using 100 million iterations and 100 billion iterations. Using Decimal type gives overflows.

Continue reading...
 
Back
Top