0

## X-(X^2/2)+(X^3/3)-(X^4/4)........+(X^n/n)

Ryan 2021-03-06 00:34:501605 瀏覽

### 3 個回答

2
lawrencelin2011
iT邦新手 5 級 ‧ 2021-03-06 08:21:16

double Ans(double x, int n)
{
int i;

``````if (n<=0) return x;
if (n==1) return 0.0;

for ( i=2; i<=n; i++)
{
if ((i%2)==0)  x = x - (pow(x,i)/i);
else                     x = x + (pow (x,i)/i);
}
return x;
``````

}

0
shewer
iT邦新手 5 級 ‧ 2021-03-07 23:49:25
``````#include <stdio.h>
#include <math.h>
// i=1 , 3 ,5,7..... 1
// i=2 , 4 ,6 ..... -1
//  i&1 => 1 or 0 => true(odd) or false(even)
double ans(double res,int x,int i){
if (0 >= i) return res;
res += pow(x,i)/ ( i&1  ? i: -i  ) ;
return ans( res , x, i-1);
}

// X-(X^2/2)+(X^3/3)-(X^4/4)........+(X^n/n)
// -(-X^1/1)+ -(-X^2/2) + -(-X^3/3) ......+ -(-X^n/n)
double ans1(const double res,const int x,const int i){
return (0>=i) ? res : ans1(res - pow(-x,i)/i,x,i-1);
}
#define Ans1(x,i) ans1(0,(x),(i))
int main(int argc , char* argv[]) {
printf("%f\n", ans(0,2,5) );
printf("%f\n", ans1(0,2,5) );
printf("%f\n", Ans1(2,5));
}

``````

gcc -lm -O2 // -O2 optimize tail recursion

0

iT邦研究生 2 級 ‧ 2021-04-03 13:29:38

``````//利用「餘式定理」及「綜合除法」求多項式值
double f(double x, int n) {
double result=((n&1)?1:-1)/n;
while(--n>=0) {
result=result*x+((n&1)?1:-1)/n;
}
return result;
}
``````