Created
January 6, 2017 22:33
-
-
Save thoolihan/86237ebcc7101673a13aba2e76520bfc to your computer and use it in GitHub Desktop.
Implementing sin in numpy with a taylor series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from math import factorial | |
def sin(x): | |
val = np.float64(0) | |
for n in range(0, 25): | |
term = (((-1) ** n) * (x ** (2*n+1)) / factorial(2*n + 1)) | |
val += term | |
print("for x_{0}, term is {1}, sin({2}) approximation is {3}".format( | |
n, term, x, val)) | |
return val | |
pi = np.float64(3.1415926) | |
pi = pi + sin(pi) | |
if __name__ == "__main__": | |
vals = np.array([0, pi / 4., pi / 2., pi * 3./4., pi], dtype=np.float64) | |
for n in vals: | |
print("sin({0}) = {1}".format(n, sin(n))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment