# L-5 MCS 471 Wed 31 Aug 2022 : newtonupdate.jl """ This script illustrates the definition of the update function dx = - f(x)/f'(x) for any function in x with SymPy, to run one step with Newton's method x = x + dx. """ using SymPy x = Sym("x") """ Returns the string representation of the derivative of the expression in x, given in the string s. """ function SymPyDerivative(s::String) evaluated = sympify(s) derivative = diff(evaluated, x) return string(derivative) end """ Given a string representation of an expression in x, returns the Julia function for the update -f(x)/f'(x), where f(x) is the function defined by the input string. """ function NewtonUpdate(f::String, verbose::Bool=true) sdf = SymPyDerivative(f) sdx = string("-(", f, ")/(", sdf, ")") if verbose println("update : $sdx") end edx = sympify(sdx) return lambdify(edx) end # a simple test dx = NewtonUpdate("x^3 + x - 1") println("dx(1.0) : ", dx(1.0))