在 C++ 中使用梯形规则积分复数
Integration of complex numbers using trapezoidal rule in C++
#include <complex>
#include <iostream>
using namespace std;
complex<double> integral(complex<double> (*f)(complex<double> const &x), complex<double> l, complex<double> u, size_t n)
{
complex<double> step = (u - l) / (double) n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<double> inner = l + (i + 0.5) * step;
area = area + f(inner) / inner * step;
}
return area;
}
int main()
{
complex<double> l(0, 0);
complex<double> u(2, 1);
cout << integral(cos, l, u, 100);
}
我得到这个输出 (5.77123,-0.761154)
这个函数的积分是sin(i+2)=(1.403-0.489i) wolframalpha
我不知道可能是什么问题。
如评论所述,除以 inner
是一个无关的步骤。
complex<double> integral(complex<double> (*f)(complex<double> const &x), complex<double> l, complex<double> u, size_t n)
{
complex<double> step = (u - l) / (double) n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<double> inner = l + (i + 0.5) * step;
area += f(inner) * step;
}
return area;
}
#include <complex>
#include <iostream>
using namespace std;
complex<double> integral(complex<double> (*f)(complex<double> const &x), complex<double> l, complex<double> u, size_t n)
{
complex<double> step = (u - l) / (double) n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<double> inner = l + (i + 0.5) * step;
area = area + f(inner) / inner * step;
}
return area;
}
int main()
{
complex<double> l(0, 0);
complex<double> u(2, 1);
cout << integral(cos, l, u, 100);
}
我得到这个输出 (5.77123,-0.761154)
这个函数的积分是sin(i+2)=(1.403-0.489i) wolframalpha
我不知道可能是什么问题。
如评论所述,除以 inner
是一个无关的步骤。
complex<double> integral(complex<double> (*f)(complex<double> const &x), complex<double> l, complex<double> u, size_t n)
{
complex<double> step = (u - l) / (double) n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<double> inner = l + (i + 0.5) * step;
area += f(inner) * step;
}
return area;
}