gpt4 book ai didi

c++ - 复合辛普森规则无限输出

转载 作者:行者123 更新时间:2023-11-28 04:02:45 25 4
gpt4 key购买 nike

算法:enter image description here

我有以下代码使用复合辛普森规则计算不正确的积分,我正在尝试计算积分 exp(-x)/sqrt(1-x) 其中 a= 0 and b = 1 and while n=6 or the steps =6.但是,当它应该是 = 4.288

时,我一直让输出为无穷大
#include <cmath>
#include <iostream>
using namespace std;

double f(double x)
{


return exp(-x)/sqrt(1-x);
}

double simpson(double a, double b, double n)
{

double x0=f(a)+f(b);

double x1=0,x2=0;
double x=0;
double h=(b-a)/(n);
for(int i = 1 ; i <n;i++){

x=a+(h*i);
if(i%2==0)
{
x2=x2+f(x);
}
else
{
x1=x1+f(x);
}


}
return (h*(x0+2*x2+4*x1))/3;
;
}

int main(){
cout<<endl;
cout<<"The improper integral is: "<<simpson(0.00000009,1,6)<<" "<<endl;
cout<<endl;
}

最佳答案

我认为你的问题是你正在评估的函数 f(double x) 没有在 x = 1 处定义,因为它等于 exp(-1)/sqrt( 1 - 1) 除以零,但当 b 为 1 时,您在 simpson 的第一行调用 f(b)。因此,您是回归无限。您可能希望将 b 设置为 0.9999。如果您使用更大的 n 值来执行此操作以更接近实际曲线(例如 n = 400),您将非常接近 @macroland 在 Wolfram Alpha 上找到的实际答案 1.076。

关于c++ - 复合辛普森规则无限输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59237372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com