Skip to content

Instantly share code, notes, and snippets.

@tillson
Last active November 14, 2018 22:11
Show Gist options
  • Save tillson/8848013a999f9eca551f8c69be7cdaef to your computer and use it in GitHub Desktop.
Save tillson/8848013a999f9eca551f8c69be7cdaef to your computer and use it in GitHub Desktop.
taylor.swift
//: Calculate the value of pi by integrating arctan's Taylor Series
/*:
arctan(1) - arctan(0) == integral of 1/(1+x^2) from 0 to 1
arctan(1) - 0 = pi/4
the sum 1/(1+x^2) is geometric, we can rewrite in the form of Sn = 1/1-r in order to easily write it as a taylor series
Sn = 1/(1 - (-x^2))
taylor series for arctan is therefore (-x^2)^n
= (-1)^n * (x^2n)
1 - x^2 + x^4 - x^6 + ...
integrate that, and you get...
1 - x^3/3 + x^5/5 - x^6/6 + ...
starting with an index of zero at, the nth term is:
(-1)^n * x/(2n+1)
we're integrating from 0 to 1, and the term will end up being zero for x=0, so we can simplify to:
pi/4 = (-1)^n * 1/(2n+1)
pi = 4 * ((-1)^n * 1/(2n+1))
*/
import Foundation
var sum = 0.0
var errorAtIndex = [Double]()
for i in 0..<1000 {
let doubleTypeN = Double(i)
let value = Double(pow(-1, doubleTypeN)) * Double(1/(2*doubleTypeN + 1)) * 4
let percentError = abs(sum - .pi) / .pi * 100
errorAtIndex.append(percentError)
sum += value
}
print("Calculated value of pi at n=1000: \(sum)")
// "Calculated value of pi at n=1000: 3.140592653839794"
// the swift playground can render this as a graph.
errorAtIndex.map() { $0 }
print("Percent error at n=1000: \(errorAtIndex.last!)")
// "Percent error at n=1000: 0.03186284348822856"
print("Error margin at n=1000: \(abs(.pi - sum))")
// "Error margin at n=1000: 0.000999999749998981"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment