我正在寻找获得 π 值的最快方法,作为个人挑战。更具体地说,我使用的方法不涉及使用 #define 常量如 M_PI, ,或对数字进行硬编码。

下面的程序测试了我所知道的各种方法。理论上,内联汇编版本是最快的选择,尽管显然不可移植。我将其作为与其他版本进行比较的基准。在我的测试中,使用内置函数时, 4 * atan(1) 该版本在 GCC 4.2 上速度最快,因为它自动折叠 atan(1) 成常数。和 -fno-builtin 指定,将 atan2(0, -1) 版本是最快的。

这是主要的测试程序(pitimes.c):

#include <math.h>
#include <stdio.h>
#include <time.h>

#define ITERS 10000000
#define TESTWITH(x) {                                                       \
    diff = 0.0;                                                             \
    time1 = clock();                                                        \
    for (i = 0; i < ITERS; ++i)                                             \
        diff += (x) - M_PI;                                                 \
    time2 = clock();                                                        \
    printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1));   \
}

static inline double
diffclock(clock_t time1, clock_t time0)
{
    return (double) (time1 - time0) / CLOCKS_PER_SEC;
}

int
main()
{
    int i;
    clock_t time1, time2;
    double diff;

    /* Warmup. The atan2 case catches GCC's atan folding (which would
     * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
     * is not used. */
    TESTWITH(4 * atan(1))
    TESTWITH(4 * atan2(1, 1))

#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__))
    extern double fldpi();
    TESTWITH(fldpi())
#endif

    /* Actual tests start here. */
    TESTWITH(atan2(0, -1))
    TESTWITH(acos(-1))
    TESTWITH(2 * asin(1))
    TESTWITH(4 * atan2(1, 1))
    TESTWITH(4 * atan(1))

    return 0;
}

还有内联汇编的东西(fldpi.c)仅适用于 x86 和 x64 系统:

double
fldpi()
{
    double pi;
    asm("fldpi" : "=t" (pi));
    return pi;
}

以及构建我正在测试的所有配置的构建脚本(build.sh):

#!/bin/sh
gcc -O3 -Wall -c           -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c           -m64 -o fldpi-64.o fldpi.c

gcc -O3 -Wall -ffast-math  -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall              -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math  -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall              -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm

除了在各种编译器标志之间进行测试(我也比较了 32 位和 64 位,因为优化不同),我还尝试切换测试的顺序。但仍然, atan2(0, -1) 版本仍然每次都名列前茅。

有帮助吗?

解决方案

蒙特卡罗法, 正如前面提到的,它应用了一些伟大的概念,但显然它不是最快的,无论从长远来看,还是从任何合理的衡量标准来看,它都不是最快的。此外,这完全取决于您想要什么样的准确性。我所知道的最快的 π 是数字硬编码的。看着 圆周率圆周率[PDF], ,有很多公式。

这是一种快速收敛的方法——每次迭代大约 14 位数字。 PiFast, 是当前最快的应用程序,将此公式与 FFT 结合使用。我只写公式,因为代码很简单。这个公式几乎被人发现了 拉马努金和楚德诺夫斯基发现. 。这实际上就是他计算数十亿位数字的方法——所以这不是一个可以忽视的方法。该公式将很快溢出,并且由于我们正在除阶乘,因此延迟此类计算以删除项将是有利的。

enter image description here

enter image description here

在哪里,

enter image description here

下面是 布伦特-萨拉明算法. 。维基百科提到,当 A 那么“足够接近” (a + b)² / 4t 将是 π 的近似值。我不确定“足够接近”是什么意思,但从我的测试来看,一次迭代得到了 2 位数字,两次迭代得到了 7 位,三次迭代得到了 15 位,当然这是双精度数,所以根据其表示形式和这 真的 计算可能会更准确。

let pi_2 iters =
    let rec loop_ a b t p i =
        if i = 0 then a,b,t,p
        else
            let a_n = (a +. b) /. 2.0 
            and b_n = sqrt (a*.b)
            and p_n = 2.0 *. p in
            let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in
            loop_ a_n b_n t_n p_n (i - 1)
    in 
    let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in
    (a +. b) *. (a +. b) /. (4.0 *. t)

最后,来玩 pi 高尔夫(800 位数字)怎么样?160个字符!

int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}

其他提示

我真的很喜欢这个程序,因为它通过查看自己的面积来近似 π。

国际奥委会 1988: 韦斯特利.c

#define _ -F<00||--F-OO--;
int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO()
{
            _-_-_-_
       _-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
        _-_-_-_-_-_-_-_
            _-_-_-_
}

这是我在高中学到的计算 pi 的技术的一般描述。

我分享这个只是因为我认为它足够简单,任何人都可以无限地记住它,而且它还教给你“蒙特卡罗”方法的概念——这是一种统计方法,用于得出不会立即出现的答案。可通过随机过程推论。

画一个正方形,并在该正方形内切一个象限(半圆的四分之一)(象限的半径等于正方形的边长,因此它尽可能填充正方形)

现在向正方形扔一个飞镖,并记录它的落地位置——也就是说,在正方形内的任意位置选择一个随机点。当然是落在正方形里面了,但是是在半圆里面吗?记录这个事实。

多次重复这个过程——你会发现半圆内的点数与抛出的总数有一个比率,称这个比率为x。

由于正方形的面积为r乘以r,因此可以推导出半圆的面积为x乘以r乘以r(即x乘以r的平方)。因此 x 乘以 4 将得到 pi。

这不是一个快速使用的方法。但这是蒙特卡罗方法的一个很好的例子。如果你环顾四周,你可能会发现许多超出你的计算能力的问题都可以通过这样的方法来解决。

为了完整性,C++ 模板版本,为了优化构建,将在编译时计算 PI 的近似值,并将内联为单个值。

#include <iostream>

template<int I>
struct sign
{
    enum {value = (I % 2) == 0 ? 1 : -1};
};

template<int I, int J>
struct pi_calc
{
    inline static double value ()
    {
        return (pi_calc<I-1, J>::value () + pi_calc<I-1, J+1>::value ()) / 2.0;
    }
};

template<int J>
struct pi_calc<0, J>
{
    inline static double value ()
    {
        return (sign<J>::value * 4.0) / (2.0 * J + 1.0) + pi_calc<0, J-1>::value ();
    }
};


template<>
struct pi_calc<0, 0>
{
    inline static double value ()
    {
        return 4.0;
    }
};

template<int I>
struct pi
{
    inline static double value ()
    {
        return pi_calc<I, I>::value ();
    }
};

int main ()
{
    std::cout.precision (12);

    const double pi_value = pi<10>::value ();

    std::cout << "pi ~ " << pi_value << std::endl;

    return 0;
}

请注意,对于 I > 10,优化构建可能会很慢,对于非优化运行也是如此。对于 12 次迭代,我相信大约有 80k 次对 value() 的调用(在没有记忆的情况下)。

实际上有一整本书致力于(除其他外) 快速地 \pi 的计算方法:《Pi 和年度股东大会》,作者:Jonathan 和 Peter Borwein(亚马逊有售).

我对 AGM 和相关算法进行了相当多的研究:这很有趣(尽管有时并不简单)。

请注意,要实现大多数现代算法来计算 \pi,您将需要一个多精度算术库(良好生产规范 是一个不错的选择,尽管距离我上次使用它已经有一段时间了)。

最佳算法的时间复杂度为 O(M(n)log(n)),其中 M(n) 是两个 n 位整数相乘的时间复杂度 (M(n)=O(n) log(n) log(log(n))) 使用基于 FFT 的算法,在计算 \pi 的数字时通常需要这种算法,并且这种算法在 GMP 中实现。

请注意,尽管算法背后的数学可能并不简单,但算法本身通常是几行伪代码,并且它们的实现通常非常简单(如果您选择不编写自己的多精度算术:-))。

以下答案 准确地说,如何以最快的方式做到这一点——用最少的计算工作量. 。即使你不喜欢这个答案,你也不得不承认这确实是获取PI值最快的方法。

最快的 获取Pi值的方法是:

1)选择您喜欢的编程语言2)加载其数学库3)并发现那里的PI已经定义了 - 可以使用!

如果您手头没有数学库..

第二快 方式(更通用的解决方案)是:

在互联网上查找 Pi,例如这里:

http://www.evandersson.com/pi/digits/1000000 (100万位数字..你的浮点精度是多少?)

或在这里:

http://3.141592653589793238462643383279502884197169399375105820974944592.com/

或在这里:

http://en.wikipedia.org/wiki/Pi

对于您想要使用的任何精度算术,找到所需的数字都非常快,并且通过定义常量,您可以确保不会浪费宝贵的 CPU 时间。

这不仅是一个半幽默的答案,而且实际上,如果有人愿意在实际应用中计算 Pi 的值..这会极大地浪费 CPU 时间,不是吗?至少我没有看到尝试重新计算这个的真正应用程序。

尊敬的主持人:请注意,OP 询问:“获取 PI 值的最快方法”

BBP公式 允许您计算第 n 位数字 - 以 2(或 16)为基数 - 甚至不必先考虑前面的 n-1 位数字:)

我总是使用,而不是将 pi 定义为常量 acos(-1).

刚刚遇到这个,为了完整性,应该放在这里:

在 Piet 中计算 PI

它有一个相当好的特性,就是可以通过增大程序来提高精度。

这里对语言本身的一些见解

如果 本文 是真的,那么 贝拉德算法 已经创造了可能是最快的可用之一。他使用台式电脑创建了 2.7 万亿位的 pi!

...他已经发表了他的 在这里工作

干得好,贝拉德,你是先锋!

http://www.theregister.co.uk/2010/01/06/very_long_pi/

这是一个“经典”方法,非常容易实现。这个实现,在Python(不是那么快的语言)中做到了:

from math import pi
from time import time


precision = 10**6 # higher value -> higher precision
                  # lower  value -> higher speed

t = time()

calc = 0
for k in xrange(0, precision):
    calc += ((-1)**k) / (2*k+1.)
calc *= 4. # this is just a little optimization

t = time()-t

print "Calculated: %.40f" % calc
print "Costant pi: %.40f" % pi
print "Difference: %.40f" % abs(calc-pi)
print "Time elapsed: %s" % repr(t)

您可以找到更多信息 这里.

无论如何,在 python 中获得精确的 pi 值的最快方法是:

from gmpy import pi
print pi(3000) # the rule is the same as 
               # the precision on the previous code

这是 gmpy pi 方法的源代码,我认为在这种情况下代码没有注释那么有用:

static char doc_pi[]="\
pi(n): returns pi with n bits of precision in an mpf object\n\
";

/* This function was originally from netlib, package bmp, by
 * Richard P. Brent. Paulo Cesar Pereira de Andrade converted
 * it to C and used it in his LISP interpreter.
 *
 * Original comments:
 * 
 *   sets mp pi = 3.14159... to the available precision.
 *   uses the gauss-legendre algorithm.
 *   this method requires time o(ln(t)m(t)), so it is slower
 *   than mppi if m(t) = o(t**2), but would be faster for
 *   large t if a faster multiplication algorithm were used
 *   (see comments in mpmul).
 *   for a description of the method, see - multiple-precision
 *   zero-finding and the complexity of elementary function
 *   evaluation (by r. p. brent), in analytic computational
 *   complexity (edited by j. f. traub), academic press, 1976, 151-176.
 *   rounding options not implemented, no guard digits used.
*/
static PyObject *
Pygmpy_pi(PyObject *self, PyObject *args)
{
    PympfObject *pi;
    int precision;
    mpf_t r_i2, r_i3, r_i4;
    mpf_t ix;

    ONE_ARG("pi", "i", &precision);
    if(!(pi = Pympf_new(precision))) {
        return NULL;
    }

    mpf_set_si(pi->f, 1);

    mpf_init(ix);
    mpf_set_ui(ix, 1);

    mpf_init2(r_i2, precision);

    mpf_init2(r_i3, precision);
    mpf_set_d(r_i3, 0.25);

    mpf_init2(r_i4, precision);
    mpf_set_d(r_i4, 0.5);
    mpf_sqrt(r_i4, r_i4);

    for (;;) {
        mpf_set(r_i2, pi->f);
        mpf_add(pi->f, pi->f, r_i4);
        mpf_div_ui(pi->f, pi->f, 2);
        mpf_mul(r_i4, r_i2, r_i4);
        mpf_sub(r_i2, pi->f, r_i2);
        mpf_mul(r_i2, r_i2, r_i2);
        mpf_mul(r_i2, r_i2, ix);
        mpf_sub(r_i3, r_i3, r_i2);
        mpf_sqrt(r_i4, r_i4);
        mpf_mul_ui(ix, ix, 2);
        /* Check for convergence */
        if (!(mpf_cmp_si(r_i2, 0) && 
              mpf_get_prec(r_i2) >= (unsigned)precision)) {
            mpf_mul(pi->f, pi->f, r_i4);
            mpf_div(pi->f, pi->f, r_i3);
            break;
        }
    }

    mpf_clear(ix);
    mpf_clear(r_i2);
    mpf_clear(r_i3);
    mpf_clear(r_i4);

    return (PyObject*)pi;
}

编辑: 我在剪切、粘贴和识别方面遇到了一些问题,无论如何你可以找到来源 这里.

如果您所说的最快是指输入代码最快,那么这是 高尔夫脚本 解决方案:

;''6666,-2%{2+.2/@*\/10.3??2*+}*`1000<~\;

使用类似 Machin 的公式

176 * arctan (1/57) + 28 * arctan (1/239) - 48 * arctan (1/682) + 96 * arctan(1/12943) 

[; \left( 176 \arctan \frac{1}{57} + 28 \arctan \frac{1}{239} - 48 \arctan \frac{1}{682} + 96 \arctan \frac{1}{12943}\right) ;], for you TeX the World people.

在Scheme中实现,例如:

(+ (- (+ (* 176 (atan (/ 1 57))) (* 28 (atan (/ 1 239)))) (* 48 (atan (/ 1 682)))) (* 96 (atan (/ 1 12943))))

如果您愿意使用近似值, 355 / 113 适用于 6 位十进制数字,并且具有可与整数表达式一起使用的额外优点。如今,这一点不再那么重要,因为“浮点数学协处理器”不再具有任何意义,但它曾经非常重要。

与双打:

4.0 * (4.0 * Math.Atan(0.2) - Math.Atan(1.0 / 239.0))

这将精确到小数点后 14 位,足以填充双精度(不精确可能是因为反正切线中的其余小数被截断)。

还有赛斯,它是 3.141592653589793238463, ,不是 64。

使用 D 在编译时计算 PI。

(复制自 DSource.org )

/** Calculate pi at compile time
 *
 * Compile with dmd -c pi.d
 */
module calcpi;

import meta.math;
import meta.conv;

/** real evaluateSeries!(real x, real metafunction!(real y, int n) term)
 *
 * Evaluate a power series at compile time.
 *
 * Given a metafunction of the form
 *  real term!(real y, int n),
 * which gives the nth term of a convergent series at the point y
 * (where the first term is n==1), and a real number x,
 * this metafunction calculates the infinite sum at the point x
 * by adding terms until the sum doesn't change any more.
 */
template evaluateSeries(real x, alias term, int n=1, real sumsofar=0.0)
{
  static if (n>1 && sumsofar == sumsofar + term!(x, n+1)) {
     const real evaluateSeries = sumsofar;
  } else {
     const real evaluateSeries = evaluateSeries!(x, term, n+1, sumsofar + term!(x, n));
  }
}

/*** Calculate atan(x) at compile time.
 *
 * Uses the Maclaurin formula
 *  atan(z) = z - z^3/3 + Z^5/5 - Z^7/7 + ...
 */
template atan(real z)
{
    const real atan = evaluateSeries!(z, atanTerm);
}

template atanTerm(real x, int n)
{
    const real atanTerm =  (n & 1 ? 1 : -1) * pow!(x, 2*n-1)/(2*n-1);
}

/// Machin's formula for pi
/// pi/4 = 4 atan(1/5) - atan(1/239).
pragma(msg, "PI = " ~ fcvt!(4.0 * (4*atan!(1/5.0) - atan!(1/239.0))) );

Pi 正好是 3![教授。弗林克(辛普森一家)]

笑话,但这是一个 C# 语言(需要 .NET-Framework)。

using System;
using System.Text;

class Program {
    static void Main(string[] args) {
        int Digits = 100;

        BigNumber x = new BigNumber(Digits);
        BigNumber y = new BigNumber(Digits);
        x.ArcTan(16, 5);
        y.ArcTan(4, 239);
        x.Subtract(y);
        string pi = x.ToString();
        Console.WriteLine(pi);
    }
}

public class BigNumber {
    private UInt32[] number;
    private int size;
    private int maxDigits;

    public BigNumber(int maxDigits) {
        this.maxDigits = maxDigits;
        this.size = (int)Math.Ceiling((float)maxDigits * 0.104) + 2;
        number = new UInt32[size];
    }
    public BigNumber(int maxDigits, UInt32 intPart)
        : this(maxDigits) {
        number[0] = intPart;
        for (int i = 1; i < size; i++) {
            number[i] = 0;
        }
    }
    private void VerifySameSize(BigNumber value) {
        if (Object.ReferenceEquals(this, value))
            throw new Exception("BigNumbers cannot operate on themselves");
        if (value.size != this.size)
            throw new Exception("BigNumbers must have the same size");
    }

    public void Add(BigNumber value) {
        VerifySameSize(value);

        int index = size - 1;
        while (index >= 0 && value.number[index] == 0)
            index--;

        UInt32 carry = 0;
        while (index >= 0) {
            UInt64 result = (UInt64)number[index] +
                            value.number[index] + carry;
            number[index] = (UInt32)result;
            if (result >= 0x100000000U)
                carry = 1;
            else
                carry = 0;
            index--;
        }
    }
    public void Subtract(BigNumber value) {
        VerifySameSize(value);

        int index = size - 1;
        while (index >= 0 && value.number[index] == 0)
            index--;

        UInt32 borrow = 0;
        while (index >= 0) {
            UInt64 result = 0x100000000U + (UInt64)number[index] -
                            value.number[index] - borrow;
            number[index] = (UInt32)result;
            if (result >= 0x100000000U)
                borrow = 0;
            else
                borrow = 1;
            index--;
        }
    }
    public void Multiply(UInt32 value) {
        int index = size - 1;
        while (index >= 0 && number[index] == 0)
            index--;

        UInt32 carry = 0;
        while (index >= 0) {
            UInt64 result = (UInt64)number[index] * value + carry;
            number[index] = (UInt32)result;
            carry = (UInt32)(result >> 32);
            index--;
        }
    }
    public void Divide(UInt32 value) {
        int index = 0;
        while (index < size && number[index] == 0)
            index++;

        UInt32 carry = 0;
        while (index < size) {
            UInt64 result = number[index] + ((UInt64)carry << 32);
            number[index] = (UInt32)(result / (UInt64)value);
            carry = (UInt32)(result % (UInt64)value);
            index++;
        }
    }
    public void Assign(BigNumber value) {
        VerifySameSize(value);
        for (int i = 0; i < size; i++) {
            number[i] = value.number[i];
        }
    }

    public override string ToString() {
        BigNumber temp = new BigNumber(maxDigits);
        temp.Assign(this);

        StringBuilder sb = new StringBuilder();
        sb.Append(temp.number[0]);
        sb.Append(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);

        int digitCount = 0;
        while (digitCount < maxDigits) {
            temp.number[0] = 0;
            temp.Multiply(100000);
            sb.AppendFormat("{0:D5}", temp.number[0]);
            digitCount += 5;
        }

        return sb.ToString();
    }
    public bool IsZero() {
        foreach (UInt32 item in number) {
            if (item != 0)
                return false;
        }
        return true;
    }

    public void ArcTan(UInt32 multiplicand, UInt32 reciprocal) {
        BigNumber X = new BigNumber(maxDigits, multiplicand);
        X.Divide(reciprocal);
        reciprocal *= reciprocal;

        this.Assign(X);

        BigNumber term = new BigNumber(maxDigits);
        UInt32 divisor = 1;
        bool subtractTerm = true;
        while (true) {
            X.Divide(reciprocal);
            term.Assign(X);
            divisor += 2;
            term.Divide(divisor);
            if (term.IsZero())
                break;

            if (subtractTerm)
                this.Subtract(term);
            else
                this.Add(term);
            subtractTerm = !subtractTerm;
        }
    }
}

这个版本(Delphi 中)没什么特别的,但至少比 Nick Hodge 在他的博客上发布的版本 :)。在我的机器上,执行 10 亿次迭代大约需要 16 秒,给出的值为 3.1415926525879(准确部分以粗体显示)。

program calcpi;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  start, finish: TDateTime;

function CalculatePi(iterations: integer): double;
var
  numerator, denominator, i: integer;
  sum: double;
begin
  {
  PI may be approximated with this formula:
  4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 .......)
  //}
  numerator := 1;
  denominator := 1;
  sum := 0;
  for i := 1 to iterations do begin
    sum := sum + (numerator/denominator);
    denominator := denominator + 2;
    numerator := -numerator;
  end;
  Result := 4 * sum;
end;

begin
  try
    start := Now;
    WriteLn(FloatToStr(CalculatePi(StrToInt(ParamStr(1)))));
    finish := Now;
    WriteLn('Seconds:' + FormatDateTime('hh:mm:ss.zz',finish-start));
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

回到过去,由于字长较小且浮点运算缓慢或不存在,我们常常这样做:

/* Return approximation of n * PI; n is integer */
#define pi_times(n) (((n) * 22) / 7)

对于不需要太多精度的应用程序(例如视频游戏),这非常快并且足够准确。

如果你想 计算 π 值的近似值(出于某种原因),您应该尝试二进制提取算法。 贝拉德的 的改进 BBP 给出 O(N^2) 中的 PI.


如果你想 获得 π的近似值进行计算,则:

PI = 3.141592654

当然,这只是一个近似值,并不完全准确。偏差略大于 0.00000000004102。(万亿分之四,大约 4/10,000,000,000).


如果你想做 数学 与 π,然后给自己准备一支铅笔和纸或计算机代数包,并使用 π 的精确值 π。

如果你真的想要一个公式,这个很有趣:

π = - ln(-1)

Chris上面发布的Brent方法非常好;布伦特通常是任意精度算术领域的巨人。

如果你想要的只是第 N 位数字,著名的BBP公式在十六进制中很有用

从圆面积计算 π :-)

<input id="range" type="range" min="10" max="960" value="10" step="50" oninput="calcPi()">
<br>
<div id="cont"></div>

<script>
function generateCircle(width) {
    var c = width/2;
    var delta = 1.0;
    var str = "";
    var xCount = 0;
    for (var x=0; x <= width; x++) {
        for (var y = 0; y <= width; y++) {
            var d = Math.sqrt((x-c)*(x-c) + (y-c)*(y-c));
            if (d > (width-1)/2) {
                str += '.';
            }
            else {
                xCount++;
                str += 'o';
            }
            str += "&nbsp;" 
        }
        str += "\n";
    }
    var pi = (xCount * 4) / (width * width);
    return [str, pi];
}

function calcPi() {
    var e = document.getElementById("cont");
    var width = document.getElementById("range").value;
    e.innerHTML = "<h4>Generating circle...</h4>";
    setTimeout(function() {
        var circ = generateCircle(width);
        e.innerHTML  = "<pre>" + "π = " + circ[1].toFixed(2) + "\n" + circ[0] +"</pre>";
    }, 200);
}
calcPi();
</script>

更好的方法

获得标准常量的输出,例如 圆周率 或者标准概念,我们应该首先使用您正在使用的语言可用的内置方法。它将以最快、最好的方式回报价值。我正在使用 python 来获取获取 pi 值的最快方法

  • 数学库的 pi 变量. 。数学库将变量 pi 存储为常量。

math_pi.py

import math
print math.pi

使用linux的time实用程序运行脚本 /usr/bin/time -v python math_pi.py

输出:

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
  • 使用反余弦数学方法

acos_pi.py

import math
print math.acos(-1)

使用linux的time实用程序运行脚本 /usr/bin/time -v python acos_pi.py

输出:

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

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))

使用linux的time实用程序运行脚本 /usr/bin/time -v python bbp_pi.py

输出:

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

所以最好的方法是使用语言提供的内置方法,因为它们是最快且最好的获得输出的方法。在 python 中使用 math.pi

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top