How can I plot a graph for the variables n and errorp?
Question:
import math
x= float(input())
term = 1
sum = 1
n = 1
eps = 10**-7
while abs(term/sum) > eps:
term = -x/n * term
sum = sum + term
n = n + 1.
print (n)
print (sum)
error = 100 - (sum * 100 /math.exp(-x))
print(abs(error), "%")
The above code calculates the value of e^-x to a certain accuracy and compares it to the value of the built-in function. I’m trying to plot a graph between n (The number of iterations needed to reach the desired accuracy) and errorp (The error in the value after every iteration). I have imported matplotlib and tried using a list but didn’t work. It doesn’t let me append any values, and each list I make contains only the final value rather than the values of errorp after every iteration. So, the graph doesn’t even show.
How can I plot the relation between them?
Thanks in advance.
Answers:
You should store the error values in a list. Append the computed error at each step of the loop. Then plot the iteration and error lists against eachother:
import matplotlib.pyplot as plt
import math
x=float(input("Enter x value: "))
term = 1
s = 1
n = 1
eps = 10**-7
error_lst = []
while abs(term/s) > eps:
term = -x/n * term
s = s + term
error_lst.append(abs(100 - (s * 100 /math.exp(-x))))
n = n + 1.
fig, ax = plt.subplots()
ax.plot(range(1, int(n)), error_lst)
ax.set_title(f"Iterations for x={x} (approx. of exp({-x}))")
ax.set_xlabel('iterations')
ax.set_ylabel('error in %')
plt.show()
Output:
import math
x= float(input())
term = 1
sum = 1
n = 1
eps = 10**-7
while abs(term/sum) > eps:
term = -x/n * term
sum = sum + term
n = n + 1.
print (n)
print (sum)
error = 100 - (sum * 100 /math.exp(-x))
print(abs(error), "%")
The above code calculates the value of e^-x to a certain accuracy and compares it to the value of the built-in function. I’m trying to plot a graph between n (The number of iterations needed to reach the desired accuracy) and errorp (The error in the value after every iteration). I have imported matplotlib and tried using a list but didn’t work. It doesn’t let me append any values, and each list I make contains only the final value rather than the values of errorp after every iteration. So, the graph doesn’t even show.
How can I plot the relation between them?
Thanks in advance.
You should store the error values in a list. Append the computed error at each step of the loop. Then plot the iteration and error lists against eachother:
import matplotlib.pyplot as plt
import math
x=float(input("Enter x value: "))
term = 1
s = 1
n = 1
eps = 10**-7
error_lst = []
while abs(term/s) > eps:
term = -x/n * term
s = s + term
error_lst.append(abs(100 - (s * 100 /math.exp(-x))))
n = n + 1.
fig, ax = plt.subplots()
ax.plot(range(1, int(n)), error_lst)
ax.set_title(f"Iterations for x={x} (approx. of exp({-x}))")
ax.set_xlabel('iterations')
ax.set_ylabel('error in %')
plt.show()
Output: