Add pi approximation as an example
This commit is contained in:
parent
6b90cc488e
commit
cf8268a4d7
1 changed files with 48 additions and 0 deletions
48
examples/pi-approx.ang
Normal file
48
examples/pi-approx.ang
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
# This program computes an approximation of pi using the proof
|
||||
# of the basel problem. It requires many terms to calculate a
|
||||
# good approximation.
|
||||
# see: https://en.wikipedia.org/wiki/Basel_problem
|
||||
|
||||
# The amount of terms
|
||||
terms := 10000
|
||||
|
||||
# The running sum of terms
|
||||
tot := 0
|
||||
|
||||
n := 1
|
||||
while n <= terms {
|
||||
tot = tot + 1 / (n*n)
|
||||
n = n + 1
|
||||
}
|
||||
|
||||
tot = tot * 6
|
||||
|
||||
# get the absolute value of a number
|
||||
func abs(x) {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
# calculate an approximation of the square root of tot using
|
||||
# newton's method.
|
||||
# see: https://en.wikipedia.org/wiki/Newton's_method
|
||||
# The required accuracy
|
||||
SQRT_ACC := 0.00001
|
||||
func sqrt(x) {
|
||||
pg := 0 # previous guess
|
||||
g := 1 # current guess
|
||||
|
||||
while abs(pg - g) >= SQRT_ACC {
|
||||
pg = g
|
||||
g = (pg + tot/pg)/2
|
||||
}
|
||||
|
||||
return g
|
||||
}
|
||||
|
||||
tot = sqrt(tot)
|
||||
|
||||
# output the result
|
||||
write(tot)
|
||||
Loading…
Add table
Add a link
Reference in a new issue