Android Question Pi calculation

agraham

Expert
Licensed User
Longtime User
Use the forum search. This produces a string result

You should use the BigDecimal library if you want to use the result but for all practical purpose the B4X cPI constant should suffice.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User

B4X:
Sub AppStart (Args() As String)
    CalcPi(1000)
End Sub

Sub CalcPi (Iterations As Int)
    Dim p As BigDecimal
    p.Initialize3(0)
    For k = 0 To Iterations - 1
        Dim t0, t00, t1, t11, t2, t22, t3, t33, t4, t44 As BigDecimal
        t0.Initialize3(1)
        t00.Initialize3(16)
        t00.Pow(k)
        t0.Divide(t00)
        t1.Initialize3(4)
        t11.Initialize3(8 * k + 1)
        t1.Divide2(t11, 1000, t1.ROUND_HALF_DOWN)
        t2.Initialize3(2)
        t22.Initialize3(8 * k + 4)
        t2.Divide2(t22, 1000, t1.ROUND_HALF_DOWN)
        t3.Initialize3(1)
        t33.Initialize(8 * k + 5)
        t3.Divide2(t33, 1000, t1.ROUND_HALF_DOWN)
        t4.Initialize3(1)
        t44.Initialize3(8 * k + 6)
        t4.Divide2(t44, 1000, t1.ROUND_HALF_DOWN)
        t1.Subtract(t2).Subtract(t3).Subtract(t4)
        t0.Multiply(t1)
        p.Add(t0)
    Next
    Dim Correct As String = File.ReadString(File.DirAssets, "pi.txt")
    Dim OutPi As String = p.ToPlainString
    For i = 0 To OutPi.Length - 1
        Dim c As String = OutPi.CharAt(i)
        Dim c2 As String = Correct.CharAt(i)
        If c <> c2 Then
            Exit
        End If
    Next
    Log($"Correct digits: ${i}"$)
    Log(OutPi.SubString2(0, i))
    Log(Correct.Length)
End Sub
B4J code based on agraham's BigNumber library.
Will also work with B4A. Make sure to test in release mode.

Text file, used for testing, is attached.
 

Attachments

  • pi.txt
    43.5 KB · Views: 231
Upvote 0
Top