Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2509525
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-08-11 10:55:21

用牛顿迭代法求根。方程为

AX3 + BX2 + CX + D = 0,系数a,b,c,d的值依次为1,2,3,4由主函数输入。求X在1附近的一个实根。求出根后由主函数输出。

牛顿迭代法:是用于求方程或方程组近似根的一种常用的算法设计方法。设方程为f(x)=0,用某种数学方法导出等价的形式 x(n+1) = g(x(n)) =  x(n)–f(x(n))/f‘(x(n)).然后按以下步骤执行:
(1) 选一个方程的近似根,赋给变量x1;
(2) 将x0的值保存于变量x1,然后计算g(x1),并将结果存于变量x0;
(3) 当x0与x1的差的绝对值还小于指定的精度要求时,重复步骤(2)的计算。
若方程有根,并且用上述方法计算出来的近似根序列收敛,则按上述方法求得的x0就认为是方程的根。

根据上面的原理,编写代码如下:

 

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

double F1(int,int,int,int,double); //源函数

double F2(int,int,int,int,double); //求解的函数的一阶导数函数

double Newton(int,int,int,int,double, double);
int main(int argc, char *argv[])
{
    int a,b,c,d;
    double x0,x1 = 1;
    double e = pow(10,-5);
    printf("question : a * x * x * x + b * x * x + c * x + d = 0 \n");
    printf("please input a,b,c,d\n");
    scanf("%d,%d,%d,%d",&a,&b,&c,&d);
    x0 = Newton(a,b,c,d,x1,e);
    printf("the result is x = %f",x0);
    system("pause");
    return 0;
}

double F1(int a, int b, int c, int d, double x)
{
       return a * x * x * x + b * x * x + c * x + d;
}

double F2(int a, int b, int c, int d, double x)
{
       return 3 * a * x * x + 2 * b * x + c;
}

double Newton(int a, int b, int c, int d,double x, double e)
{
       double x1;
       do
       {
         x1 = x;
         x = x1 - F1(a,b,c,d,x1) / F2(a,b,c,d,x1);
       }while (fabs(x1 - x) > e);
       return x;
}


阅读(8876) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~