为什么C++没有根据 pow (-1,i) 更改我的代码编号条件?

Why is C++ not changing my code's numbers' condition according to pow (-1,i)?

本文关键字:我的 代码 编号 条件 有根据 C++ pow 为什么      更新时间:2024-09-27

我这里有C++代码:

#include <iostream>
#include <cmath>
#include <time.h>
using namespace std;

int main()
{

double n,x;
cin>>n>>x;
double b=1,c=0.0;
for (int i=1;i<=n;i++){
x=pow(x,i);
x=x*pow((-1),(i+1));
cout<<x<<endl;
b=i;
c=c+x/b;

}
cout<<c<<endl;

return 0;
}

我创建这个是为了计算x^1-x^2/2+x^3/3-.....+(-1)^(n-1)*(x^n)/n。用户输入n。问题出现在这一行:x=x*pow((-1),(i+1));

我正在创建它来计算x^1 - x^2/2 + x^3/3 - ... + (-1)^(n-1)*(x^n)/n

这似乎是ln(1 + x)的Maclaurin系列,但不是发布的代码所评估的:

for (int i=1;i<=n;i++)
{
x = pow(x,i);
//      ^     This is updated at each iteration! It should be const.  
x = x * pow((-1),(i+1));
//      ^^^^^^^^^^^^^^^  Please don't (see later).
b=i;
c=c+x/b;
//    ^  Okish, but why not use i directly?
}

至少,应该引入一个不同于x的变量来存储幂的结果。

使用pow((-1),(i+1))生成简单序列{1,-1,1,-1…}如果不容易出现舍入误差,也是值得怀疑的。我将展示完成同一任务的两种不同方法。

// Evaluates the Mclaurin series of ln(1 + x) using n terms.
// Noting that (e.g. with n == 4):
// p(4) = x -x^2 / 2 + x^3 / 3 - x^4 / 4
// p(4) = x - x*x/2 + x*x*x/3 - x*x*x*x/4
// p(4) = k(1) -x*k(1)/2 + x*x*x/3 - x*x*x*x/4      k(1) = x 
// p(4) = k(1) -x*k(1)/2 -x*k(2)/3 - x*x*x*x/4      k(2) = -x*k(1)
// p(4) = k(1) -x*k(1)/2 -x*k(2)/3 -x*k(3)/4        k(3) = -x*k(2)

// Preconditions: n >= 1  and  -1 < x <= 1
double fn(int n, double x)
{
double k{ x };
double sum{ x };
for (int i{ 2 }; i <= n; ++i)
{
k *= -x;
sum += k / i;
}
return sum;
}

注意,在收敛区间内,abs(k / i)趋于零,而在收敛区间外则增长。最终,由于像double这样的浮点类型的精度有限,sum += k/i不会更改sum的值。

另一种方法可能基于霍纳规则。

// Evaluates the Mclaurin series of ln(1 + x) using n terms.
// Applying Horner's rule:
// p(4) = x -x^2 / 2 + x^3 / 3 - x^4 / 4
//      = x*(1 + x*(-1/2 + x*(1/3 + x*(-1/4))))
//      = x*(1 + x*(-1/2 + x*( 1/3 + x*k(4) )))   k(4) = 1/4
//      = x*(1 + x*( -1/2 + x*k(3) ))             k(3) = 1/3 + x*k(4) 
//      = x*( 1 + x*k(2) )                        k(2) = -1/2 + x*k(3)
//      = x * k(1)                                k(1) = 1 + x*k(2)  
// Preconditions: n >= 1 and -1 < x <= 1
double fn(int n, double x)
{
double sign{ n % 2 == 0? -1.0 : 1.0 };
double k{ sign / n };
while ( --n > 0 )
{
sign = -sign;
k = sign / n + x * k;
}
return k * x;
}
相关文章: