Accurate and fast PI in Python

In my last article I show how to use numpy and numba to speed up a naive Monte Carlo method to compute PI. We managed to get > 20x speed up. However the accuracy of PI even with 10 million samples was only accurate 2 decimal places. Rather disappointing :)

In this article I will show you how scientific programmers or numerical people do MC. Using the following we compute PI as 3.1415348.

No alt text provided for this image

The key is to use RandomState and two separate seeds to get two minimally correlated sequences of floats to avoid 'x' and 'y' be correlated. Even though numpy is using a very good Mersenne Twister, the previous method use two consecutive random numbers from the random generator. That is not a good idea.

We could have use a single random generator if we generate all the 'x' first followed by 'y'. But that is less flexible. Imagine you want to compute until certain acceptance criteria is meet. In that case you do not know how many 'x's you will need before you start the simulation.

No alt text provided for this image


Mael F.

building AI that empowers people

5 年

Great way to handle the correlation! Thanks for sharing the solution.

回复

要查看或添加评论,请登录

Manny Ko的更多文章

  • Improved Enum for Python

    Improved Enum for Python

    Sample code to demonstrate how to use some of added methods in Enumbase to write a command line declaration that is…

    8 条评论
  • Claude Shannon

    Claude Shannon

    Well he only invented the whole 'entropy' thing. Started the field of Information Theory (Mutual-information…

    14 条评论
  • Numpy+numba for 20x in Python

    Numpy+numba for 20x in Python

    Method 1: Naive Monte-Carlo rejection sampling to compute PI - C/C++ style. I am using 10 million MC samples…

    24 条评论
  • 6th method for Pandas: swifter

    6th method for Pandas: swifter

    In my previous Pandas article I show 5 different ways to apply a heaverside() function to a small dataset of NY hotel…

    6 条评论
  • Pandas: 5 Very Different Performances, more than 2000x

    Pandas: 5 Very Different Performances, more than 2000x

    Our dataset consists of 1631 records for locations of hotels in New York. The above is the output from 5 different ways…

    12 条评论
  • Rotation Invariance in Neural Nets

    Rotation Invariance in Neural Nets

    A recent CVPR paper "Strike (with) a Pose:" very elegantly and forcefully demonstrate the importance of invariance in…

    8 条评论
  • Deep Image Prior

    Deep Image Prior

    We might be aware of recent amazing results of generative-networks being able to upsample a very low quality/low-res…

    1 条评论

社区洞察

其他会员也浏览了