定积分求近似数:
计算定积分原理比较简单,即微元法,将积分区间(a,b)划分成长度为d的n等份,即将面积划分成一个一个的小梯形,计算每一个小梯形的面积,近似为长方形面积(底:d,高:f(x)),然后相加
牛顿迭代法求根的近似数
x=x-f(x)/f'(x),dx=f(x)/f'(x),当dx趋近于0时,x趋近于根
二分法求根的近似数
原理是零点定理,存在x∈(a,b)使得f(a)*f(b)<0,然后一直缩小(a,b)的范围,直到b-a趋近于0
弦截法求根的近似数
使(x1,x2)一直缩小范围,直至f(x2)逼近0
#include<stdio.h>
#include<math.h>
#define EPSILON 0.00001//定义迭代精度
//定义被积函数,以x^3-2为例,多项式函数及其导数
double f(double x) {
return pow(x,3)-2;
}
double df(double x) {
return 3 * pow(x, 2);
}
//使用梯形法则进行数值积分
double intergrate(double a, double b, int n) {
double d = (b - a) / n;
double sum = 0;
for (int i = 0; i < n; i++) {
double x = a + i * d;
sum =sum+ f(x)*d;
}
return sum;
}
//使用牛顿迭代法求解多项式函数的根
//x=x-f(x)/f'(x)
double newton(double x) {
double dx;
do {
dx = f(x) / df(x);
x -= dx;
} while (fabs(dx) > EPSILON);
return x;
}
//使用二分法,存在x∈(a,b)使得f(a)*f(b)<0
double doublesection(double left, double right) {
while (fabs(left - right) > EPSILON) {
double mid = (left + right) / 2;
if (f(mid) == 0)
return mid;
else if (f(mid) * f(left) < 0)
right = mid;
else
left = mid;
}
return (left + right) / 2;
}
//使用弦截法求根
//x=[x1*f(x2)-x2*f(x1)]/f(x2)-f(x1)
//x1 x2 x
//1 2 1.5
//2 1.5
double xuanjie(double x1, double x2) {
double x;
do {
x = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
x1 = x2;
x2 = x;
} while (fabs(f(x)) > EPSILON);
return x;
}
int main() {
//定积分求近似值
double a = 1.0;
double b = 2.0;
int n = 10000;
double ret = intergrate(a, b, n);
printf("函数从%.0f到%.0f的定积分近似值为:%f\n", a, b, ret);
//牛顿迭代法求一元多次方程的根
double init_x = 1.0;//假设x的值为1
double root1 = newton(init_x);
printf("newton求方程根的近似值为:%f\n", root1);
//二分法求根
double init_left = 0.0;
double init_right = 2.0;
double root2 = doublesection(init_left, init_right);
printf("二分法求方程根的近似值为:%f\n", root2);
//弦截法求根
double init_x1 = 0.0;
double init_x2 = 1.0;
double root3 = xuanjie(init_x1, init_x2);
printf("弦截法求方程根的近似值为:%f\n", root3);
return 0;
}
编译运行结果为: