Need help with python

How would this equation:
10n + \sum_{i=1}^n\left((x_i - 1)^2 - 10\cos(2\pi(x_i - 1))\right)

look like when implemented with python function?

That is, without the help of sum() nor numpy nor Mathdotnet.Numerics.

I would like to understand the structure.

If possible also the for or if loops to not be in the same line of the return as this is still very confusing to me.

Much obliged.

A sum is simply:

def sumthing(n):
  s = 0
  for i in range(1,n+1):
    s = s + i
  return s

Write in for then i in s = s + i the expression you need for your calculation.

1 Like

do I need to create a function inside a function, because I have a member A*n that is added to the sum in the final answer?

For your initial bit it would be

thefinalanswer = 10*n + sumthing(n)

You can obviously parametrize the sumthing as you please, if you want the A = 10 passed in as well.

def sumthing(A, n):
  s = 0
  for i in range(1, n+1):
    s = s + i # elaborate calculation instead of i
  return s

def entireFormula(A, n):
  return A*n + sumthing(A, n)

why is A in the first function?

I assumed the 10 in your original formula is the A you mention later, then you could call this with whatever you want for A and whatever for n. This formula is now reusable :slight_smile:

1 Like

Thanks Nathan,

I’ll try that with a couple of equations that just couldn’t figure out.
I’ll ask again if I am still missing something.

By the way this is the Rastrigin function. :slight_smile:

Sorry, I don’t speak math :slight_smile: