大家谈一谈如何编写sqrt()函数!
double sqrt(double x)
{
....
....
....
}
另外大家在谈一谈如何求一个数的对数!
(不许调用库函数)
double log10(double x) (其中x>0)
{
...
...
...
}
只需要说说你的思想就可以呢!
如果能够给出算法或示例代码更好!
这个是高数中的内容 , 需要知道泰勒级数的相关概念
f(x) = f0(m)(x - m)^0 / 0! + f1(m)(x - m)^1 / 1! + f2(m)(x - m)^2 / 2! + … +fn(m)(x - m)^n / n! + …
其中, fn(m) 用来代表f(X)在m 处的n阶导数,
(x - m)^ n 表示(x - m)的n次方,
n !表示n的阶乘
m是任意实数,不妨取0(只要f(x)在0处n阶可导
那么式子就可以变成:
f(x) = f(0) + f1(0)x ^1 / 1! + f2(0)x^2 / 2! + … +fn(0)x^n / n! + …
举例:
sin(x)= sin(0) + sin1(0) x^1 / 1! +sin2(0) x^2 / 2! + ......+ sinn(0) x^n / n!+.......
由于:sin(0) = sin2(0) =sin4(0) = sin6(0) = sin8(0) = ....... = sin2n(0) =0
sin1(0) = sin5(0) = sin8(0) = ......=sin4n+1(0) = 1
sin3(0) = sin7(0) =sin11(0) = ...... = sin4n+3(0) = -1
其中n=1,2,3,...........
所以,带入公式的到:
sin(x) = 0 + x + 0 - x^3/3! + 0 + x^5 / 5! +0 - x^7 / 7! + 0 + x^9 /9! + ......
化简得:
sin(x) = x - x^3/3! + x^5 / 5! - x^7 / 7!+ x^9 /9! + ........ + (-1)^n x^(2n+1) / (2n+1)!+........ ,其中n=0,1,2,3......
上面应该是比较正宗的做法
但是我们说:算法
算法就是解决问题的方法.只要能解决问题 ,不管复杂度!
下面是我的另一个想法:
#define MAXSQRT (double)1000000000
double sprt(double x)
{
double min = 0;
double max = MAXSQRT ;
double average = (min + max)/2.0;
if(x<0) return -1; //错误,x不能小于0
while(((average*average) - x) != 0.0 )
{
if(((average*average) - x) > 0.0 )
max = average;
else
min = average;
average = (min + max)/2;
}
return average;
}
加上测试程序:
#include "iostream.h" #define MAXSQRT (double)1000000000
double sprt(double x)
{
double min = 0;
double max = MAXSQRT ;
double average = (min + max)/2.0;
if(x<0) return -1; //错误,x不能小于0
while(((average*average) - x) != 0.0 )
{
if(((average*average) - x) > 0.0 )
max = average;
else
min = average; average = (min + max)/2;
}
return average;
}
void main() { double s; s = sprt((double)100); cout<<s<<endl; }