问题描述
我需要计算Python中序列的总和 但是我不能使用内置函数求幂。
这意味着我不能使用**
和pow()
。我必须为此创建自己的功能。
因此,我创建了用于求幂的函数,但它仅适用于数字。我需要将公式计算到第n个。
我的求幂函数:
def exponentiation(a,b):
result = 1
for index in range(b):
result = result * a
return result
对于数字,它可以工作。但是当我想执行第n次(我将“ n”定义为符号)时,我得到:
'Symbol' object cannot be interpreted as an integer
所以我不知道该如何解决。
如果我想计算序列的总和,我会使用它并且可以起作用:
sy.summation((-1/2)**n,(n,1,oo))
但是正如我之前所说,我需要将**
更改为自己的幂函数,但这仍然表明'Symbol'对象无法解释为整数。
sy.summation(exponentiation((-1/2),n),oo))
您有什么建议吗?
解决方法
您不能将'n'提升为幂。我很确定您是否被禁止使用**
和pow()
来使用SymPy也不会飞行。
要计算的结果,您可以简单地假设一个“大” n,然后检查是否仍然可以检测到较早的结果与下一个结果之间的任何差异-您将不会很快看到更多变化浮动数学限制(Is floating point math broken?):
def exponentiation(a,b): result = 1 for index in range(b): result = result * a return result
s = 0
a = -1/2
for n in range(1,10000000):
old_s = s
s += exponentiation(a,n)
# do not compare floats with small differences with ==
# see link below for better ways to do that
if s == old_s:
print("\nThe sum no longer changes due to floating math limitations.")
print(f"Result before: {old_s} and after {s} for n={n}")
break
else:
print(f"nResult before: {old_s} and after {s} for n={n}")
输出:
Result before: 0 and after -0.5 for n=1
Result before: -0.5 and after -0.25 for n=2
Result before: -0.25 and after -0.375 for n=3
[...snipp...]
Result before: -0.33333333333333326 and after -0.33333333333333337 for n=53
Result before: -0.33333333333333337 and after -0.3333333333333333 for n=54
Result before: -0.3333333333333333 and after -0.33333333333333337 for n=55
The sum no longer changes due to floating math limitations.
Result before: -0.33333333333333337 and after -0.33333333333333337 for n=56
有关浮点比较的更多信息,请参见What is the best way to compare floats for almost-equality in Python?。
,“ nth”表示任何给定的数字。因此,您不需要(而且我不认为您会如何)对任何符号取幂。我认为,如果您返回一个列表而不只是第n个值,则可以稍微简化一下事情:
https://maven.jzy3d.org/releases
然后使用for循环处理列表以获取总和
如果您需要使用sympy,请检查以下答案:Summation over a sympy Array
,我会说,用Python代码替换**
的唯一有意义的解决方案是这样的:
def exponentiation(a,b):
if isinstance(a,Symbol):
return a.__pow__(b)
if isinstance(b,Symbol):
return b.__pow__(a)
result = 1
for index in range(b):
result = result * a
return result
如果您想重新实现SymPys的 pow 功能-对于Stackoverflow-answer;)肯定太困难了。
但是您可以在这里找到SymPys源代码: https://github.com/sympy/sympy/blob/master/sympy/core/power.py