BBP-type_formulae.sf 1.0 KB

12345678910111213141516171819202122232425262728
  1. #!/usr/bin/ruby
  2. # The generalized Bailey–Borwein–Plouffe formula (BBP formula)
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
  5. func BBP(s, b, A, m=A.len, r=200) {
  6. sum(0..r, {|k|
  7. sum(1..m, {|j|
  8. A[j-1] / (m*k + j)**s
  9. }) / b**k
  10. })
  11. }
  12. say BBP(1, 2, [1]) # 1.38629436111989061883446424291635313615100026872 = log(4)
  13. say BBP(1, 16, [4, 0]) # 4.08660499012792546564411277042929547902488637157 = log(390625/6561)
  14. say BBP(1, 16, [4, 0, 0, -2, -1, -1, 0, 0]) # 3.14159265358979323846264338327950288419716939938 = Pi
  15. # The BBP() function can also be used to efficiently compute atan(1/x)
  16. func plouffe_atan(x) {
  17. BBP(1, x**4, [1, 0, -(x**-2), 0]) / x
  18. }
  19. say plouffe_atan(2) # 0.463647609000806116214256231461214402028537054286 = atan(1/2)
  20. say plouffe_atan(3+4i) # 0.122489331563432077086041240605637905457072049191-0.158997191679999174364761036007018781573305474235i