为什么C++没有根据 pow (-1,i) 更改我的代码编号条件?
Why is C++ not changing my code's numbers' condition according to pow (-1,i)?
我这里有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;
}
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么我的代码在输出中增加了93天
- 0-1背包代码中的错误.我的代码中有什么错误
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 我的代码运行良好,但在游戏循环中中断
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 我的代码中的意外价值以及我如何修复它
- 为什么 rand 不在我的代码中生成随机数?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- 无法找出我的代码中的内存泄漏
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- 我正在尝试创建一个菜单,但我的代码一直在循环