Wednesday, August 8, 2018

How do programming languages calculate PI approximations?


Two very well known approximations to PI are 22/7 (West) and 355/113 (Chinese).


As numbers how are they treated in Python, C#, SQL Server and the desktop 'Calculator' app?

It was fun looking into this. Here are how they work.

Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x=(355/113)
>>> x
3.1415929203539825
>>> y=(22/7)
>>> y
3.142857142857143
>>> x-y
-0.0012642225031602727
>>> y-x
0.0012642225031602727
>>>
----------------
Desktop Calculator

355/113=3.141592920353982
22/7=   3.142857142857143
PI=3.1415926535897932384626433832795
----------------

SQL Server 2017
Select cast((22.0000000000/7.0000000000) as numeric(30,25))
3.1428571428571428571428000

Select cast((355.0000000000/113.0000000000) as numeric(30,25))
3.1415929203539823008849550
-------------------------
C# Interactive in Visual Studio Community 2017
double y;
> y = 22 / 7;
> y
3
> y = 22.0000000000 / 7.0000000000;
> y
3.1428571428571428
> double x;
> x = 355 / 113;--delete this line
> x = 355.0000000000 / 113.0000000000;
> x
3.1415929203539825
>
I like the way Python spitted out the answer with lot less things to worry about.  Also, desktop calculator not to bad. What do you think?

No comments: