[Solved] Fast way to calculate solution of a triangular equation c++ [closed]


You can reformulate your equation as

sin (a x) + b sin (c x) – d * x – e == 0

Now, this is a root finding problem. Here is a list for root finding algorithms.

Newton’s method is very fast and easy to implement, since the derivative of your equation can be calculated analytically.

#include <array>
#include <iostream>
#include <cmath>

template <typename T> double func(const T &parameter, const double x) {
  const auto a = parameter[0];
  const auto b = parameter[1];
  const auto c = parameter[2];
  const auto d = parameter[3];
  const auto e = parameter[4];
  return sin(a * x) + b * sin(c * x) - (d * x + e);
}

template <typename T> double derivative(const T &parameter, const double x) {
  const auto a = parameter[0];
  const auto b = parameter[1];
  const auto c = parameter[2];
  const auto d = parameter[3];

  return a * cos(a * x) + b * c * cos(c * x) - d;
}

template <typename T> double solve(const T &parameter) {
  double x = 0.0;
  const double eps = 1e-9;
  while (fabs(func(parameter, x)) > eps) {
    x = x - func(parameter, x) / derivative(parameter, x);
  }
  return x;
}

int main() {
  const std::array<double, 5> parameter{1.1, 1.2, 0.9, 0.1, 0.1};
  const auto x = solve(parameter);
  std::cout << "solution is x=" << x << " f(x)=" << func(parameter, x) << '\n';
}

Go from double to float to speed it up, if your desired accuracy allows that.

solved Fast way to calculate solution of a triangular equation c++ [closed]