CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

| Download
Project: test
Views: 91872
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Thu Mar 19 08:26:08 2015
4
5
@author: rlabbe
6
"""
7
8
import numpy as np
9
import matplotlib.pyplot as plt
10
11
from math import sin, cos, factorial
12
def df(x, p):
13
if p == 0:
14
return sin(x)
15
16
return x
17
if p % 4 == 1:
18
return cos(x)
19
20
if p % 4 == 2:
21
return -sin(x)
22
23
if p % 4 == 3:
24
return -cos(x)
25
26
return sin(x)
27
28
29
30
31
def taylor(df, x, a, n):
32
33
f = 0.0
34
35
for i in range(n+1):
36
term = df(a, i) * (x - a)**i / factorial(i)
37
f += term
38
39
return f
40
41
42
x = 0.1
43
a = 0.8
44
n = 1
45
46
47
48
plt.cla()
49
50
xs = np.linspace(-2, 2, 100)
51
ts = [taylor(df, i, a, n) for i in xs]
52
53
plt.plot(xs, np.sin(xs))
54
plt.plot(xs, ts)
55
56
57
58