Advertisement
Guest User

randomwalk

a guest
Nov 13th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import numpy as np
  2. np.random.seed( 101 )
  3. def f( x,y ):
  4. return -((x-4)**2 + (y+2)**2)
  5. # Random walk algorithm begins here. ###############################
  6. X = np.linspace( -5,5,401 ) # set up a grid in x
  7. Y = np.linspace( -5,5,401 ) # set up a grid in y
  8. xy = np.random.randint( 401,size=(2,) )
  9. u = np.array( ( 0,-1 ) ) # "up" looking at array in quadrant 4
  10. d = np.array( ( 0,+1 ) ) # "down" looking at array in quadrant 4
  11. l = np.array( ( -1,0 ) ) # "left" looking at array in quadrant 4
  12. r = np.array( ( +1,0 ) ) # "right" looking at array in quadrant 4
  13.  
  14. num_steps = 500000
  15. best_xy = xy
  16. best_f = f( xy[ 0 ],xy[ 1 ] )
  17. steps = np.empty( ( num_steps,3 ) )
  18. for i in range( num_steps ):
  19. # Take a random step, 25% chance in each direction.
  20. trial_xy = xy.copy()
  21. chance = np.random.uniform()
  22. if chance < 0.25:
  23. trial_xy = ( xy + u ) % Y.shape[ 0 ]
  24. elif chance < 0.5:
  25. trial_xy = ( xy + d ) % Y.shape[ 0 ]
  26. elif chance < 0.75:
  27. trial_xy = ( xy + l ) % X.shape[ 0 ]
  28. else:
  29. trial_xy = ( xy + r ) % X.shape[ 0 ]
  30.  
  31. if f( X[ trial_xy[ 0 ] ],Y[ trial_xy[ 1 ] ] ) > best_f:
  32. # If the solution improves, accept it.
  33. best_f = f( X[ trial_xy[ 0 ] ],Y[ trial_xy[ 1 ] ] )
  34. best_xy = trial_xy.copy()
  35. xy = trial_xy.copy()
  36. else:
  37. # If the solution does not improve, sometimes accept it.
  38. chance = np.random.uniform()
  39. if chance < 0.25:
  40. xy = trial_xy.copy()
  41.  
  42. if i % 100 == 0:
  43. print( xy,f( X[ trial_xy[ 0 ] ],Y[ trial_xy[ 1 ] ] ),best_xy,best_f )
  44.  
  45. # Log steps for plotting later.
  46. steps[ i,: ] = np.array( ( xy[ 0 ],xy[ 1 ],f( X[ trial_xy[ 0 ] ],Y[ trial_xy[ 1 ] ] ) ) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement