Solution: Compute Pi
Go over the implementation of calculating the approximate value of Pi based on its definition.
We'll cover the following...
We'll cover the following...
Solution
print "Enter the number of terms for the approximation: "
n = gets.chomp.to_i * 2
pi = 0
plus = true
(1..n).step(2) do |x| # each step is equal to 1 + 2x
if plus
pi += 1.0 / x
else
pi -= 1.0 / x
end
plus = !plus
end
pi = pi * 4
puts "My computation PI = #{pi}"
puts " Ruby's PI value: #{Math::PI}"Calculating Pi with different numbers of iterations
Explanation
Line 6:
step(2)ensures that in each ...