C++求ln(x),源代码,不使用math.h

已知double ln2(double x),可用于0<x<=2时的情况,求double ln(double x)对于x>0时的结果
只允许使用+,-,*,/,-pi/2~pi/2的三角函数,指数为正整数的乘方,开平方

下面用 2个 级数 之一 计算 (根据自变量范围)。
如果你想对比 数学库 的结果,你可以 包含 math.h 并输出 log(x)
对于特殊点的判断条件,你可以自己增减,我没有仔细考虑。
==========================================
#include <stdio.h>
// #include <math.h>

double log_n(double x){
double y,term,r;
double eps= 1e-10;
int i;
if ( x <= 0.0) { printf("x must > 0\n"); exit(0);};
if ( x<eps && x > -eps) return 0;
y= (x-1)/x;
term = y; r=y;
for (i=2;i<1000;i++){
term= term*y/i*(i-1);
//printf("term=%lf\n",term);
if (term > -eps && term < eps)break;
r=r+term;
};
return r;
}
double sigma(double y){
double x;
double term, n1= -1,r=0,t,eps=1e-10;
int i;
if ( y<eps && y > -eps){ printf("x must > 0\n"); exit(0);};
if (y > -1 && y <=1){
x = y-1;
term=x;
r=x;
for (i=2;i<1000;i++){
term=term*x*n1;
t = term/i;
if (t < eps && t > -eps) break;
r=r+t;
};
return r;
}else {
r=log_n(y);
return r;
};
}

main(){
double x,y;
printf("input x\n");
scanf("%lf",&x);
// printf("%lf %lf\n",sigma(x),log(x));
printf("%lf\n",sigma(x));
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2015-06-19
你们学了ln(x)展开成多项式了吗
相似回答