Reputation: 61
Hi I'm trying to calculate digits of pi using the Nilakantha series, however when i reaches 645 I just get an overflow error, could anyone help me understand what I'm doing wrong and how to fix it?
The Nilakantha series is: π = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + 4/(10*11*12) - 4/(12*13*14)...
Here's my code:
Dim pi As Decimal
pi = 3D
For i = 1 To 100000
If i Mod 2 = 1 Then
pi += 4 / ((2 * i) * ((2 * i) + 1) * ((2 * i) + 2))
ElseIf i Mod 2 = 0 Then
pi -= 4 / ((2 * i) * ((2 * i) + 1) * ((2 * i) + 2))
End If
Next
Console.WriteLine(pi.ToString)
Console.Read()
Thanks so much,
Upvotes: 0
Views: 409
Reputation: 25013
The denominator is being calculated as an Integer and so falls outside the range for an Integer.
You can coerce it into using Decimal values simply by introducing a Decimal into the calculation:
Dim pi As Decimal = 3D
For i = 1 To 100000
If i Mod 2 = 1 Then
pi += 4 / ((2D * i) * ((2 * i) + 1) * ((2 * i) + 2))
Else
pi -= 4 / ((2D * i) * ((2 * i) + 1) * ((2 * i) + 2))
End If
Next
Console.WriteLine(pi.ToString)
Console.ReadLine()
Outputs:
3.1415926535897929884701432528
Close, but no cigar.
Upvotes: 1