I have a problem!! I need to do a "first three terms taylor's series graph of Acos(Bx) from x1 to x2. I have to get inputs from user and I want A,B,x1 and x2 as a float number. I handled the formula so I will put it in here. I NEED HELP ABOUT GRAPH. It doesn't works I don't know why its happening, please help me. Here is the codes:
import matplotlib.pyplot as plt
import numpy as np
A = float(input("For A, please enter a value: "))
B = float(input("For B, please enter a value: "))
x1 = float(input("For x1, please enter a value between -10 and +10: "))
if (-10)<=x1<=(10):
x2 = float(input("For x2, please enter a value between -10 and +10: "))
else:
print ("x1 must be greater than or equal to -10 OR less than or equal to 10")
quit()
a0 = A*np.cos(B*(x1))
a1 = ((-A)*B)*np.sin(B*(x1))
a2 = ((-A)*(B**2))*np.cos(B*(x1))
data1 = (((a0)*((x1-x2)**0))/np.math.factorial(0))
data2 =(((a0)*((x1-x2)**0))/np.math.factorial(0))+(((a1)*((x1-x2)**1))/np.math.factorial(1))
data3 = (((a0)*((x1-x2)**0))/np.math.factorial(0))+(((a1)*((x1-x2)**1))/np.math.factorial(1))+(((a2)*((x1-x2)**2))/np.math.factorial(2))
plt.figure()
plt.plot(data1, label="1. term",color="red")
plt.plot(data2, label="2. term",color="yellow")
plt.plot(data3, label="3. term",color="green")
plt.xlabel("x label")
plt.ylabel("y label")
plt.axis([-10,10,-10,10])
plt.show()
To plot a curve, a list of x values and a list of corresponding y values needs to be given.
Numpy has a convenient way to create a list of x values from x1 to x2: e.g. np.linspace(x1, x2, 200)
to have a list of 200 values. Numpy's broadcasting and vectorization then can create a complete list of y values in a compact way: y = f(x)
Note that in your formulas for the Taylor expansion, you need the value of the derivatives at x - x1
, not at x1 - x2
. The first term is constant, with the value at x1. The second term also has the tangent line correct. The third term adjusts the curvature.
Here is some code to get you started.
import matplotlib.pyplot as plt
import numpy as np
A = 4
B = 0.3
x1 = -9
x2 = 8
a0 = A*np.cos(B*(x1))
a1 = ((-A)*B)*np.sin(B*(x1))
a2 = ((-A)*(B**2))*np.cos(B*(x1))
x = np.linspace(x1, x2, 200)
data1 = (((a0)*((x-x1)**0))/np.math.factorial(0))
data2 = data1 + (((a1)*((x-x1)**1))/np.math.factorial(1))
data3 = data2 + (((a2)*((x-x1)**2))/np.math.factorial(2))
plt.figure()
plt.plot(x, data1, label="1. term" ,color="crimson")
plt.plot(x, data2, label="2. term", color="gold")
plt.plot(x, data3, label="3. term", color="limegreen")
plt.plot(x, A*np.cos(B*x), label="A·cos(B·x)", color="dodgerblue", ls='--')
plt.xlabel("x")
plt.ylabel("y")
plt.axis([-10,10,-10,10])
plt.legend()
plt.show()