# lab2_based

Oct 27th, 2021 (edited)
165
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import numpy as np
2. import matplotlib.pyplot as plt
3. from scipy import integrate
4.
5. T = 1.75418438
6. C = 1.03439984
7. g = 9.8
8. exactValue = (T - 1e-7) * np.sqrt(2 * C / g)
9. print(exactValue)
10.
11.
12. def Ft(t):
13.     return (1 / np.sqrt(g)) * np.sqrt((1 + ((np.sin(2 * t) ** 2) / (1 - np.cos(2 * t)) ** 2))/(C * (1 - np.cos(2 * t)))) \
14.             * C * (1 - np.cos(2 * t))
15.
16.
17. def compositeSimpson(a, b, n):
18.     # n - number of dots
19.     # n - 1 - number of intervals. Must be even
20.     # nodes sum via odd and even indexes
21.     if (n - 1) % 2 != 0:  # if number of intervals isn't even
22.         n = n + 1
23.     dotsNumber = n
24.     intervalsNumber = n - 1
25.     h = (b - a) / intervalsNumber
26.     nodesT = []
27.
28.     for i in range(1, dotsNumber + 1):
29.         nodesT.append(a + (i - 1) * h)
30.
31.     oddSum = evenSum = 0
32.
33.     for index, item in enumerate(nodesT):
34.         if index == 0 or index == n - 1:
35.             continue
36.         if index % 2 != 0:   # for odd indexes
37.             # print(index, item)
38.             evenSum += Ft(item)
39.         else:       # for even indexes
40.             oddSum += Ft(item)
41.     oddSum *= 2
42.     evenSum *= 4
43.     return (Ft(nodesT[0]) + oddSum + evenSum + Ft(nodesT[n - 1])) * h / 3
44.
45.
46. def compositeTrapezoid(a, b, n):
47.     # n - number of dots
48.     # n - 1 - number of intervals.
49.     dotsNumber = n
50.     intervalsNumber = n - 1
51.     h = (b - a) / intervalsNumber
52.     nodesT = []
53.     sum = 0
54.
55.     for i in range(1, dotsNumber + 1):
56.         nodesT.append(a + (i - 1) * h)
57.     # print(len(nodesT))
58.     for i in range(1, n - 1):
59.         sum += Ft(nodesT[i])
60.
61.     sum *= 2
62.
63.     return (Ft(nodesT[0]) + sum + Ft(nodesT[n - 1])) * h / 2
64.
65.
66. def calculateInaccuracy(a, b):
67.     # n - 1 - number of intervals
68.     # n - number of dots
69.     inaccuracyValuesSimpson = []
70.     inaccuracyValuesTrapezoid = []
71.     hValues = []
72.     for n in range(3, 10000, 100):
73.         inaccuracyValuesSimpson.append(np.abs(exactValue - compositeSimpson(a, b, n)))
74.         inaccuracyValuesTrapezoid.append(np.abs(exactValue - compositeTrapezoid(a, b, n)))
75.         hValues.append((b - a) / (n - 1))
76.     plt.loglog(hValues, inaccuracyValuesSimpson, 'o', color='black')
77.     plt.loglog(hValues, inaccuracyValuesTrapezoid, 'o', color='red')
78.     plt.title('Dependence of the absolute error of numerical integration on the integration step', color='grey')
79.     plt.legend(['Simpson method', 'Trapezoid method'], loc=0)
80.     plt.xlabel('Integration step', color='grey')
81.     plt.ylabel('Absolute inaccuracy', color='grey')
82.     plt.grid(True)
83.     plt.show()
84.
85.
RAW Paste Data