龙贝格法

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//P70

#include "stdafx.h"
#include "math.h"
#include <iostream>
using namespace std;

int main()
{
    #define f(x) (sin(x)/x)
double a, b, e,h,T1,T2,S,x,S1,S2,C1,C2,R1,R2;
cout << "请输入a,b,e:" << endl;
cin >> a >> b >> e;
h = b - a;
T1 = h / 2 * (f(a)+f(b));
int k = 1;
do
{
S = 0;
x = a + h / 2;
do
{
S += f(x);
   x += h;
} while (x < b);
T2 = T1 / 2 + h / 2 * S;
S2 = T2 + 1 / 3 * (T2 - T1);
if (k = 1);
C2 = S2 + 1 / 15*(S2 - S1);
if (k = 2);
R2 = C2 + 1 / 63*(C2 - C1);
if (k = 3);
} while (fabs(R2-R1)>=e);
cout << R2;
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用龙贝格计算定积分的 C 代码,其中用户需要输入积分上限、下限和被积函数: ```c #include <stdio.h> #include <math.h> #define MAX_ITER 20 // 最大迭代次数 #define EPS 1e-6 // 目标精度 double f(double x) { // 定义被积函数,这里选择 sin(x) return sin(x); } double romberg(double a, double b) { double R[MAX_ITER][MAX_ITER] = {0}; double h = b - a; R[0][0] = h / 2 * (f(a) + f(b)); for (int i = 1; i < MAX_ITER; i++) { h /= 2; double sum = 0; for (int j = 1; j <= pow(2, i - 1); j++) { sum += f(a + (2 * j - 1) * h); } R[i][0] = 0.5 * R[i - 1][0] + sum * h; for (int k = 1; k <= i; k++) { R[i][k] = (pow(4, k) * R[i][k - 1] - R[i - 1][k - 1]) / (pow(4, k) - 1); } if (i >= 2 && fabs(R[i][i] - R[i - 1][i - 1]) < EPS) { return R[i][i]; } } return R[MAX_ITER - 1][MAX_ITER - 1]; } int main() { double a, b; printf("Enter the lower limit: "); scanf("%lf", &a); printf("Enter the upper limit: "); scanf("%lf", &b); double res = romberg(a, b); printf("The integral of sin(x) from %.6f to %.6f is: %.6f\n", a, b, res); return 0; } ``` 该代码使用了龙贝格(Romberg Integration)来计算定积分的近似值。其中 `f` 函数定义了被积函数,`romberg` 函数使用一个二维数组来记录每次迭代的数值积分近似值,并根据龙贝格公式逐步提高精度。在 `main` 函数中,我们要求用户输入积分上下限,然后计算定积分的近似值并输出结果。 以下是使用差商计算函数导数的 C 代码,其中用户需要输入函数值的数组 `y` 和相应的 x 坐标值: ```c #include <stdio.h> #define MAX_N 100 // 最大数组长度 double diff_quotient(double x[], double y[], int n, double x0) { double res = 0; for (int i = 0; i < n; i++) { double term = y[i]; for (int j = 0; j < n; j++) { if (i != j) { term *= (x0 - x[j]) / (x[i] - x[j]); } } res += term; } return res; } int main() { double x[MAX_N], y[MAX_N]; int n; printf("Enter the number of data points: "); scanf("%d", &n); printf("Enter the data points:\n"); for (int i = 0; i < n; i++) { scanf("%lf%lf", &x[i], &y[i]); } double x0; printf("Enter the x coordinate at which to evaluate the derivative: "); scanf("%lf", &x0); double res = diff_quotient(x, y, n, x0); printf("The derivative at x = %.6f is: %.6f\n", x0, res); return 0; } ``` 该代码使用了差商(Finite Difference Method)来计算函数在一个特定点的导数值。其中 `diff_quotient` 函数计算差商,并返回函数在 `x0` 处的导数值。在 `main` 函数中,我们要求用户输入函数值的数组 `y` 和相应的 x 坐标值 `x`,然后计算函数在指定点 `x0` 处的导数值并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值