Python 一系列的程序总和

Python program summation of a series

我试图在 python 中创建一个程序,它基本上总结了一个序列,直到小于 0 的项,如下所示: 1+((2X)/1!)+((3X^2)/2!)+((4X^3)/3!).... 我为系列中的每个术语设计了一个基本术语 ((A+1)((X)^A))/A!,其中 A 在术语循环中递增。下面的程序没有给出编译错误,但是没有显示结果。请帮忙。将不胜感激。谢谢!

import decimal
def fact(n):
    if n == 0:
        return 1
    else:
        return n*(fact(n-1))
x = int(input("Enter the value of x"))
A=0
summation=0
sumt1=(A+1)
sumt2=(x**A)
sumt3=fact(x)
sumt4=sumt1*sumt2
sumt5=sumt4/sumt3

while (sumt5 > 0.00) :
    summation = summation+sumt5
    A+=1
finalsum=decimal.Decimal(1+summation)
print("The value is")
print(finalsum)

将您的 sumt 变量移动到您的 while 循环中,然后在 sumt5 <= 0.00:

时跳出循环
import decimal

def fact(n):
    if n == 0:
        return 1
    else:
        return n*(fact(n-1))

x = 1  # Hardcoded for this example, instead of prompting.
A = 0
summation = 1.0

while True:
    sumt1 = A + 1
    sumt2 = x**A
    sumt3 = fact(A)  # Was `fact(x)` in original code, which didn't match your formula & prevented `sumt5 <= 0.00` from ever being true.
    sumt4 = sumt1 * sumt2
    sumt5 = sumt4/sumt3

    summation += sumt5
    A += 1

    if sumt5 <= 0.00:
        break


finalsum=decimal.Decimal(summation)
print("The value is {}.".format(finalsum))

更新答案

我想了解发生了什么对我自己更好,所以我将求和分解为一个单独的函数,而不是单独计算所有单独的项,我将它们直接插入到您在 OP 中提供的函数中: ((A+1)((X)^A))/A!。这是我的代码:

import decimal

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)


def summation(num):
    A = 0
    result = 1.0

    while True:
        term = (A + 1) * num**A / factorial(A)
        result += term
        A += 1

        if term <= 0.0:  # Break out of the loop when the `term <= 0`.
            break

    return result


# Sample output.    
for i in range(1, 11):
    final = decimal.Decimal(summation(i))
    print('summation({}) == {}'.format(i, final))

当我 运行 它时,我收到以下输出:

final == 6.43656365691809018159119659685529768466949462890625
final == 23.167168296791945891754949116148054599761962890625
final == 81.3421476927506574838844244368374347686767578125
final == 273.99075016572106733292457647621631622314453125
final == 891.478954615459542765165679156780242919921875
final == 2825.00155444914480540319345891475677490234375
final == 8774.06526742766800452955067157745361328125
final == 26829.62188337555198813788592815399169921875
final == 81031.839275753838592208921909332275390625
final == 242292.12374287386774085462093353271484375