functions and branching /dfdx( ( return #call the method for ( ) ** - * +exp(-xf lambda xx** - * +exp(-xdfdx lambda * - -exp(-xsol newton( ,dfdx, , - print( ' {sol:gis an approximate rootf({sol: }{ (sol): }'notice how the variable is updated inside the loop the algorithm only needs to know the value at one iteration to compute the next oneso for each iteration we update to hold the most recent approximationand then use this to compute the next one note also that the implementation provided here is not very robustand if the method does not convergeit will simply continue in an infinite loop one simple way to improve the implementation is to stop the method after given number of iterationsfrom math import exp def newton (fdfdxx max_it= tol - ) ( iter while abs( tol and iter max_itx /dfdx( ( iter + converged iter max_it return convergediter #call the method for ( ) ** - * +exp(-xf lambda xx** - * +exp(-xdfdx lambda * - -exp(-xsolconvergediter newton ( ,dfdx, ,tol= - if convergedprint( 'newtons method converged in {iteriterations'elseprint( 'the method did not converge'newton' method usually converges much faster than the bisection methodbut has the disadvantage the function needs to be manually differentiated in we will see some examples of how this step can be avoided