Alex

Fixed Point Calculations and Finding Roots

Fixed Points

Example of fixed point of cosx
double fixed_point(double f(double), int max_it, double init) {
  double x = init;
  for (int i = 0; i < max_it; i++) 
    x = f(x);
  return x;
}
fixed_point([](double x) -> double { return std::cos(x); }, 100, 0.75) // calculating the fixed point of the cosine function

Finding Roots of Equations Iteratively

double fixed_point(double f(double), int max_it, double init, double epsilon = 1e-10) {
  double x = init;

  for (int i = 0; i < max_iterations; i++) {
    double x1 = f(x);

    double error = fabs(x1-x);
    if (error < epsilon)
      break

    x = x1;
  }

  return x
}

Template Functions

template <typename Float>
Float fixed_point(Float f(Float), int max_it, Float init, Float epsilon = 1e-10) {
    Float x = init;
    for (int i = 0; i < max_it; i++) {
        Float x1 = f(x);
        if (fabs(x1-x) < epsilon) break;
        x = x1; 
    }
    return x;
}
template <typename Data>
std::pair<Data, int> fixed_point(Data f(Data), bool cond(Data, Data), int n, Data init) {
    Data x = init;
    for (int i = 0; i < n; i++) {
        Data x1 = f(x);
        if (cond(x, x1)) return {x1, i}; // we also generalise the break condition for flexibility
        x1 = x;
    }
    return {x, n};
}

// example of using this final fixed point function
using float_type = double;
fixed_point(
    [](float_type x) { return cbrt(sin(x)); },
    [](float_type prev, float_type curr) { return fabs(curr - prev) < 1e-10; },
    1000,
    float_type(1.0)
)

Finding Square Roots

template <typename Float>

Float sqrt(Float a, int n, Float init) {
    return fixed_point([a](Float x) { return average(x,a/x); }, n, init);
}

Other Methods for Finding Roots