Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #define _USE_MATH_DEFINES
  2. #include <fstream>
  3. #include <iostream>
  4. #include <math.h>
  5. #include <iomanip>
  6. #include <ctype.h>
  7.  
  8. using namespace std;
  9.  
  10. template<typename T>
  11. using func = T(*)(T, T);
  12.  
  13. template <typename T>
  14. T fun(T x) {
  15. return cos(x / 2.);
  16. }
  17.  
  18. template <typename T>
  19. T poch(T x) {
  20. return -0.5 * sin(x / 2.);
  21. }
  22.  
  23. template <typename T>
  24. T progresywna(T h, T x) {
  25. return (fun(x + h) - fun(x)) / h;
  26. }
  27.  
  28. template <typename T>
  29. T wsteczna(T h, T x) {
  30. return (fun(x) - fun(x - h)) / h;
  31. }
  32.  
  33. template <typename T>
  34. T centralna(T h, T x) {
  35. return (fun(x + h) - fun(x - h)) / (2 * h);
  36. }
  37.  
  38. template <typename T>
  39. T x0_3pkt(T h, T x) {
  40. return (-1.5*fun(x) + 2 * fun(x + h) - 0.5*fun(x + 2 * h)) / h;
  41. }
  42.  
  43. template <typename T>
  44. T xn_3pkt(T h, T x) {
  45. return (0.5*fun(x - 2 * h) - 2 * fun(x - h) + 1.5*fun(x)) / h;
  46. }
  47.  
  48. template <typename T>
  49. void plot(string name, T x, func<T> f) {
  50. T h = 0.2;
  51. ofstream outfile(name);
  52.  
  53. for (int i = 0; i < 100; i++) {
  54. outfile << log10(h) << " " << log10(fabs(poch(x) - f(h, x))) << endl;
  55. h /= 2.0;
  56. }
  57.  
  58. outfile.close();
  59. }
  60.  
  61. template <typename T>
  62. void make_plot(T x0, T xn, T xc) {
  63. string name = typeid(T).name();
  64. plot(name + "1.txt", x0, progresywna);
  65. plot(name + "2.txt", x0, x0_3pkt);
  66. plot(name + "3.txt", xn, wsteczna);
  67. plot(name + "4.txt", xn, xn_3pkt);
  68. plot(name + "5.txt", xc, progresywna);
  69. plot(name + "6.txt", xc, wsteczna);
  70. plot(name + "7.txt", xc, centralna);
  71. }
  72.  
  73. int main() {
  74. make_plot<double>(0, M_PI, M_PI / 2);
  75. make_plot<float>(0, M_PI, M_PI / 2);
  76. return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement