Deutsch English Français Italiano |
<Newton-20240923132243@ram.dialup.fu-berlin.de> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!news.mixmin.net!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail From: ram@zedat.fu-berlin.de (Stefan Ram) Newsgroups: comp.lang.python Subject: Re: Beazley's Problem Date: 23 Sep 2024 12:26:38 GMT Organization: Stefan Ram Lines: 49 Expires: 1 Jul 2025 11:59:58 GMT Message-ID: <Newton-20240923132243@ram.dialup.fu-berlin.de> References: <problem-20240921130726@ram.dialup.fu-berlin.de> <87tte941ko.fsf@nightsong.com> <newton-20240921151727@ram.dialup.fu-berlin.de> <87plow4v4p.fsf@nightsong.com> <0709b4b8b0bbf2a32d53649d1a6fbefbcd44a68a.camel@tilde.green> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de MhHMeHGEDJkkKr5yvniG1QcRef70q1EE5Su4TETfrBCOU4 Cancel-Lock: sha1:BPjQO8/eZGVm9mcMLYynUOUMiOc= sha256:P556lyQSH0RBiw+SpaOU+o0cJaEhmwam977NgDQd/f8= X-Copyright: (C) Copyright 2024 Stefan Ram. All rights reserved. Distribution through any means other than regular usenet channels is forbidden. It is forbidden to publish this article in the Web, to change URIs of this article into links, and to transfer the body without this notice, but quotations of parts in other Usenet posts are allowed. X-No-Archive: Yes Archive: no X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some services to mirror the article in the web. But the article may be kept on a Usenet archive server with only NNTP access. X-No-Html: yes Content-Language: en-US Bytes: 2881 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}")