Ex-2 Taylor
Ex-2 Taylor
26/7/24
AIM:
To implement Python code to execute Taylor's Sales and to find error
approximation.
ALGORITHM:
CODE:
#METHOD1 :1/(1-x)=x^0+x^1+x^2+x^3+...+x^n
x=float(input("Enter X:"))
n=int(input("Terms n:"))
import math
s,i=0,0
while i<=n:
Term=x**i
s+=Term
i+=1
print("The sum of the series:",s)
OUTPUT:
Enter X:0.5
Terms n:5
The sum of the series: 1.96875
#METHOD2: e^x=x^0/0!+x^1/11+x^2/2!+x^3/3!+...+x^n/n!
import math
import matplotlib.pyplot as plt
def fact(n):
if n == 0:
return 1
return n * fact(n - 1)
x = float(input("Enter X: "))
for n in n_values:
s=0
for i in range(n + 1):
Term = (x ** i) / fact(i)
s += Term
error = math.exp(x) - s
errors.append(error)
plt.figure(figsize=(8, 5))
plt.plot(n_values, errors, marker='o')
plt.title(f'Error Approximation for e^{x} Series Expansion')
plt.xlabel('Number of Terms (n)')
plt.ylabel('Error Approximation')
plt.show()
OUTPUT:
#METHOD3 e^-x=x^0/0!-x^1/1!+x^2/2!-x^3/3!+...+x^n/n!
import math
import matplotlib.pyplot as plt
def fact(n):
if n == 0:
return 1
return n * fact(n - 1)
x = float(input("Enter X: "))
plt.figure(figsize=(8, 5))
plt.plot(n_values, errors, marker='o')
plt.title(f'Error Approximation for e^{-x} Series Expansion')
plt.xlabel('Number of Terms (n)')
plt.ylabel('Error Approximation')
plt.show()
OUTPUT:
#METHOD4 sinx=x^1/1!-x^3/3!+x^5/5!-x^7/7!+...+x^2i-1/2i-1!
import math
import matplotlib.pyplot as plt
def fact(n):
if n == 0:
return 1
return n * fact(n - 1)
x = float(input("Enter X: "))
for n in n_values:
s=0
for i in range(n + 1):
Term = ((-1)**i)*((x**((2*i)+1))/fact((2*i)+1))
s += Term
error = (math.sin(x))-s
errors.append(error)
plt.figure(figsize=(8, 5))
plt.plot(n_values, errors, marker='o')
plt.title(f'Error Approximation for sin{x} Series Expansion')
plt.xlabel('Number of Terms (n)')
plt.ylabel('Error Approximation')
plt.show()
OUTPUT:
#METHOD5 cosx=1-x^2/2!+x^4/4!-x^6/6!+x^8/8!+...+x^2i/2i!
import math
import matplotlib.pyplot as plt
def fact(n):
if n == 0:
return 1
return n * fact(n - 1)
x = float(input("Enter X: "))
for n in n_values:
s=0
for i in range(n + 1):
Term = ((-1)**i)*((x**((2*i)))/fact((2*i)))
s += Term
error = (math.cos(x))-s
errors.append(error)
plt.figure(figsize=(8, 5))
plt.plot(n_values, errors, marker='o')
plt.title(f'Error Approximation for cos{x} Series Expansion')
plt.xlabel('Number of Terms (n)')
plt.ylabel('Error Approximation')
plt.show()
OUTPUT:
RESULT:
Taylor series of 1/(1-x) , exp(x), exp(-x), Sin(x) and Cos(x) has been executed
using python code and error approximations has been plotted.