Learn R Programming

vectorialcalculus (version 1.0.5)

newton_raphson_anim: Newton-Raphson root finding with tangent animation (Plotly)

Description

Builds a Plotly animation of the Newton-Raphson method for finding a root of a real function. Each frame shows the tangent line at the current iterate and how its x-intercept defines the next iterate.

Usage

newton_raphson_anim(
  f,
  x0,
  df = NULL,
  h = 1e-04,
  max_iter = 10L,
  tol = 1e-08,
  xlim = NULL,
  n_curve = 600L,
  frame_ms = 600L,
  transition_ms = 400L,
  title = NULL,
  safe_mode = TRUE
)

Value

A list with components:

plot

A plotly object (htmlwidget) with animation frames.

iterates

Data frame with iterations (n, x, fx, dfx).

root

Last iterate (approximate root).

converged

Logical. TRUE if convergence was detected within max_iter.

Arguments

f

Function. A real-valued function f(x). Must accept a numeric vector and return a numeric vector of the same length.

x0

Numeric scalar. Initial guess.

df

Optional function. Derivative f'(x). If NULL, a numerical derivative is used.

h

Numeric scalar. Step size for numerical derivative (when df is NULL).

max_iter

Integer. Maximum number of iterations.

tol

Numeric scalar. Stopping tolerance based on |f(x_n)|.

xlim

Numeric vector of length 2. Plot range for x. If NULL, it is chosen around the iterates.

n_curve

Integer. Number of points used to draw the curve.

frame_ms

Integer. Frame duration in milliseconds.

transition_ms

Integer. Transition duration in milliseconds.

title

Character. Plot title. If NULL, a default title is used.

safe_mode

Logical. If TRUE, use calmer animation defaults intended to reduce flicker and visual stress.

Details

The Newton-Raphson update is $$ x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}. $$ If a derivative function is not provided, the derivative is approximated numerically by the central difference $$ f'(x) \approx \frac{f(x+h)-f(x-h)}{2h}. $$

Examples

Run this code
# \donttest{
library(plotly)

f <- function(x) x^3 - 2*x - 5
out <- newton_raphson_anim(f, x0 = 2)
out$plot
out$root

g <- function(x) cos(x) - x
newton_raphson_anim(g, x0 = 1)
# }

Run the code above in your browser using DataLab