iT邦幫忙

0

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

c
Ryan 2021-03-06 00:34:502099 瀏覽

各位大大好
有人知道怎麼用C語言計算這個多項式嗎? (ಥ_ಥ)

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
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

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
淺水員
iT邦大師 6 級 ‧ 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;
}

我要發表回答

立即登入回答