1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
| #include<stdio.h> #include<math.h>
double Function(double x) { return (x-0.5)*(x-0.5); }
double Derivative(double x) { double eps=0.0000001; double dx=0.5; double dy=Function(x+dx)-Function(x); double dd1=dy/dx; double dd2=0; dx=dx/2; dy=Function(x)-Function(x+dx); dd2=dy/dx; while(abs(dd1-dd2)>eps) { dd1=dd2; dx=dx/2.0; dy=Function(x+dx)-Function(x); dd2=dy/dx; } return dd2; }
double Derivative2(double x) { double eps=0.00000001; double dx=0.5; double dy=Derivative(x+dx)-Derivative(x); double dd1=dy/dx; double dd2=0; dx=dx/2; dy=Derivative(x)-Derivative(x+dx); dd2=dy/dx; while(abs(dd1-dd2)>eps) { dd1=dd2; dx=dx/2.0; dy=Derivative(x+dx)-Derivative(x); dd2=dy/dx; } return dd2; }
void GoldenSection(double a,double b,int n) { double l=a+0.382*(b-a); double h=a+0.618*(b-a); double region=b-a; double fl; double fh; int num=1; while(region>0.0000000001&&num<n) { fl=Function(l); fh=Function(h); if(fl>fh) { a=l; l=h; h=a+0.618*(b-a); } else { b=h; h=l; l=a+0.382*(b-a); } num++; region=abs(b-a); } if(num==n) printf("找不到最小值"); else { printf("黄金分割法:x=%f时,最小值f(x)=%f",(a+b)/2,Function((a+b)/2)); } }
void Dichotomy(double a,double b) { double eps=0.0000001; double x=(a+b)/2; double region=b-a; double fxDerivative= Derivative(x); while(region>0.0000001&&abs(fxDerivative)>eps) { fxDerivative= Derivative(x); if(fxDerivative>eps) b=x; if(fxDerivative<-eps) a=x; x=(a+b)/2; region=abs(b-a); } printf("\n\n二分法:x=%f时,f(x)=%f\n",x,Function(x)); }
void Newton(double a,double b,double x1) { double eps=0.0000001; double x=x1; double d1=Derivative(x1); double d2; while(abs(d1)>eps) { d2=Derivative2(x); if(d2<0) printf("二阶导小于0,无法求解"); else { x=x-d1/d2; d1=Derivative(x); } } printf("\n牛顿法:x=%f时,f(x)=%f\n\n",x,Function(x)); } void main() { GoldenSection(0,1,100000); Dichotomy(0,1); Newton(0,1,1); }
|