gpt4 book ai didi

c - 在 C 中通过梯形规则积分

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:15 25 4
gpt4 key购买 nike

我正在尝试使用梯形法则在 0 和无穷大之间对函数 1/((1+x^2)x^0.5) 求积分。

我需要找到使用双 float 时可能提供最高精度的 N 值,我通过运行程序并增加 N 值来完成,直到 N 的连续值给出的总数之间没有差异. 但是我陷入了无限循环。

谢谢

贝丝

#include<stdio.h>
#include<math.h>
#include<float.h>

double inter(double x, double h, double y, double N, double total)
{
h=(y-x)/(N-1);
total= total +0.5*(1/((1+pow(x,2))*sqrt(x)));
x=x+h;

while (x<y)
{
total=total+(1/((1+pow(x,2))*sqrt(x)));
x=x+h;
//printf("t - %lf \n", total);
//printf("x - %lf \n", x);
}
total= total +0.5*(1/((1+pow(x,2))*sqrt(x)));
total=total*h;
return total;
}

main()
{
double x,y,total,h,c,d,f,N, finish;
x=DBL_EPSILON;
y=331;
total=0;
N=0.5;
c=inter(x,h,y,N,total);
d=0;
finish=0;

while(finish==0)
{
d=inter(x,h,y,N,total);
if(d==c)
{
finish=1;
}
else
{
c=d;
d=0;
h++;
printf("%lf/n", h);
}
}

printf("%lf\n", d);
}

最佳答案

在您的 iter() 函数中,h 为负数,这导致 x 变为负数。负数的 sqrt() 返回 NaN。此外,由于 h 为负,x 继续变小,因此 总是 小于 y,这是无限循环的原因。

h 是负数,因为分母(N-1)出来是-0.5(N 传入为0.5)。

关于c - 在 C 中通过梯形规则积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098553/

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