Sujet : Re: Beazley's Problem
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 23. Sep 2024, 14:26:38
Autres entêtes
Organisation : Stefan Ram
Message-ID : <Newton-20240923132243@ram.dialup.fu-berlin.de>
References : 1 2 3 4 5
Annada Behera <
annada@tilde.green> wrote or quoted:
The "next-level math trick" Newton-Raphson has nothing to do with
functional programming.
Nobody up the thread was claiming it was functional. And you can
totally implement anything in an imperative or functional style.
from typing import Callable
def newton_raphson(
f: Callable[[float], float],
f_prime: Callable[[float], float],
x0: float,
epsilon: float = 1e-7,
max_iterations: int = 100
) -> float:
def recurse(x: float, iteration: int) -> float:
if iteration > max_iterations:
raise ValueError("Maximum iterations reached. The method may not converge.")
fx: float = f(x)
if abs(fx) < epsilon:
return x
x_next: float = x - fx / f_prime(x)
return recurse(x_next, iteration + 1)
return recurse(x0, 0)
# Example application: find a root of f(x) = x^2 - 4
# Define the function and its derivative
def f(x: float) -> float:
return x**2 - 4
def f_prime(x: float) -> float:
return 2*x
# Initial guess
x0: float = 1.0
try:
root: float = newton_raphson(f, f_prime, x0)
print(f"The root is approximately: {root}")
print(f"f({root}) = {f(root)}")
except ValueError as e:
print(f"Error: {e}")