Guest User

Untitled

a guest
Dec 13th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. # # a run with floats
  2. # puts pi
  3. #
  4. # 2012-08-30 08:11:17 -0500
  5. # Found it with 426183 terms
  6. # 2012-08-30 08:11:19 -0500
  7. # 3.1415949999995694
  8. #
  9. # # a run with rational numbers
  10. # puts pi(false)
  11. #
  12. # 2012-08-30 08:11:44 -0500
  13. # Found it with 426183 terms
  14. # 2012-08-30 08:33:02 -0500
  15. # 3.141594999999669
  16. #
  17. # # Don't add rationals with differing denominators in a tight loop
  18.  
  19. # Given that Pi can be estimated using the function
  20. # 4 * (1 – 1/3 + 1/5 – 1/7 + …) with more terms giving greater accuracy,
  21. # write a function that calculates Pi to an accuracy of 5 decimal places.
  22. #
  23. def pi(fast=true)
  24. puts Time.now
  25. previous_value = i = running_multiplier = 1
  26. while ('%0.5f' % previous_value.to_f) != ('%0.5f' % (previous_value=(4*running_multiplier)).to_f) do
  27. new_term = (Rational(1,1+(i*2)) * (-1)**i)
  28. new_term = new_term.to_f if fast
  29. running_multiplier += new_term
  30. i += 1
  31. end
  32. puts "Found it with #{i} terms"
  33. puts Time.now
  34. (4*running_multiplier).to_f
  35. end
Add Comment
Please, Sign In to add comment