Advertisement
Tooster

Untitled

Dec 19th, 2018
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. using Plots
  2. runge = x->1/(1+x^2)
  3. f = x->1/(1+25x^2)
  4. #P2D to macierz Nx2 o wierszach [x y]
  5. # współczynniki ilorazów dla interp. Newtona
  6. function _diff(P2D)
  7. b, n = Array(P2D[:, 2]), length(P2D[:, 1])
  8. for i = 2:n
  9. for j = n:-1:i
  10. b[j] = (b[j] - b[j-1])/(P2D[j, 1] - P2D[j-i+1, 1])
  11. end
  12. end
  13. return b
  14. end
  15.  
  16. # Zwraca wartość ilorazu.
  17. function diff(P2D)
  18. last(_diff(P2D))
  19. end
  20.  
  21. function interp_newton(P2D)
  22. return function(x)
  23. b, n = _diff(P2D), length(P2D[:, 1])-1
  24. sum, p = b[1], 1
  25. for i in 1:n
  26. p *= (x - P2D[i, 1])
  27. sum += b[i+1]*p
  28. end # nie chce mi się robić Hornera
  29. sum
  30. end
  31. end;
  32.  
  33. err = f_interp->x->abs(f(x)-f_interp(x))
  34. maxerr = f_interp->reduce(max, map(x->err(f_interp)(x), range(-1,stop=1,length=1000)))
  35. w9_eq = interp_newton(reduce(vcat, map(x->[x f(x)], collect(range(-1,stop=1, length=10))))) # w równoodległych
  36. w9_T10_zeros = interp_newton(reduce(vcat, map(x->[x f(x)], map(j->cos(pi*((2*j-1)/(2*10))), [1:10;])))) # w zerach Czebyszewa
  37. w9_T9_extremums = interp_newton(reduce(vcat, map(x->[x f(x)], map(j->cos(j*pi/9), [0:9;])))) # w extremach Czebyszewa
  38.  
  39. equal_plot = begin
  40. plot(f, -1, 1, line=(color=:blue), label="f", title="equal")
  41. plot!(w9_eq, line=(color=:green), label="equal")
  42. plot!(err(w9_eq), line=(color=:red),fill=(0, 0.1, :red), label="EQ error")
  43. annotate!(-1, 2, text(string("max error: ", maxerr(w9_eq)), 10, :left, :top, :crimson))
  44. end
  45. Chebyshev_zeros_plot = begin
  46. plot(f, -1, 1, line=(color=:blue), label="f", title="Chebyshev's zeros")
  47. plot!(w9_T10_zeros, line=(color=:green), label="Ch. zeros")
  48. plot!(err(w9_T10_zeros), line=(color=:red),fill=(0, 0.1, :red), label="CH. zeros error")
  49. annotate!(-1, 2, text(string("max error: ", maxerr(w9_T10_zeros)), 10, :left, :top, :crimson))
  50. end
  51. row1_plot = plot(equal_plot, Chebyshev_zeros_plot, layout=(1,2), ylims=(-0.3, 2))
  52.  
  53. Chebyshev_extremums_plot = begin
  54. plot(f, -1, 1, line=(color=:blue), label="f", title="Chebyshev's extremums")
  55. plot!(w9_T9_extremums, line=(color=:green), label="Ch. extremums")
  56. plot!(err(w9_T9_extremums), line=(color=:red), fill=(0, 0.1, :red), label="CH. extremums error")
  57. annotate!(-1, 1, text(string("max error: ", maxerr(w9_T9_extremums)), 10, :left, :top, :crimson))
  58. end
  59. plot(row1_plot, Chebyshev_extremums_plot, layout=(2,1), size=(900, 600), fmt=:png)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement