Writing sums as functions: INTERACTIVE
Contents
Writing sums as functions: INTERACTIVE#
We want to calculate the following general sum:
\[\sum_{k = 1}^{100} f(k) \]
where \(f\) is some function.
For the specific case \(f(k) = \frac{1}{k^2}\) we would be computing
\[\sum_{k = 1}^{100} \frac{1}{k^2} \]
and we could use the following code:
def my_sum(start, stop):
"""Sum the function 1/k^2 for integers between start and stop (inclusive)"""
total = 0
for k in range(start, stop + 1):
total = total + (1 / k**2)
return total
print(my_sum(1,100))
1.6349839001848923
But we could make this more general by allowing this to work on any function.
Let’s change this to accept an additional argument my_func
def my_sum(start, stop, my_func):
"""Sum the function 1/k^2 for integers between start and stop (inclusive)"""
total = 0
for k in range(start, stop + 1):
total = total + my_func(k)
return total
Now to call this we have to provide a start, a stop, and the form of \(f(k)\), my function. Of course, we are yet to define ```my_func``. So for \(f(k) = \frac{1}{k^2}\) we would do:
def my_func(k):
"""Return 1/k**2"""
return 1/k**2
print(my_sum(1, 100, my_func))
1.6349839001848923
Putting this together: exercise#
Using the above compute:
\[ \sum_{k=1}^{1000} \frac{1}{k^2}.\]
Exercise#
Compute
\[ \sum_{k=5}^{75} k^3 - 7k^2 + k.\]