Search⌘ K
AI Features

Solution: Compute Pi

Explore how to compute Pi in Ruby using the step method to iterate through odd numbers and floating-point arithmetic. Understand toggling boolean values to alternate terms and improve your programming logic with this practical example.

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 ...