## 0 Replies - 1394 Views - Last Post: 23 November 2009 - 03:02 PM

### #1 erik.price Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

# Leibniz formula for finding pi

Posted 23 November 2009 - 03:02 PM

Description: Uses a simple formula to estimate pi. It is functional, but not the most optimal formula as it requires quite a few iterations to produce accurate results
```#The Leibniz formula: 1-(1/3)+(1/5)-(1/7)+(1/9)...

def pi(prec)
denom = 3.0
mod = -1.0
result = 1.to_f
i = 0
while( i < prec)
result += mod*((1.0/denom))
denom += 2
mod *= -1
i += 1
end
#the formula returns pi/4, so to get the approximation of pi, we multiply by 4
result *= 4.0
return result
end

#Example:

puts pi(3423231) #=>3.14159236146807

#note that there is no significance to "3423231", but was just an arbitrary number I used
```

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }