What is the fastest way to get the value of π?

后端 未结 23 1812
自闭症患者
自闭症患者 2020-11-28 00:33

I\'m looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I\'m using ways that don\'t involve using #define constan

23条回答
  •  不知归路
    2020-11-28 01:02

    Better Approach

    To get the output of standard constants like pi or the standard concepts, we should first go with the builtins methods available in the language that you are using. It will return a value in the fastest and best way. I am using python to run the fastest way to get the value of pi.

    • pi variable of the math library. The math library stores the variable pi as a constant.

    math_pi.py

    import math
    print math.pi
    

    Run the script with time utility of linux /usr/bin/time -v python math_pi.py

    Output:

    Command being timed: "python math_pi.py"
    User time (seconds): 0.01
    System time (seconds): 0.01
    Percent of CPU this job got: 91%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03
    
    • Use arc cos method of math

    acos_pi.py

    import math
    print math.acos(-1)
    

    Run the script with time utility of linux /usr/bin/time -v python acos_pi.py

    Output:

    Command being timed: "python acos_pi.py"
    User time (seconds): 0.02
    System time (seconds): 0.01
    Percent of CPU this job got: 94%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03
    
    • use BBP formula

    bbp_pi.py

    from decimal import Decimal, getcontext
    getcontext().prec=100
    print sum(1/Decimal(16)**k * 
              (Decimal(4)/(8*k+1) - 
               Decimal(2)/(8*k+4) - 
               Decimal(1)/(8*k+5) -
               Decimal(1)/(8*k+6)) for k in range(100))
    

    Run the script with time utility of linux /usr/bin/time -v python bbp_pi.py

    Output:

    Command being timed: "python c.py"
    User time (seconds): 0.05
    System time (seconds): 0.01
    Percent of CPU this job got: 98%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.06
    

    So the best way is to use builtin methods provided by the language because they are the fastest and best to get the output. In python use math.pi

提交回复
热议问题