- #include<stdio.h>
- #include<math.h>
- double resistance;
- double func(double x) //original function
- {
- return -5.775e-7*x*x+3.9083e-3*x+1-resistance/100.0;
- }
- double func1(double x) //derivative function
- {
- return -5.775e-7*2.0*x+3.9083e-3;
- }
- int Newton(double *x,double precision,int maxcyc)
- {
- double x1,x0;
- int k;
- x0=*x;
- for(k=0;k<maxcyc;k++)
- {
- if(func1(x0)==0.0)
- {
- printf("derivative =0! on iterative process.\n");
- return 0;
- }
- x1=x0-func(x0)/func1(x0);
- if(fabs(x1-x0)<precision || fabs(func(x1))<precision)
- {
- *x=x1;
- printf("root near the value.%lf\n",*x);
-
- return 1;
- }
- else
- {
- x0=x1;
- }
- }
- printf("iterative repetition overflow.\n");
- return 0;
- }
-
- int main(int argc, char** argv)
- {
- double x,precision;
- int maxcyc;
- printf("resistance of Pt100(85~200):");
- scanf("%lf",&resistance);
- printf("initial iterative value x0:");
- scanf("%lf",&x);
- printf("max iterative repetition:");
- scanf("%d",&maxcyc);
- printf("iterative precision:");
- scanf("%lf",&precision);
- if(Newton(&x,precision,maxcyc)==1)
- {
- }
- else
- {
- printf("iteration failed!\n");
- }
- return 0;
- }
复制代码
我给你写了个牛顿迭代代码,不要害怕这么长的代码,主要目的还是展示牛顿迭代的原理和所需要的参数,核心代码就这么几行,其他的都可以在移植到单片机的时候删掉。
- for(k=0;k<maxcyc;k++)
- {
- x1=x0-func(x0)/func1(x0);
- if(fabs(x1-x0)<precision || fabs(func(x1))<precision)
- {
- *x=x1;
- return 1;
- }
- else x0=x1;
- }
复制代码
至于如何从AD读数来推导出电阻值,我算了下,确实是初中数学问题,就不贴了。 |