Re: Beazley's Problem

Liste des GroupesRevenir à cl python 
Sujet : Re: Beazley's Problem
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 23. Sep 2024, 13: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}")



Date Sujet#  Auteur
21 Sep 24 * Beazley's Problem14Stefan Ram
21 Sep 24 `* Re: Beazley's Problem13Paul Rubin
21 Sep 24  `* Re: Beazley's Problem12Stefan Ram
21 Sep 24   `* Re: Beazley's Problem11Paul Rubin
23 Sep 24    `* Re: Beazley's Problem10Annada Behera
23 Sep 24     +* Re: Beazley's Problem8Stefan Ram
24 Sep 24     i+- Re: Beazley's Problem (Posting On Python-List Prohibited)1Lawrence D'Oliveiro
24 Sep 24     i+* Re: Beazley's Problem4Paul Rubin
24 Sep 24     ii+- Re: Beazley's Problem1Annada Behera
10 Nov 24     ii`* Re: Beazley's Problem2david k. combs
10 Nov 24     ii `- Re: Beazley's Problem1Paul Rubin
26 Sep 24     i`* Modern Optimization (was: Beazley's Problem)2Stefan Ram
26 Sep 24     i `- Re: Modern Optimization1Stefan Ram
6 Oct 24     `- Re: Beazley's Problem1Antoon Pardon

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal