MCPcopy Create free account
hub / github.com/cfgnunes/numerical-methods-python / example_solution_newton

Function example_solution_newton

main.py:214–246  ·  view source on GitHub ↗

Run an example 'Solutions: Newton'.

()

Source from the content-addressed store, hash-verified

212
213@print_docstring
214def example_solution_newton():
215 """Run an example 'Solutions: Newton'."""
216 # Newton method (find roots of an equation)
217 # Pros:
218 # It is a fast method.
219 # Cons:
220 # It may diverge;
221 # It is necessary to calculate the derivative of the function;
222 # It is necessary to give an initial x0 value where
223 # f'(x0) must be nonzero.
224
225 def f(x):
226 return 2 * x ** 3 - math.cos(x + 1) - 3
227
228 def df(x):
229 return 12 * x ** 2 + 1 - math.sin(x)
230
231 x0 = 1.0
232 toler = 0.01
233 iter_max = 100
234
235 print("Inputs:")
236 print(f"x0 = {x0}")
237 print(f"toler = {toler}")
238 print(f"iter_max = {iter_max}")
239
240 print("Execution:")
241 root, i, converged = solutions.newton(f, df, x0, toler, iter_max)
242
243 print("Output:")
244 print(f"root = {root:.5f}")
245 print(f"i = {i}")
246 print(f"converged = {converged}")
247
248
249@print_docstring

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected