Skip to content

Instantly share code, notes, and snippets.

@cosinekitty
Created December 27, 2019 19:54
Show Gist options
  • Save cosinekitty/c8c5eea0945e3f79cd94bf80d1dd68b9 to your computer and use it in GitHub Desktop.
Save cosinekitty/c8c5eea0945e3f79cd94bf80d1dd68b9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# naive.py - by Don Cross
#
# Illustrates why 4*arctan(1) is not a good way to calculate pi.
# Calculates the series 4*(1/1 - 1/3 + 1/5 - 1/7 + ...)
import math
n = 1
polarity = +4
x = 0.0
error = 1.0
while error >= 1.0e-6:
x += polarity / n
error = abs(math.pi - x)
print('n={:15d}, x={:15.13f}, error={:10.6g}'.format(n, x, error))
polarity *= -1
n += 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment