Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # # a run with floats
- # puts pi
- #
- # 2012-08-30 08:11:17 -0500
- # Found it with 426183 terms
- # 2012-08-30 08:11:19 -0500
- # 3.1415949999995694
- #
- # # a run with rational numbers
- # puts pi(false)
- #
- # 2012-08-30 08:11:44 -0500
- # Found it with 426183 terms
- # 2012-08-30 08:33:02 -0500
- # 3.141594999999669
- #
- # # Don't add rationals with differing denominators in a tight loop
- # Given that Pi can be estimated using the function
- # 4 * (1 – 1/3 + 1/5 – 1/7 + …) with more terms giving greater accuracy,
- # write a function that calculates Pi to an accuracy of 5 decimal places.
- #
- def pi(fast=true)
- puts Time.now
- previous_value = i = running_multiplier = 1
- while ('%0.5f' % previous_value.to_f) != ('%0.5f' % (previous_value=(4*running_multiplier)).to_f) do
- new_term = (Rational(1,1+(i*2)) * (-1)**i)
- new_term = new_term.to_f if fast
- running_multiplier += new_term
- i += 1
- end
- puts "Found it with #{i} terms"
- puts Time.now
- (4*running_multiplier).to_f
- end
Add Comment
Please, Sign In to add comment