C ++中的数值积分 [英] Numerical integration in C++
问题描述
我需要集成一个函数(包含两个变量)。
我知道我可以通过使用 Fubini定理集成一个变量函数,然后使用诸如 Rectangle方法或梯形规则的数值方法来做到这一点。
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 as the Rectangle method or the Trapezoidal rule.
但是在 C ++ 中是否有任何预建函数可以做到这一点?我需要对单元 R2
三角形(((0,0),(1,0),(0,1))
。
But are there any pre-built functions to do that in C++? I need to integrate over the unit R2
triangle ((0,0), (1,0), (0,1))
.
推荐答案
您可以使用 GNU科学库,它支持许多数值分析功能,包括集成。
You can use the GNU Scientific Library, which supports many "Numerical analysis" functions including integration.
一个非常简单的<手册中的href = https://www.gnu.org/software/gsl/manual/html_node/Numerical-integration-examples.html rel = noreferrer>集成示例仅是其中的一部分代码行:
A very simple example of integration from the manual is just a few lines of code:
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
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;
}
这篇关于C ++中的数值积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!