Skip to content

Instantly share code, notes, and snippets.

@andradei
Created November 17, 2015 00:32
Show Gist options
  • Save andradei/a122cd458c7384611c77 to your computer and use it in GitHub Desktop.
Save andradei/a122cd458c7384611c77 to your computer and use it in GitHub Desktop.
PI Approximation in Ruby
module PiApprox
class PI
attr_accessor :approximation, :denominator, :sum, :signal
def initialize(approx = 0, den = 1.0, sum = 0, signal = true)
@approximation = approx
@denominator = den
@sum = sum
@signal = signal
end
def print_approx times=10
answer = 'y'
i = 0
while i < times
if @signal
@sum += 1/@denominator
else
@sum -= 1/@denominator
end
@approximation = 4 * @sum
@signal = !@signal
@denominator += 2
i += 1
end
puts %{
PI approximation - #{@approximation}
denominator - #{@denominator}
sum - #{@sum}
signal - #{@signal}
}
puts "Loop again? (y|n)"
answer = gets.chomp!
print_approx times unless answer == 'n'
end
def reset
@approximation = 0
@denominator = 1.0
@sum = 0
@signal = true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment