max_val_algos.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. ### Author: estelendur
  2. # Find the maximum value k of a function f(X) where X = [x1,x2,...,xn]
  3. # Each xi in a range [ai,bi]
  4. # Uses shiftwidth=4 for tabs; foldmarker={{{,}}} for folds;
  5. import random
  6. ### Methodical algorithm {{{
  7. # Find the highest value of f varying only x1, then x2, then...
  8. def methodical(f,x,ab,varyf,varyv):
  9. # initialize each xi to rand(ai, bi)
  10. for i in range(len(x)):
  11. a = ab[i][0]
  12. b = ab[i][1]
  13. rand = random.random()
  14. x[i] = (rand*(b-a)) + a
  15. for i in range(len(x)):
  16. x[i] = varyf(f,x,ab,i,varyv)
  17. return f(x)
  18. ### End Methodical }}}
  19. ### Step-wise vary function {{{
  20. # Takes xi through its range in varyv steps of equal size
  21. # Vary functions: take function, x[], ab[], i, varyv
  22. def stepvary(f,x,ab,i,varyv):
  23. a = ab[i][0]
  24. b = ab[i][1]
  25. step = (b-a)/varyv
  26. currplace = a
  27. currmax = f(x) # the current highest value of f
  28. top = x[i] # the value of x[i] for which f is highest
  29. while(currplace <= b):
  30. x[i] = currplace
  31. if f(x) > currmax:
  32. currmax = f(x)
  33. top = x[i]
  34. currplace += step
  35. return top
  36. ### End Step-wise vary }}}