Pi with arbitrary precision and mpmath

26 views
Skip to first unread message

Carlos Gouveia

unread,
Jul 21, 2019, 7:33:38 PM7/21/19
to mpmath

Hello,

Just for the love of programming, I wrote an arbitrary precision script
to compute Pi using mpmath. I'm not new to mpmath and I like this library
whole lot. This time I've got puzzling outputs, though.

The algorithm is based on the Borwein brothers' algorithm, which is quite 
simple to program:

a.png
With the formulae above I wrote a Python script that spits Pi with an 
arbitrary precision... well, not quite. What I got was a long string
of digits such as the following (only the first five lines shown):

3.14159264621354594737567822448909282684326171875
3.1415926535897935600871733186068013310432434082031
3.1415926535897935600871733186068013310432434082031
3.1415926535897935600871733186068013310432434082031
3.1415926535897935600871733186068013310432434082031

What puzzles me is that the long numerical strings above look like Pi,
but all the digits after the 15th decimal place are wrong. This is an
iterative process that should converge quartically, and the figures
above suggest that Pi has converged after the 2nd iteration, given
the chosen precision. But it converged to the wrong number, and I
wonder why.

Here's the code I've been using:

import mpmath as mp

mp
.dps  = 72
mp.pretty = True

one
= mp.mpf('1.0')
two
= mp.mpf('2.0')
four
= mp.mpf('4.0')
six
= mp.mpf('6.0')

m
= -one/four
tmp
= mp.mpf(0)
val
= mp.mpf(0)

sqrt2
= mp.sqrt(two)

y
= sqrt2 - one
a
= six - four*sqrt2

for k in range(0,12):
    tmp
= (one - mp.power(y,four))
    tmp
= tmp**m
    y
= (tmp - one)/(tmp + one)
    a
= a*mp.power((one + y),four) - \
        y
*mp.power(two,(2*k+3))*(one + y + mp.power(y,2))
    val
= one/a
   
   
print(mp.nstr(val,50))


Can you spot any mistake in it? The 'algorithmization' is probably
correct, otherwise the script wouldn't yield Pi correct to fifteen
decimal places. It's something wrong I did with mpmath. But what?

Ubuntu 18.04, Python 3.6.8 and mpmath 1.1.0.

Thanks a lot for any light shed on this matter.

C.G.

Isuru Fernando

unread,
Jul 22, 2019, 12:32:54 AM7/22/19
to mpm...@googlegroups.com
Hi,

You need to do,
mp.mp.dps = 72 instead of mp.dps = 72, otherwise the working precision doesn't change properly.
You can do print(mp.mp) to see the working precision.

Isuru

--
You received this message because you are subscribed to the Google Groups "mpmath" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mpmath+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mpmath/2f3b3b41-0393-4bbf-9a44-5de8344e9b87%40googlegroups.com.

Carlos Gouveia

unread,
Jul 22, 2019, 8:43:53 AM7/22/19
to mpmath

Hi Isuru,

That worked, thanks!

C.G.
To unsubscribe from this group and stop receiving emails from it, send an email to mpm...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages