Symmetryc

Equation API, By Symmetryc & Wobbo

Dec 19th, 2013
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.11 KB | None | 0 0
  1. -----------
  2. -- API that holds miscellaneous functions for equations
  3. -- @author Symmetryc, Wobbo
  4. -- @module api
  5. -- @alias M
  6.  
  7. local M = {}
  8.  
  9. --- Create a derivative for a function
  10. -- This function takes two arguments, a function and a delta. The delta can be left unspecified. The function returned is an approximation for the derivative of the given function, and delta specifies the accuracy, where a smaller delta results in a higher accuracy.
  11. -- @tparam func _f The function to derive from
  12. -- @tparam number delta The accuracy of the derivation, defaults to 1e-6
  13. -- @treturn func The derivative of _f
  14. M.derive = function(_f, _delta)
  15.     local delta = _delta or 1e-6
  16.     return function(x)
  17.         return (_f(x + delta) - _f(x)) / delta
  18.     end
  19. end
  20.  
  21. --- Creates an equation object
  22. -- @param f The function that the equation will use to create values
  23. -- @return The equation
  24. M.eq = function(_f)
  25.     return setmetatable({f = _f}, {
  26.         __index = function(self, _key)
  27.             self[_key] = self.f(_key)
  28.             return self[_key]
  29.         end;
  30.     })
  31. end
  32.  
  33. --- Finds the solution to an equation using Newton-Raphson method
  34. -- @param api The api itself (call using `:` syntactic sugar)
  35. -- @param eq The equation that you are solving
  36. -- @param init The initial guess
  37. -- @param loop How many loops the approximation should go through
  38. -- @return The solution
  39. M.nr = function(api, _eq, _init, _loop)
  40.     local ans = _init or 0.1
  41.     local fprime = api.derive(_eq)
  42.     for i = 1, _loop or 5 do
  43.         ans = ans - _eq(ans) / fprime(ans)
  44.     end
  45.     return ans
  46. end
  47.  
  48. --- Funciton for implicit equations
  49. -- @param api The api itself (call using `:` syntactic sugar)
  50. -- @param str The string of the equation
  51. -- @return The equation solved for x
  52. -- @return The equation solved for y
  53. M.impl = function(api, _str)
  54.     local f = function(x, y)
  55.         return setfenv(loadstring("return ".._str:gsub("(.-)=(.+)", "(%1)-(%2)")), setmetatable({x = x, y = y}, {__index = math}))()
  56.     end
  57.     local fx = function(x)
  58.         return api:nr(function(y) return f(x, y) end, x)
  59.     end
  60.     local fy = function(y)
  61.         return api:nr(function(x) return f(x, y) end, y)
  62.     end
  63.     return api.eq(fx), api.eq(fy)
  64. end
  65.  
  66. return M
Add Comment
Please, Sign In to add comment