入力方程式と入力変数を使用して合計を取る sigsum() 関数を作成しています。これが私がこれまでに持っているものです:
def sigsum(eqn, index, lower=0, upper=None, step=1):
if type(step) is not int:
raise TypeError('step must be an integer')
elif step < 1:
raise ValueError('step must be greater than or equal to 1')
if upper is None:
upper = 1280000
if lower is None:
lower = -1280000
if (upper - lower) % step:
upper -= (upper - lower) % step
index = lower
total = 0
while True:
total += eqn
if index == upper:
break
index += step
return total
関数の使用法:
print(sigsum('1/(i+5)','i'))
>>> 12.5563
私の現在の問題は、「eqn」と「index」を関数のローカル名前空間内に存在する変数に変換することです。exec を使用するのは得策ではなく、おそらく setattr() が機能する可能性があると聞いたことがあります。誰でも私を助けることができますか?ありがとう。