莱布尼茨公式 估算PI

2015-09-27 0 976
莱布尼茨公式 估算PI
#The Leibniz formula: 1-(1/3)+(1/5)-(1/7)+(1/9)...

def pi(prec)
  denom = 3.0
  mod = -1.0
  result = 1.to_f
  i = 0
  while( i < prec)
    result += mod*((1.0/denom))
    denom += 2
    mod *= -1
    i += 1
  end
  #the formula returns pi/4, so to get the approximation of pi, we multiply by 4
  result *= 4.0
  return result
end

#Example:

puts pi(3423231) #=>3.14159236146807

#note that there is no significance to "3423231", but was just an arbitrary number I used

遇见资源网 ruby 莱布尼茨公式 估算PI http://www.ox520.com/16461.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务