莱布尼茨公式 估算PI

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#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