В следующем коде я пытаюсь добавить индекс к моему графику, чтобы я мог пометить две разные строки. Однако я сталкиваюсь со следующей ошибкой, как я могу это исправить?
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-115-3c7429a6498c> in <module>()
36 n_inv_4.append(1.0 / ((2*i)**4))
37 n_lines = plt.loglog(n, n_inv_4)
---> 38 plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), ('upper right'))
39 plt.show()
TypeError: 'Text' object does not support indexing
и вот мой код, ниже у меня есть изображение, которое он выводит:
from math import pi, cos, sin
from matplotlib import pyplot as plt
def simpson(f, a, b, n):
h = (b - a) / (2*n)
s = f(a) + f(b)
for i in range(1, 2*n, 2):
s += 4 * f(a + i * h)
for i in range(2, 2*n-1, 2):
s += 2 * f(a + i * h)
return s * h / 3
diffs = {}
exact = 1 - cos(pi/2)
for n in range(1, 100):
result = simpson(lambda x: sin(x), 0.0, pi/2, n)
diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.
ordered = sorted(diffs.items())
x,y = zip(*ordered)
plt.autoscale()
plt.loglog(x,y)
error_lines = plt.xlabel("Intervals n")
plt.ylabel("Absolute Error")
n = []
n_inv_4 = []
for i in range(1,100):
n.append(2*i)
n_inv_4.append(1.0 / ((2*i)**4))
n_lines = plt.loglog(n, n_inv_4)
plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), ('upper right')
plt.show()
и вот вывод:
