具体原理请参考《费恩曼物理学讲义》第1卷,新千年版,223~226.
代码如下
#include <iostream> #include<vector> #include<math.h> #include<iomanip> using namespace std; double getSquare(double N) { double a; double _a=N/3;//迭代过程中的新值 for(;a!=_a;) { a=_a; _a=(a+N/a)/2; } return a; } double getSeveralSquare(double N,int n) { float temp; for(int i=0;i<n;i++) { temp=N; N=getSquare(temp); } return N; } double lg10(double a) { int num=31;//开方根次数 double *squareArray=new double[num]; int *s_num=new int[num]; int i; double delta=0.254; s_num[0]=pow(2,num-1); double sum=0; for(i=0;i<num;i++) { squareArray[i]=getSeveralSquare(10,i); //cout<<setprecision(8)<< squareArray[i]<<endl; if(i<num-1) s_num[i+1]=s_num[i]/2; } for(i=1;i<num;i++) { if(squareArray[i]<a&&a<squareArray[i-1]) { a/=squareArray[i]; sum+=s_num[i]; } } sum =(sum+delta)/s_num[0]; delete [] squareArray; delete [] s_num; return sum; } int main() { double a,N=10; cout<<setprecision(8); cout<<"log10(3)="<<lg10(3)<<endl; return 0; }
运行结果如下: