4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで総和を実装

Last updated at Posted at 2015-10-08

総和の式を実装してみる

\sum_{i=m}^{n} f(x) = f(m) + f(m+1) + \cdots + f(n) \\
sigma.py
def sigma(m, n, func, s = 0) :
    if m > n: return s
    return sigma(m + 1, n, func, s + func(m))

#使用例

sigma_test.py
print(sigma(1, 10, lambda x : x))
55

print(sigma(1, 3, lambda x : 3 * 5 ** (x - 1)))
93

Webで適当な問題見つけて入力したけどちゃんと動いてそう。
もっと効率のいい書き方とか、もっとオサレな書き方とか、もうそれ用意されてるしとかもあるのかも。
##追記
NumPyという数学関数ライブラリがあるので大抵の式は揃っていそう。。。

Pythonの数値計算ライブラリ NumPy入門
http://rest-term.com/archives/2999/

4
3
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?