Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / Numerical analysis / Project.wl
blob: 9eb49f748ce6ed877311686394b716fac8ac309d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
(*----------
 * 1 задача
 *----------*)
ApproxIntegral[M_, a_, b_, f_] := With[
  {
    h=(b-a)/(2M),
    xk=Function[k,a+k*(b-a)/(2M)]
  },
   (h/3) (f[a] + f[b]) +
  (2h/3) Sum[f[xk[2k]],   {k, 1, M-1}] +
  (4h/3) Sum[f[xk[2k-1]], {k, 1, M}]
]

Integrand[x_] := 1/((1 + 2x^2)^5)
m15 := N[ApproxIntegral[15, -1, 1, Integrand], {Infinity,20}]
m50 := N[ApproxIntegral[50, -1, 1, Integrand], {Infinity,20}]
correct := N[Integrate[Integrand[x], {x, -1, 1}], {Infinity,20}]

Print["1 задача)"]
Print["При M=15:        ", m15]
Print["Разлика с точен: ", N[correct-m15,{Infinity,20}]]
Print["При M=50:        ", m50]
Print["Разлика с точен: ", N[correct-m50,{Infinity,20}]]
Print["Точна стойност:  ", correct]

(*----------
 * 2 задача
 *----------*)

(* Намиране Pn *)
Pncoeff [xs_, f_] := With[
  {
    k  = Length[xs],
    x0 = First[xs],
    xk = Last[xs]
  },
  Piecewise[{
    {
      f[xk],
      k == 1
    },
    {
      (Pncoeff[Drop[xs, 1], f] - Pncoeff[Drop[xs, -1], f])/(xk - x0),
      x0 != xk
    },
    {
      (D[f[y], {y, k-1}] /. y->x0)/((k-1)!),
      x0 == xk
    }}]
]

Pn[f_,xsWithDup_] := With[
  { xs = xsWithDup },
  Function[x,Sum[
    Pncoeff[Take[xs, i], f] *
    Product[x - xs[[j]], {j, 1, i-1}],
    {i, 1, Length[xs]}
  ]]
]

f[x_]:= Piecewise[{
    {Cos[3x],    x <= Pi},
    {x - Pi - 1, x > Pi}
  }]
values := {9Pi/10, 9Pi/10, 9Pi/10, 10Pi/11, 10Pi/11, 11Pi/10}
newtonpolyn := Pn[f, values]

Print["2 задача)"]
Print["Полином: ", Simplify[newtonpolyn[x]]]
(* InterpolatingPolynomial[{{9Pi/10, f[9Pi/10]}, {10Pi/11, f[10Pi/11]}, {11Pi/10, f[11Pi/10]}}, x] *)

(* Графика разлика *)
Print["Графика на разлика:"]
Plot[Abs[f[z] - newtonpolyn[z]], {z, -6.5, 12}]