r/dailyprogrammer • u/Steve132 0 1 • Jul 25 '12
[7/25/2012] Challenge #81 [intermediate] (Local Minimization)
For a lot of the questions today we are going to be doing some simple numerical calculus. Don't worry, its not too terrifying.
Write a function fmin that can take in a real-valued function f(x) where x is a vector in 3D space (bonus points for N-D).
xout=fmin(f,x0) should return a local minimum of f close to x0.
Example in Python
%f is a function with 1 3-vector
def f(x):
return x[0]**2+x[1]**2+x[2]**2
%find the local minimum of f, starting at (1,1,1)
print fmin(f,[1.0,1.0,1.0])should print out
[0.0,0.0,0.0] %because (0,0,0) is the global minimum of f(x,y,z)=x^2+y^2+z^2EDIT: To make this a little easier, I decided that it is acceptable for your implementation to require that fmin have additional arguments for the derivatives of f
2
u/Cosmologicon 2 3 Jul 25 '12
I decided to do this without calculus. Here's a simple Markov chain in python:
1
u/goldjerrygold_cs Jul 26 '12
As a high level description, I was considering starting at that point and travelling in the reverse direction of the gradient by some increment. Does that sound valid? As far as the increment, I was planning on travelling by some small constant (maybe 1) along the negative gradient (recalculating the gradient at each new point). If the gradient actually increases, we might decrease the decrement or something like that.
1
u/skeeto -9 8 Jul 28 '12 edited Jul 28 '12
Compared to other intermediate and difficult problems, I'd say this one may qualify as "difficult."
Here's my solution. I made up my own gradient descent algorithm using Newton's method. It's able to compute the first and second derivative of
f()on its own, so that it can use Newton's method.And the output.
It's not too exciting with the example function because the second derivative is a constant. This means it's able to solve the problem in a single step, so this is all a bit overkill. Oh, and it achieves the bonus.