Reputation: 25
Consider the function f(x,y) that equals two sigma (ΣΣ) where i ranges from 1 to 10 and (first sigma) and j ranges from 1 to 10 (second sigma) of the quantity {ix^2 + jy^3)
I believe the first sigma would be an inner loop and the second sigma an outer loop, but I am having trouble rewriting this into Python.
How can I convert this into Python?
Upvotes: 1
Views: 706
Reputation: 350310
The mathematical formula can be rewritten without summation, leading to this simple function:
def f(x, y):
return 550 * (x * x + y * y * y)
Here is how it is derived:
∑𝑖=1..10∑𝑗=1..10𝑖𝑥² + 𝑗𝑦³
= 10∑𝑖=1..10𝑖𝑥² + 10∑𝑗=1..10𝑗𝑦³
= 10𝑥²∑𝑖=1..10𝑖 + 10𝑦³∑𝑗=1..10𝑗
Using triangular number formula:
= 10𝑥²(10⋅11)/2 + 10𝑦³(10⋅11)/2
= 550(𝑥² + 𝑦³)
Upvotes: 1
Reputation: 9866
The first answer's approaches all work. Often the "pythonic" approach is to define a list comprehension before using sum
so another approach would be:
def f(x, y):
return sum([(i * x ** 2 + j * y ** 3) for i in range(1,11) for j in range(1, 11)]);
Upvotes: 0
Reputation: 169051
I'm no mathematician, but as far as I could tell, that would translate to
def f(x, y):
return sum(
sum(
i * x ** 2 + j * y ** 3
for j in range(1, 11)
)
for i in range(1, 11)
)
or written out as for loops,
def f(x, y):
value = 0
for i in range(1, 11):
for j in range(1, 11):
value += i * x ** 2 + j * y ** 3
return value
Upvotes: 3