1

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?

Please click to see the mathematical expression. I cannot embed

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Does this answer your question? [Nested summation in python](https://stackoverflow.com/questions/66475717/nested-summation-in-python) – Jonathan Scholbach Oct 11 '21 at 11:57
  • The expressions are a bit different but I guess it potentially could, yes. I accepted an answer supplied by AKX. The other solutions are good to know as well. – Maria Evans Oct 11 '21 at 12:12

3 Answers3

3

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
AKX
  • 152,115
  • 15
  • 115
  • 172
1

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(² + ³)

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thanks Trincot. Sorry I already accepted AKX answer before seeing any more solutions really but I hope they will all help others in case they have a similar problem in the future. – Maria Evans Oct 11 '21 at 12:15
0

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)]);
Souperman
  • 5,057
  • 1
  • 14
  • 39