如何使用python找到该系列的值?

2024-04-24 10:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很新,太棒了!但我很难找到这个系列的结果:

 1-x+(x^2)/2!-(x^3)/3!+(x^4)/4!-..............up to n terms

我写的是:

  import math
  a=input("ENter the no")
  x=input("ENter value of x")
  i=1
  s=0
  s1=0
  s2=1
  p=1
  while(i<=a):
          if(i%2!=0):
                    s=s-math.pow(x,i)/p*i
          else:
                     s1=s1+math.pow(x,i)/p*i
          i=i+1
  else:
              s2=s2+s1+s
              print s2

请让我知道正确的程序和错误:)!!提前谢谢。 不直接使用阶乘函数就告诉我?你知道吗


Tags: ofthetonoimportinputvaluemath
2条回答

这是exp(-x)的泰勒级数展开式。认识到这一点,您就有机会对照math.exp(-x)检查您的结果。你知道吗

简单的语法改进

一段时间后你不需要一个“else”。只需在while循环之前的缩进级别添加要在循环之后运行的代码。你知道吗

数学问题

最重要的是,阶乘的计算永远不会完成。写p*i不会在p中存储p和i的乘积。你需要这样做。你知道吗

然后,运算符优先级出现问题。当您编写pow(...)/p*i时,Python理解( pow(...) / p ) * i,这不是您的意思。你知道吗

最后,序列中的大多数项都会被抵消,但是您会在一边添加所有的正项,在另一边添加所有的负项。这意味着您将增长两个非常大的值(如果使用整数,则会导致风险溢出),然后取它们之间的差值来得到结果。因为计算机上的双精度是有限的,这是一个错误的做法精度明智。最好使你的和中的所有项保持相同的数量级。你知道吗

提高了正确性

import math
a=input("Enter the no")
x=input("Enter value of x")
s=1
p=1
for i in range(1,a):
    p=p*i
    if(i%2!=0):
        s=s-math.pow(x,i)/p
    else:
         s=s+math.pow(x,i)/p
print s
print math.exp(-x)

请注意,使用for循环和较少的中间求和使其更易于阅读。你知道吗

移除分支

pow(-x,i)如果i不均匀则为负,否则为正。因此-pow(x,i) if i%2 != 0 else pow(x,i)可以被重写pow(-x,i)。移除内部循环中的if是(几乎?)总是一件好事,为了表现。所以简化的版本是:

import math
a=input("Enter the no")
x=input("Enter value of x")
s=1
p=1
for i in range(1,a):
    p=p*i
    s=s+math.pow(-x,i)/p
print s
print math.exp(-x)

这样做还有一个好处,就是使代码更短(从而更可读)。你知道吗

import math    #imported to use the factorial function
def exp(x,n):
    ans = 1    #initializing it with 1 because the first term is a constant:1
    for i in xrange(1,n+1):   #starts looping from 1 to n terms 
        ans+=(-1**i*(float(x)**i)/math.factorial(i)) #changing the sign of 1, adding.
        # -1**i equals to 1 if i is even and -1 if i is odd
        # ** operator stands for the pow() function , (2**3 =8)
        # float(x) returns a floating value if value of x entered is integer
        # You can remove this is you are already entering floating values.
        # math.factorial() returns factorial of a given argument, 
    return ans

如果你不想使用数学.阶乘()然后您可以尝试:

def exp(x,n):
    ans = 1
    dummy_factorial = 1
    for i in xrange(1,n+1):
        dummy_factorial*=i
        print dummy_factorial
        ans+=(-1**i*(float(x)**i)/(dummy_factorial))
    return ans

相关问题 更多 >