Numerical integration in C++

后端 未结 4 410
Happy的楠姐
Happy的楠姐 2020-12-29 16:21

I need to integrate a function (of two variables). I know I can do it by using Fubini theorem to integrate one variable functions, then using numerical methods such

4条回答
  •  臣服心动
    2020-12-29 16:42

    You can use the GNU Scientific Library, which supports many "Numerical analysis" functions including integration.

    A very simple example of integration from the manual is just a few lines of code:

    #include 
    #include 
    #include 
    
    double f (double x, void * params) {
      double alpha = *(double *) params;
      return log(alpha*x) / sqrt(x);
    }
    
    int
    main (void)
    {
      double result, error;
      double expected = -4.0;
      double alpha = 1.0;
      gsl_integration_workspace * w 
        = gsl_integration_workspace_alloc (1000);
    
      gsl_function F;
      F.function = &f;
      F.params = α
    
      gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000,
                            w, &result, &error); 
    
      printf ("result          = % .18f\n", result);
      printf ("exact result    = % .18f\n", expected);
      printf ("estimated error = % .18f\n", error);
      printf ("actual error    = % .18f\n", result - expected);
      printf ("intervals =  %d\n", w->size);
    
      gsl_integration_workspace_free (w);
    
      return 0;
    }
    

提交回复
热议问题