Add pi approximation as an example

This commit is contained in:
Neemek 2024-12-29 14:51:54 +01:00
parent 6b90cc488e
commit cf8268a4d7
Signed by: neemek
GPG key ID: 28360A8951CD0E9B

48
examples/pi-approx.ang Normal file
View 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)