Learn R Programming

vectorialcalculus (version 1.0.5)

newton_raphson2d: Newton-Raphson method for systems in R^2 with animation (Plotly)

Description

Applies the Newton-Raphson method to solve a nonlinear system in two variables: $$ \mathbf{F}(x,y)=\mathbf{0}, $$ where $$ \mathbf{F}(x,y)=\begin{pmatrix}f_1(x,y)\\ f_2(x,y)\end{pmatrix}. $$ At an iterate $$ \mathbf{x}_n=(x_n,y_n), $$ the Newton update is $$ \mathbf{x}_{n+1}=\mathbf{x}_n - J(\mathbf{x}_n)^{-1}\mathbf{F}(\mathbf{x}_n), $$ where the Jacobian matrix is $$ J(x,y)=\begin{pmatrix} \frac{\partial f_1}{\partial x}(x,y) & \frac{\partial f_1}{\partial y}(x,y)\\ \frac{\partial f_2}{\partial x}(x,y) & \frac{\partial f_2}{\partial y}(x,y) \end{pmatrix}. $$ If a Jacobian function is not provided, partial derivatives are approximated numerically by central differences.

Usage

newton_raphson2d(
  f,
  x0,
  J = NULL,
  h = 1e-04,
  max_iter = 10L,
  tol = 1e-08,
  xlim = NULL,
  ylim = NULL,
  n_grid = 120L,
  frame_ms = 700L,
  transition_ms = 450L,
  title = NULL,
  safe_mode = TRUE
)

Value

A list with components:

plot

A plotly object (htmlwidget) with animation frames.

iterates

Data frame of iterates (n, x, y, f1, f2, norm_inf).

root

Numeric vector c(x, y) with the last iterate.

converged

Logical. TRUE if convergence was detected within max_iter.

Arguments

f

Function. A function f(x,y) that returns a numeric vector of length 2: c(f1(x,y), f2(x,y)).

x0

Numeric vector of length 2. Initial guess c(x0, y0).

J

Optional function. A function J(x,y) returning a 2x2 numeric matrix (the Jacobian). If NULL, a numerical Jacobian is used.

h

Numeric scalar. Step size for numerical partial derivatives (when J is NULL).

max_iter

Integer. Maximum number of Newton iterations.

tol

Numeric scalar. Stopping tolerance based on the infinity norm: max(|f1|,|f2|) <= tol.

xlim

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

ylim

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

n_grid

Integer. Grid size per axis used to draw the zero level curves.

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, uses calmer animation defaults intended to reduce flicker and visual stress.

Details

The animation shows the two zero level curves $$ f_1(x,y)=0 \quad \text{and} \quad f_2(x,y)=0 $$ together with the Newton iterates and the step segments $$ \mathbf{x}_n \to \mathbf{x}_{n+1}. $$

Examples

Run this code
# \donttest{
library(plotly)

# Example system:
# f1(x,y)=x^2+y^2-1 (unit circle)
# f2(x,y)=x-y (line)
f <- function(x, y) c(x^2 + y^2 - 1, x - y)

out <- newton_raphson2d(f, x0 = c(0.8, 0.2), max_iter = 8)
out$plot
out$iterates
out$converged
out$root
# }

Run the code above in your browser using DataLab