实现一种算法来计算R中的pi

时间:2017-12-27 15:31:40

标签: r algorithm

我正在尝试在R中实现Brent-Salamin algorithm的变体。它适用于前25次迭代,但随后,它会出现意外行为,返回负面结果。

我想实现的算法是:

initial values:
x_0 = 1; y_0 = 1/sqrt(2); z_0 = 1/2

x_n = (x_n-1 + y_n-1)/2 
y_n = sqrt(x_n-1 * y_n-1)
z_n = z_n-1 - 2^n * (x_n^2-y_n^2)

p_n = (2 * x_n^2) / z_n

其中n是当前迭代。

格式更精美的公式为here

我想出的代码是:

mypi <- function(n){

  x = 1
  y = 1/sqrt(2)
  z = 1/2
  iteration = 0

  while(iteration < n){
    iteration = iteration + 1

    newx = (x + y) / 2
    y = sqrt(x * y)
    x = newx
    z = z-(2^iteration * (x^2 - y^2))
    p = (2 * x^2) / z
  }

  return(p)
}

输出:

> mypi(10)
[1] 3.141593
> mypi(20)
[1] 3.141593
> mypi(50)
[1] -33.34323

因为我是R的新手,我的代码中是否有错误或是算法?

1 个答案:

答案 0 :(得分:11)

您的代码只是混乱,因为它与维基页面中编写的算法不一致。正确的版本如下所示:

mypi <- function(n){

  x = 1
  y = 1/sqrt(2)
  z = 1/4
  p <- 1

  iteration = 0

  while(iteration < n){
    iteration = iteration + 1

    newx = (x + y) / 2
    y = sqrt(x * y)
    # x = newx
    # z = z-(2^iteration * (x^2 - y^2))
    z = z- p* (x-newx)^2
    p = 2*p
    x = newx
  }

  (newx + y)^2/(4*z)
}

给出

> mypi(10)
[1] 3.141593
> mypi(20)
[1] 3.141593
> mypi(50)
[1] 3.141593