update.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #define _USE_MATH_DEFINES
  2. #include <cmath>
  3. #include "../matplotlibcpp.h"
  4. #include <chrono>
  5. namespace plt = matplotlibcpp;
  6. void update_window(const double x, const double y, const double t,
  7. std::vector<double> &xt, std::vector<double> &yt)
  8. {
  9. const double target_length = 300;
  10. const double half_win = (target_length/(2.*sqrt(1.+t*t)));
  11. xt[0] = x - half_win;
  12. xt[1] = x + half_win;
  13. yt[0] = y - half_win*t;
  14. yt[1] = y + half_win*t;
  15. }
  16. int main()
  17. {
  18. size_t n = 1000;
  19. std::vector<double> x, y;
  20. const double w = 0.05;
  21. const double a = n/2;
  22. for (size_t i=0; i<n; i++) {
  23. x.push_back(i);
  24. y.push_back(a*sin(w*i));
  25. }
  26. std::vector<double> xt(2), yt(2);
  27. plt::title("Tangent of a sine curve");
  28. plt::xlim(x.front(), x.back());
  29. plt::ylim(-a, a);
  30. plt::axis("equal");
  31. // Plot sin once and for all.
  32. plt::named_plot("sin", x, y);
  33. // Prepare plotting the tangent.
  34. plt::Plot plot("tangent");
  35. plt::legend();
  36. for (size_t i=0; i<n; i++) {
  37. if (i % 10 == 0) {
  38. update_window(x[i], y[i], a*w*cos(w*x[i]), xt, yt);
  39. // Just update data for this plot.
  40. plot.update(xt, yt);
  41. // Small pause so the viewer has a chance to enjoy the animation.
  42. plt::pause(0.1);
  43. }
  44. }
  45. }