title: Is it possible to implement Newton's method *once* in VBA?
body: <p>I need to use Newton's method on closures.</p>
  
  <pre><code>Function f (x as Double, y as Double) as Double
      f = x^3-y
  End Function
  </code></pre>
  
  <p>I get the value of  <code>y</code> from a cell and then I would like to find out when <code>f</code> is zero. In the toy example above, if the cell contains <code>y=8</code>, then I would expect Newton's method to find a solution close to <code>x=2</code>.</p>
  
  <p>My solution was to make a <code>newton_solve_f</code> function:</p>
  
  <pre><code>Function newton_solve_f (y as Double as Double) as Double
      Dim x as Double
      x = 0 'initial guess for x
      'do Newton's method to find x
      ...
      newton_solve_f = x
  End Function
  </code></pre>
  
  <p>so in effect, I copy paste my code for Newton's method (<a href="http://www.econ-pol.unisi.it/palmieri/slides/VBA/VBA%20%20iterative%20function.pdf#page=7" rel="nofollow">taken from here</a>) into <code>newton_solve_f</code>.</p>
  
  <p>The problem is that I have several such <code>f</code>s (some with more than two arguments), and it would be really neat if I didn't have to make a separate almost identical <code>newton_solve_f</code> for every one of them.</p>
  
  <p>How would you solve this in VBA?</p>
  
  <p>In Python, for example, it's possible to solve this problem as follows:</p>
  
  <pre><code>def f(y):
      def g(x):
          return x^3-y
      return g
  
  def newton_solve(f):
      #do newton's method on f(x)
  
  newton_solve(f(3))
  </code></pre>
  
  <p>Here <code>f(3)</code> is a function, a <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" rel="nofollow">closure</a> of one variable. (The closure example on wikipedia is almost identical to this one.)</p>
  
  <p>ps. I know Newton's method also needs the (partial) derivative of <code>f</code>, I'm actually doing something that's more like the secant method, but that's irrelevant for what I'm asking about</p>