使用spyder中具有指定公差的连续项之间的关系来扩展泰勒级数
我已使用此代码来确定间谍程序(Python 3.8)中指定容差的 e^pi 值。
from math import*
term=1
sum=0
n=1
while (abs(e**pi-term))>0.0001:
term=term*pi/n
sum+=term
n+=1
print(sum,e**pi)
我多次运行这段代码。但当我运行此代码时,spyder 没有显示任何内容。我是Python新手。所以现在我无法知道这段代码是否正确。如果您可以验证此代码是否有效,那将会很有帮助。
I have used this code to determine the value of e^pi with a specified tolerance in spyder(Python 3.8).
from math import*
term=1
sum=0
n=1
while (abs(e**pi-term))>0.0001:
term=term*pi/n
sum+=term
n+=1
print(sum,e**pi)
I ran this code several times. But spyder is not showing anything when I run this code. I am new to python. So now I have no way to know whether this code is correct or not. It would be beneficial if you could verify whether this code is valid or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,所以 e^x 的泰勒级数是 n=0 到 x^n / n 的 inf 之和!您似乎通过在每次迭代期间乘以 pi/n 来正确地执行此操作。
我注意到的一个问题是你的 while 循环条件。要检查函数的错误,您应该从实际值中减去当前的
sum
。这就是您进入无限循环的原因,因为您的term
将接近 0,因此差值将接近实际值 e^pi,它始终大于 0.0001 或无论您的错误是什么。另外,由于我们从 1 开始 n,所以我们也应该从 1 开始 sum,因为泰勒级数的第 0 项已经是 1。这就是进入无限循环的原因,因为
因此,我们的代码应该如下所示:
输出:
I希望这有助于回答您的问题!如果您需要任何进一步的说明或详细信息,请告诉我:)
Okay, so the taylor series for e^x is sum n=0 to inf of x^n / n! which you seem to be doing correctly by multiplying by pi/n during each iteration.
One problem I noticed was with your while loop condition. To check the error of the function, you should be subtracting your current
sum
from the actual value. This is why you enter the infinite loop, because yourterm
will approach 0, so the difference will approach the actual value, e^pi, which is always greater than .0001 or whatever your error is.Additionally, since we start n at 1, we should also start sum at 1 because the 0th term of the taylor series is already 1. This is why you enter the infinite loop, because
Therefore, our code should look like this:
Output:
I hope this helped answer your question! Please let me know if you need any further clarification or details :)
while 循环并未结束。
我陷入了一个跳出循环的条件(在 10,000 个循环时)来展示这一点:
如果用 for 循环替换 while 循环,那么您可以看到每次迭代,如下所示。
这是前 10 项的结果:
数字越来越大,因此
while
循环从未退出(并且您的笔记本电脑可能在此过程中变得非常热!)。The while loop does not end.
I have stuck in a condition to break out of the loop (at 10,000 cycles) to show this:
If you replace the while loop with a for loop, then you can see each iteration as follows.
And this is the result for the first 10 items:
The numbers are getting larger, hence the
while
loop was never exited (and your laptop probably got quite hot in the process !!).