12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- ### Author: estelendur
- # Find the maximum value k of a function f(X) where X = [x1,x2,...,xn]
- # Each xi in a range [ai,bi]
- # Uses shiftwidth=4 for tabs; foldmarker={{{,}}} for folds;
- import random
- ### Methodical algorithm {{{
- # Find the highest value of f varying only x1, then x2, then...
- def methodical(f,x,ab,varyf,varyv):
- # initialize each xi to rand(ai, bi)
- for i in range(len(x)):
- a = ab[i][0]
- b = ab[i][1]
- rand = random.random()
- x[i] = (rand*(b-a)) + a
- for i in range(len(x)):
- x[i] = varyf(f,x,ab,i,varyv)
- return f(x)
- ### End Methodical }}}
- ### Step-wise vary function {{{
- # Takes xi through its range in varyv steps of equal size
- # Vary functions: take function, x[], ab[], i, varyv
- def stepvary(f,x,ab,i,varyv):
- a = ab[i][0]
- b = ab[i][1]
- step = (b-a)/varyv
- currplace = a
- currmax = f(x) # the current highest value of f
- top = x[i] # the value of x[i] for which f is highest
- while(currplace <= b):
- x[i] = currplace
- if f(x) > currmax:
- currmax = f(x)
- top = x[i]
- currplace += step
- return top
- ### End Step-wise vary }}}
|