x027.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <algorithm>
4 #include <cmath>
5 #include <iostream>
6 #include <numeric>
7 #include <vector>
8 
9 namespace nmx::apps::x027 {
10 
14 inline void ex1() {
15  //----------------------------------------------------------
16  // Berechnung der Geraden a1 x + a0, die durch die Punkte
17  // (x0,y0) und (x1,y1) geht
18  //--------------------------------------------------------
19  auto line = [](double x0, double y0, double x1, double y1) {
20  double a1 = (y1 - y0) / (x1 - x0);
21  double a0 = y1 - a1 * x1;
22  return std::make_pair(a0, a1);
23  };
24 
25  //----------------------------------------------------------
26  //für eine Gerade y(x) = a1 * x + a0 berechne y(x)
27  //----------------------------------------------------------
28  auto lininterp = [](double a0, double a1, double x) { //
29  return a0 + a1 * x;
30  };
31 
32  //**
33  //---------------------------------------------
34  //Erstellung von Beispieldaten (x,y)
35  //-----------------------------------------------
36  //reserviere Speicher für 20 Elemente
37  std::vector<double> xvalues(20), yvalues(20);
38  //fülle x = 0.1,0.2,...
39  double xval = 0;
40  std::generate(xvalues.begin(), xvalues.end(), [&xval]() { //
41  return xval += 0.1;
42  });
43  //fülle y = cos(x)
44  std::transform(xvalues.begin(),
45  xvalues.end(), //
46  std::begin(yvalues),
47  [](double x) { return std::cos(x); });
48 
49  //**
50  //-------------------------------------
51  //Berechnung von y(x=1.23)
52  //----------------------------------------
53  const double x = 1.23;
54  // suche 1.tes x_i >= x
55  auto itr = std::upper_bound(xvalues.begin(), xvalues.end(), x);
56  // wenn gefunden...
57  if (itr != xvalues.end()) {
58  // finde Index im Feld
59  auto idx = static_cast<size_t>(std::distance(xvalues.begin(), itr));
60  std::cout << "found index: " << idx //
61  << " with x=" << xvalues[idx] //
62  << " and y=" << yvalues[idx] << std::endl;
63  const double x0 = xvalues[idx - 1];
64  const double x1 = xvalues[idx];
65  const double y0 = yvalues[idx - 1];
66  const double y1 = yvalues[idx];
67  auto [a0, a1] = line(x0, y0, x1, y1);
68  std::cout << "(x0,y0)=(" << x0 << "," << y0 << ")" << std::endl;
69  std::cout << "(x1,y1)=(" << x1 << "," << y1 << ")" << std::endl;
70  std::cout << "(a0,a1)=(" << a0 << "," << a1 << ")" << std::endl;
71  std::cout << "x=" << x << std::endl;
72  std::cout << "interpolated value:" << lininterp(a0, a1, x) << std::endl;
73  std::cout << "true value:" << std::cos(x) << std::endl;
74  }
75 }
76 
77 } // namespace nmx::apps::x027
void ex1()
ex1 Berechnung von Daten mittels linearer Interpolation.
Definition: x027.h:14