C++ realized dichotomy to find the root of continuous unary function

  • 2020-10-07 18:49:20
  • OfStack

The example of this paper shares the specific code of C++ to realize the 2-cent method to find the root of continuous 1-yuan function, for your reference, the specific content is as follows

A universal function solve is designed to find the root of a continuous function of 1 element by the method of 2 points
This function takes three arguments:

The first is a function pointer to a continuous function at the desired root The 2.3 argument indicates the interval of the root and ensures that the function is marked differently at both ends of the interval

The return value of the function is the resulting solution

main functions are required to be written as follows:


double fun(double x)
{
 double y;
 y=4*pow(x,3)-6*pow(x,2)+3*x-2;
 return y;
}

int main()
{
 cout<<"4*x^3-6*x^2+3*x-2=0 In the interval (1 . 2) The root of  x="<<solve(fun,1,2);
 return 0;
}

C + + implementation:


#include <iostream>
#include <cmath>

using namespace std;

double solve(double (*fun)(double x), double a, double b);

double fun(double x);

int main() {
 cout << "4*x^3-6*x^2+3*x-2=0 In the interval (1 . 2) The root of  x=" << solve(fun, 1, 2);
 return 0;
}

double solve(double (*fun)(double x), double a, double b) {
 double i = b - a;
 double c = (a + b) / 2;
 while (i > 0.0000001) {
 i = b - a;
 if (fun(c) == 0)return c;
 if (fun(c) * fun(a) < 0) {
  b = c;
  c = (a + b) / 2;
 } else {
  a = c;
  c = (a + b) / 2;
 }
 }
 return c;
}

double fun(double x) {
 double y;
 y = 4 * pow(x, 3) - 6 * pow(x, 2) + 3 * x - 2;
 return y;
}

Conclusion:

A combination of functions and Pointers Note the type and requirement of the return

Related articles: