Learn R Programming

vectorialcalculus (version 1.0.5)

secant_tangent: Secant lines converge to the tangent line (Plotly)

Description

Approximates the derivative of a function at a point numerically and builds an interactive Plotly animation showing how secant (incremental quotient) lines converge to the tangent line as the step size decreases. The secant point(s) used for the slope computation are also animated.

Usage

secant_tangent(
  f,
  x0,
  h_vals = NULL,
  method = c("forward", "central"),
  xlim = NULL,
  n_curve = 400L,
  frame_ms = 220L,
  transition_ms = 220L,
  title = NULL,
  safe_mode = TRUE
)

Value

A list with components:

plot

A plotly object (htmlwidget) with animation frames.

derivative

Numeric scalar. Derivative estimate using the smallest h.

data

Data frame used for the animated secant lines (useful for debugging).

Arguments

f

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

x0

Numeric scalar. Point where the derivative is approximated.

h_vals

Numeric vector. Positive step sizes used as animation frames. If NULL, a default decreasing sequence is used.

method

Character. Derivative approximation method: "forward" (default) or "central".

xlim

Numeric vector of length 2. Plot range for x. If NULL, it is chosen automatically from x0 and h_vals.

n_curve

Integer. Number of points used to draw the curve and lines.

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 forward incremental quotient is $$ m_h = \frac{f(x_0+h)-f(x_0)}{h}. $$ The central difference approximation is $$ m_h = \frac{f(x_0+h)-f(x_0-h)}{2h}. $$ The tangent line model at x0 is $$ y = f(x_0) + f'(x_0)\,(x-x_0). $$

Examples

Run this code
# \donttest{
library(plotly)

f <- function(x) x^2
out <- secant_tangent(f, x0 = 1)
out$plot
out$derivative

g <- function(x) sin(x)
secant_tangent(g, x0 = 0.7, method = "central", h_vals = 2^(-(1:7)))
# }

Run the code above in your browser using DataLab