我尝试在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)
答案 0 :(得分:1)
将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中给出的函数:{{ 1}}。这是我的代码:
((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))