### R: Root Finding with rootSolve for Univariate and Multivariate Equations Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Demonstrates finding roots of univariate and multivariate nonlinear equations using the rootSolve package in R. Includes examples for finding all roots of a function within an interval and solving systems of equations. ```r library(rootSolve) # Find all roots of a univariate function in an interval f <- function(x) x^3 - 5*x^2 + 6*x - 2 x_range <- c(-2, 5) # Find all roots (uniroot.all attempts to find multiple roots) all_roots <- uniroot.all(f, x_range) cat("All roots found:", all_roots, "\n") # Verify roots for(r in all_roots) { cat("f(", r, ") =", f(r), "\n") } # Plot function with roots x_plot <- seq(-2, 5, by = 0.01) plot(x_plot, f(x_plot), type = "l", main = "Root Finding for f(x) = x³ - 5x² + 6x - 2", xlab = "x", ylab = "f(x)") abline(h = 0, col = "gray", lty = 2) points(all_roots, rep(0, length(all_roots)), col = "red", pch = 19, cex = 1.5) # Multivariate root finding: solve system of equations # x + y = 3 # x^2 + y^2 = 5 system <- function(x) { c(x[1] + x[2] - 3, x[1]^2 + x[2]^2 - 5) } # Initial guess start <- c(1, 1) solution <- multiroot(system, start) cat("\nSystem solution:\n") cat("x =", solution$root[1], "\n") cat("y =", solution$root[2], "\n") cat("Residual:", solution$f.root, "\n") cat("Precision:", solution$estim.precis, "\n") # Verify solution x_sol <- solution$root[1] y_sol <- solution$root[2] cat("Verification:\n") cat("x + y =", x_sol + y_sol, "(expected: 3)\n") cat("x² + y² =", x_sol^2 + y_sol^2, "(expected: 5)\n") # Larger system: economic equilibrium # Supply: p = 2q + 3 # Demand: p = -q + 15 # Market clearing: q_supply = q_demand market <- function(x) { q <- x[1] p <- x[2] c(p - (2*q + 3), # supply equation p - (-q + 15), # demand equation 2*q + 3 - (-q + 15)) # equilibrium condition } equilibrium <- multiroot(market, c(5, 10)) cat("\nMarket equilibrium:\n") cat("Quantity:", equilibrium$root[1], "\n") cat("Price:", equilibrium$root[2], "\n") ``` -------------------------------- ### R: Multiple Precision Arithmetic with gmp Package Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Shows how to perform arbitrary-precision arithmetic for integers and rational numbers using the gmp package in R. Includes examples of basic operations, prime factorization, primality testing, GCD, LCM, and modular arithmetic. ```r library(gmp) # Large integer arithmetic big_int1 <- as.bigz("123456789012345678901234567890") big_int2 <- as.bigz("987654321098765432109876543210") # Basic operations sum_result <- big_int1 + big_int2 prod_result <- big_int1 * big_int2 power_result <- pow.bigz(2, 100) cat("Sum:", as.character(sum_result), "\n") cat("Product:", as.character(prod_result), "\n") cat("2^100:", as.character(power_result), "\n") # Prime factorization n <- as.bigz("1234567890") factors <- factorize(n) cat("\nFactorization of 1234567890:\n") print(factors) # Verify factorization product_factors <- prod(factors) cat("Product of factors:", as.character(product_factors), "\n") # Probabilistic primality test candidate <- as.bigz("170141183460469231731687303715884105727") is_prime <- isprime(candidate) cat("\nIs", as.character(candidate), "prime?", ifelse(is_prime > 0, "Yes", "No"), "\n") # Greatest Common Divisor a <- as.bigz("123456789") b <- as.bigz("987654321") gcd_result <- gcd.bigz(a, b) lcm_result <- lcm.bigz(a, b) cat("GCD:", as.character(gcd_result), "\n") cat("LCM:", as.character(lcm_result), "\n") # Rational arithmetic rat1 <- as.bigq(1, 3) rat2 <- as.bigq(1, 6) rat_sum <- rat1 + rat2 rat_prod <- rat1 * rat2 cat("\n1/3 + 1/6 =", as.character(rat_sum), "\n") cat("1/3 * 1/6 =", as.character(rat_prod), "\n") # Modular arithmetic base <- as.bigz(123) modulus <- as.bigz(456) result_mod <- base %% modulus power_mod <- powm(base, 10, modulus) # 123^10 mod 456 cat("\n123 mod 456 =", as.character(result_mod), "\n") cat("123^10 mod 456 =", as.character(power_mod), "\n") ``` -------------------------------- ### Eigenvalue Decomposition for Large Matrices with rARPACK Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Shows how to efficiently compute a subset of eigenvalues and eigenvectors for large, sparse, and symmetric matrices using the rARPACK package. The example demonstrates selecting the largest eigenvalues and verifies the results using the eigenvalue equation. ```r library(rARPACK) # Create a large symmetric matrix n <- 1000 set.seed(123) A <- matrix(rnorm(n * n), n, n) A <- (A + t(A)) / 2 # Make symmetric # Compute only the 5 largest eigenvalues and eigenvectors result <- eigs_sym(A, k = 5, which = "LA") # Extract eigenvalues and eigenvectors eigenvalues <- result$values eigenvectors <- result$vectors print("Five largest eigenvalues:") print(eigenvalues) # Verify: A * v = lambda * v for(i in 1:5) { v <- eigenvectors[, i] lambda <- eigenvalues[i] residual <- norm(A %*% v - lambda * v, "2") cat("Eigenvalue", i, "residual:", residual, " \n") } ``` -------------------------------- ### Spline Interpolation and Signal Filtering with signal Package Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Provides functions for piecewise cubic Hermite interpolation and signal filtering on discrete data. It requires the signal package. The example shows how to define data points and implies subsequent interpolation or filtering operations. ```r library(signal) # Original data points x <- c(0, 1, 2, 3, 4, 5) y <- c(0, 0.5, 2, 1.5, 1, 0.5) ``` -------------------------------- ### Polynomial Manipulation and Evaluation in R with PolynomF Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Demonstrates the creation, arithmetic, evaluation, and root finding of univariate polynomials using the PolynomF package. It includes creating polynomials from coefficients and roots, performing addition and multiplication, evaluating polynomials at specific points, and finding roots using base R's polyroot function. A Horner's method implementation for efficient evaluation is also shown. ```r library(PolynomF) # Create polynomials: p(x) = x^2 + 2x + 1 p <- poly_calc(c(1, 2, 1)) print(p) # Create polynomial from roots: (x-1)(x-2)(x-3) roots <- c(1, 2, 3) q <- poly_from_roots(roots) print(q) # Polynomial arithmetic p1 <- poly_calc(c(1, 2, 1)) # x^2 + 2x + 1 p2 <- poly_calc(c(1, -1)) # x - 1 sum_poly <- p1 + p2 prod_poly <- p1 * p2 cat("Sum:", as.character(sum_poly), " \n") cat("Product:", as.character(prod_poly), " \n") # Evaluate polynomial x_vals <- seq(-2, 2, by = 0.5) y_vals <- predict(p1, x_vals) plot(x_vals, y_vals, type = "l", main = "p(x) = x² + 2x + 1", xlab = "x", ylab = "p(x)") abline(h = 0, col = "gray", lty = 2) # Find roots using base R polynomial_roots <- polyroot(c(1, 2, 1)) cat("Roots:", polynomial_roots, " \n") # Horner's method for efficient evaluation horner_eval <- function(coeffs, x) { result <- coeffs[length(coeffs)] for(i in (length(coeffs)-1):1) { result <- result * x + coeffs[i] } result } cat("p(2) =", horner_eval(c(1, 2, 1), 2), " \n") ``` -------------------------------- ### Gaussian Quadrature Rules with gaussquad Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Generates nodes and weights for various orthogonal polynomial quadrature rules, including Gauss-Legendre, Gauss-Hermite, Gauss-Laguerre, and Chebyshev. It requires the gaussquad package and allows for numerical integration of functions based on these rules. ```r library(gaussquad) # Gauss-Legendre quadrature: ∫₋₁¹ f(x) dx n <- 5 # number of nodes rule_legendre <- legendre.quadrature.rules(n)[[n]] nodes <- rule_legendre$x weights <- rule_legendre$w # Integrate f(x) = x^4 from -1 to 1 # Analytical result: 2/5 = 0.4 f <- function(x) x^4 integral <- sum(weights * f(nodes)) cat("Legendre quadrature (n=5):", integral, "(expected: 0.4)\n") # Gauss-Hermite quadrature: ∫₋∞^∞ f(x) exp(-x²) dx rule_hermite <- hermite.h.quadrature.rules(10)[[10]] h_nodes <- rule_hermite$x h_weights <- rule_hermite$w # Standard normal probability (integrate x²) f_norm <- function(x) x^2 integral_hermite <- sum(h_weights * f_norm(h_nodes)) / sqrt(pi) cat("Hermite quadrature (x²):", integral_hermite, "(expected: 1)\n") # Gauss-Laguerre quadrature: ∫₀^∞ f(x) exp(-x) dx rule_laguerre <- laguerre.quadrature.rules(8)[[8]] l_nodes <- rule_laguerre$x l_weights <- rule_laguerre$w # Compute Γ(3) = 2! = 2 f_gamma <- function(x) x^2 gamma_3 <- sum(l_weights * f_gamma(l_nodes)) cat("Laguerre quadrature Γ(3):", gamma_3, "(expected: 2)\n") # Chebyshev quadrature of the first kind rule_cheby <- chebyshev.t.quadrature.rules(6)[[6]] c_nodes <- rule_cheby$x c_weights <- rule_cheby$w # Integrate polynomial f_poly <- function(x) 1 + x + x^2 integral_cheby <- sum(c_weights * f_poly(c_nodes)) cat("Chebyshev quadrature:", integral_cheby, "\n") # Custom integration function gauss_integrate <- function(f, rule) { sum(rule$w * sapply(rule$x, f)) } result <- gauss_integrate(function(x) exp(x), rule_legendre) cat("Custom integration exp(x):", result, "\n") ``` -------------------------------- ### Combinatorics with arrangements in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Generates permutations, combinations, and partitions using the 'arrangements' package in R. It supports options for replacement, multisets, and iterators for memory efficiency with large datasets. The package provides functions to count these objects without explicit generation. ```r library(arrangements) perms <- permutations(5, 3) cat("Number of permutations P(5,3):", nrow(perms), "\n") cat("First 10 permutations:\n") print(head(perms, 10)) combs <- combinations(5, 3) cat("\nNumber of combinations C(5,3):", nrow(combs), "\n") cat("All combinations:\n") print(combs) perms_rep <- permutations(x = 3, k = 2, replace = TRUE) cat("\nPermutations with replacement (3,2):\n") print(perms_rep) combs_rep <- combinations(x = 3, k = 2, replace = TRUE) cat("\nCombinations with replacement (3,2):\n") print(combs_rep) elements <- c("A", "A", "B", "C") perms_multiset <- permutations(freq = c(2, 1, 1), k = 3) cat("\nPermutations of multiset {A,A,B,C}:\n") print(perms_multiset) iter <- ipermutations(10, 3) cat("\nFirst 5 permutations using iterator:\n") for(i in 1:5) { perm <- getnext(iter) cat(perm, "\n") } iter_comb <- icombinations(letters[1:26], 5) cat("\nFirst 3 combinations of 5 letters:\n") for(i in 1:3) { comb <- getnext(iter_comb) cat(paste(comb, collapse = ""), "\n") } n_perms <- npermutations(10, 5) n_combs <- ncombinations(10, 5) cat("\nnpermutations(10, 5):", n_perms, "\n") cat("ncombinations(10, 5):", n_combs, "\n") colors <- c("red", "blue", "green", "yellow") color_perms <- permutations(colors, 2) cat("\nColor permutations:\n") print(color_perms) parts <- partitions(4, 2) cat("\nPartitions of 4 into 2 parts:\n") print(parts) ``` -------------------------------- ### Sparse and Dense Matrix Operations in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Demonstrates dense and sparse matrix operations, including creation, decomposition (Cholesky), matrix exponential, norm calculation, and condition number estimation using the Matrix package. It highlights the efficiency of sparse matrix representations for large, data-sparse problems. ```r library(Matrix) # Create a sparse matrix sparse_mat <- sparseMatrix( i = c(1, 3, 1, 2, 4), j = c(1, 1, 3, 4, 2), x = c(4, 2, 1, 5, 3), dims = c(4, 4) ) print(sparse_mat) # 4 x 4 sparse Matrix of class "dgCMatrix" # # [1,] 4 . 1 . # [2,] . . . 5 # [3,] 2 . . . # [4,] . 3 . . # Compute Cholesky decomposition for positive definite matrix dense_mat <- matrix(c(4, 2, 2, 3), nrow = 2) chol_decomp <- chol(dense_mat) print(chol_decomp) # Matrix exponential mat <- matrix(c(1, 2, 3, 4), nrow = 2) mat_exp <- expm(mat) print(mat_exp) # Compute norm and condition number for sparse matrix norm_val <- norm(sparse_mat, type = "F") # Frobenius norm cond_num <- kappa(as.matrix(sparse_mat)) # Condition number cat("Norm:", norm_val, " \nCondition number:", cond_num, " \n") ``` -------------------------------- ### Solve Optimization Problem using SciPy in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt This snippet demonstrates how to solve an optimization problem (minimize x^2 + 4x + 4) using the SciPy library accessed through R's reticulate package. It outputs the minimum point and the function's value at that point. ```r minimize_result <- scipy_optimize$minimize( fun = function(x) x^2 + 4*x + 4, x0 = 0 ) cat("\nOptimization result:\n") cat("Minimum at x =", minimize_result$x, "\n") cat("Function value:", minimize_result$fun, "\n") ``` -------------------------------- ### Solve Linear System with Rational Coefficients in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Solves a system of linear equations with rational coefficients using the 'bigq' package for exact rational arithmetic. It takes a matrix 'A' and a vector 'b' as input and returns the exact rational solution. ```r A <- rbind(c(2, 3), c(4, -1)) b <- c(7, 5) A_q <- as.bigq(A) b_q <- as.bigq(b) solution_q <- solve(A_q, b_q) cat("\nLinear system solution (exact rational):\n") print(solution_q) ``` -------------------------------- ### R: Interpolation and Savitzky-Golay Filtering Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Demonstrates various interpolation methods (linear, spline, PCHIP) to fit data points and compares them visually. It also shows how to apply the Savitzky-Golay filter for smoothing noisy data using R. ```r x_fine <- seq(0, 5, by = 0.1) # Linear interpolation y_linear <- interp1(x, y, x_fine, method = "linear") # Spline interpolation y_spline <- interp1(x, y, x_fine, method = "spline") # Piecewise Cubic Hermite Interpolation (PCHIP) y_pchip <- pchip(x, y, x_fine) # Plot comparison plot(x, y, pch = 19, col = "black", cex = 1.5, main = "Interpolation Methods Comparison", xlab = "x", ylab = "y", ylim = c(-0.5, 2.5)) lines(x_fine, y_linear, col = "blue", lty = 2) lines(x_fine, y_spline, col = "red", lty = 1) lines(x_fine, y_pchip, col = "green", lty = 3) legend("topright", c("Data", "Linear", "Spline", "PCHIP"), col = c("black", "blue", "red", "green"), pch = c(19, NA, NA, NA), lty = c(NA, 2, 1, 3)) # Savitzky-Golay filter for smoothing noisy data set.seed(42) x_noisy <- seq(0, 2*pi, length.out = 100) y_noisy <- sin(x_noisy) + rnorm(100, 0, 0.1) # Apply Savitzky-Golay filter sgolay_filter <- sgolay(p = 3, n = 11) # polynomial order 3, window size 11 y_smooth <- filter(sgolay_filter, y_noisy) plot(x_noisy, y_noisy, col = "gray", pch = 20, main = "Savitzky-Golay Smoothing") lines(x_noisy, y_smooth, col = "red", lwd = 2) lines(x_noisy, sin(x_noisy), col = "blue", lty = 2, lwd = 2) legend("topright", c("Noisy", "Smoothed", "True"), col = c("gray", "red", "blue"), pch = c(20, NA, NA), lty = c(NA, 1, 2)) ``` -------------------------------- ### Numerical Differentiation with numDeriv Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Computes gradients, Jacobians, and Hessians of functions using Richardson extrapolation and complex step methods. It requires the numDeriv package and accepts functions and points as input, returning numerical approximations of derivatives. ```r library(numDeriv) # Simple function: f(x) = x^2 + 3x + 2 f <- function(x) x^2 + 3*x + 2 x0 <- 2 # First derivative (analytical: 2x + 3 = 7 at x=2) grad_result <- grad(f, x0) cat("Gradient at x=2:", grad_result, "(expected: 7)\n") # Multivariate function: f(x,y) = x^2 + y^2 + xy f_multi <- function(x) x[1]^2 + x[2]^2 + x[1]*x[2] point <- c(1, 2) # Gradient vector gradient <- grad(f_multi, point) cat("Gradient at (1,2):", gradient, "\n") # Jacobian for vector-valued function f_vector <- function(x) c(x[1]^2 + x[2], x[1]*x[2], x[2]^2) jacobian_matrix <- jacobian(f_vector, c(1, 2)) print("Jacobian matrix:") print(jacobian_matrix) # Hessian (second derivatives) hessian_matrix <- hessian(f_multi, point) print("Hessian matrix:") print(hessian_matrix) # Using complex step method (more accurate) grad_complex <- grad(f, x0, method = "complex") cat("Gradient (complex step):", grad_complex, "\n") # Higher-order function example rosenbrock <- function(x) { 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2 } x_opt <- c(-1, 1) grad_rb <- grad(rosenbrock, x_opt) hess_rb <- hessian(rosenbrock, x_opt) cat("Rosenbrock gradient:", grad_rb, "\n") print("Rosenbrock Hessian:") print(hess_rb) ``` -------------------------------- ### Numerical Integration with cubature Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Performs adaptive multivariate integration over hypercubes using cubature methods. It requires the cubature package and can integrate scalar or vector-valued functions over specified bounds. The function returns the integral value and an error estimate. ```r library(cubature) # 1D integration: ∫₀¹ x² dx = 1/3 f_1d <- function(x) x^2 result_1d <- cubintegrate(f_1d, lower = 0, upper = 1) cat("1D integral:", result_1d$integral, "(expected: 0.333...)\n") cat("Error estimate:", result_1d$error, "\n") # 2D integration: ∫∫ exp(-(x²+y²)) over [0,1]×[0,1] f_2d <- function(x) exp(-(x[1]^2 + x[2]^2)) result_2d <- cubintegrate(f_2d, lower = c(0, 0), upper = c(1, 1)) cat("2D integral:", result_2d$integral, "\n") # 3D integration: volume of unit sphere portion f_sphere <- function(x) { if(x[1]^2 + x[2]^2 + x[3]^2 <= 1) return(1) return(0) } result_sphere <- cubintegrate(f_sphere, lower = c(0, 0, 0), upper = c(1, 1, 1), maxEval = 10000) cat("1/8 of unit sphere volume:", result_sphere$integral, "\n") cat("Full sphere volume:", 8 * result_sphere$integral, "(expected:", 4*pi/3, ")\n") # Integration with parameters f_param <- function(x, a, b) a * x[1]^2 + b * x[2]^2 result_param <- cubintegrate(f_param, lower = c(-1, -1), upper = c(1, 1), a = 2, b = 3) cat("Parametric integral:", result_param$integral, "\n") # Monte Carlo integration for comparison f_mc <- function(x) sin(x[1]) * cos(x[2]) result_det <- cubintegrate(f_mc, lower = c(0, 0), upper = c(pi, pi), method = "hcubature") cat("Deterministic result:", result_det$integral, "\n") ``` -------------------------------- ### Create Plot using Matplotlib in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt This code demonstrates plotting a sine wave using matplotlib from Python within an R environment. It generates x and y values, creates a figure, plots the sine wave, adds labels and a title, saves the plot to a file, and closes the plot. ```r plt <- import("matplotlib.pyplot") x_vals <- seq(0, 2*pi, length.out = 100) y_vals <- sin(x_vals) plt$figure(figsize = c(8, 6)) plt$plot(x_vals, y_vals, color = "blue", linewidth = 2) plt$title("Sine Wave from Python/matplotlib") plt$xlabel("x") plt$ylabel("sin(x)") plt$grid(TRUE) plt$savefig("python_plot.png") plt$close() cat("\nPlot saved to python_plot.png\n") ``` -------------------------------- ### Perform Symbolic Math using SymPy in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt This code illustrates symbolic mathematics operations using the SymPy library via R's reticulate package. It defines a symbolic variable 'x', creates an expression, and then computes its derivative, integral, and solves for the roots. ```r sympy <- import("sympy") x <- sympy$Symbol('x') expr <- x**2 + 2*x + 1 # Symbolic operations derivative <- sympy$diff(expr, x) integral <- sympy$integrate(expr, x) solved <- sympy$solve(expr, x) cat("\nSymPy symbolic operations:\n") cat("Expression:", py_to_r(sympy$latex(expr)), "\n") cat("Derivative:", py_to_r(sympy$latex(derivative)), "\n") cat("Integral:", py_to_r(sympy$latex(integral)), "\n") cat("Solutions:", unlist(solved), "\n") ``` -------------------------------- ### Special Functions using GSL Package in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Provides access to various special mathematical functions from the GNU Scientific Library (GSL), including Bessel functions (J0, J1), the hypergeometric function 2F1, the Lambert W function, the Riemann zeta function, and elliptic integrals (F, E). This snippet visualizes Bessel functions and computes specific values for others. ```r library(gsl) # Bessel functions of the first kind x <- seq(0, 10, length.out = 100) j0_values <- bessel_J0(x) j1_values <- bessel_J1(x) plot(x, j0_values, type = "l", col = "blue", ylim = c(-0.5, 1), main = "Bessel Functions", xlab = "x", ylab = "J(x)") lines(x, j1_values, col = "red") legend("topright", c("J0(x)", "J1(x)"), col = c("blue", "red"), lty = 1) # Hypergeometric function result <- hyperg_2F1(1, 2, 3, 0.5) cat("2F1(1, 2, 3; 0.5) =", result, " \n") # Lambert W function w_values <- lambert_W0(c(0, 1, 2, 5, 10)) cat("W0 values:", w_values, " \n") # Riemann zeta function zeta_2 <- zeta(2) # Should be π²/6 cat("ζ(2) =", zeta_2, " (expected:", pi^2/6, ")\n") # Elliptic integrals k <- 0.5 # modulus phi <- pi/4 elliptic_F <- ellint_F(phi, k) elliptic_E <- ellint_E(phi, k) cat("Elliptic F(π/4, 0.5) =", elliptic_F, " \n") cat("Elliptic E(π/4, 0.5) =", elliptic_E, " \n") ``` -------------------------------- ### Symbolic Computation with caracas in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Performs symbolic mathematics operations including differentiation, integration, solving equations, limits, series expansion, and matrix operations using the 'caracas' R package. It requires the 'caracas' library and defines symbolic variables. ```r library(caracas) def_sym(x, y, z) expr1 <- x^2 + 2*x + 1 expr2 <- sin(x) * cos(y) cat("Expression 1:", as.character(expr1), "\n") cat("Expression 2:", as.character(expr2), "\n") deriv1 <- der(expr1, x) deriv2 <- der(expr2, x) partial_y <- der(expr2, y) cat("\nDerivatives:\n") cat("d/dx (x² + 2x + 1) =", as.character(deriv1), "\n") cat("d/dx (sin(x)cos(y)) =", as.character(deriv2), "\n") cat("d/dy (sin(x)cos(y)) =", as.character(partial_y), "\n") integral1 <- int(x^2, x) integral2 <- int(sin(x), x) definite_int <- int(x^2, x, 0, 1) cat("\nIntegrals:\n") cat("∫ x² dx =", as.character(integral1), "\n") cat("∫ sin(x) dx =", as.character(integral2), "\n") cat("∫₀¹ x² dx =", as.character(definite_int), "\n") equation <- x^2 - 4*x + 3 solutions <- solve_sys(equation, x) cat("\nSolutions to x² - 4x + 3 = 0:\n") print(solutions) eq1 <- x + y - 3 eq2 <- x - y - 1 system_solution <- solve_sys(c(eq1, eq2), list(x, y)) cat("\nSystem solution:\n") print(system_solution) limit_result <- lim(sin(x)/x, x, 0) cat("\nlim(x→0) sin(x)/x =", as.character(limit_result), "\n") taylor <- taylor(sin(x), x, 0, n = 5) cat("Taylor series of sin(x):\n") print(taylor) A_sym <- matrix(c(x, 1, 1, x), nrow = 2) det_A <- det(as_sym(A_sym)) cat("\nDeterminant of [[x, 1], [1, x]] =", as.character(det_A), "\n") eigenvals <- eigenvals(as_sym(A_sym)) cat("Eigenvalues:\n") print(eigenvals) complex_expr <- (x + 1)^2 - (x^2 + 2*x + 1) simplified <- simplify(complex_expr) cat("\nSimplified (x+1)² - (x²+2x+1) =", as.character(simplified), "\n") ``` -------------------------------- ### Python Integration with reticulate in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt Facilitates interaction between R and Python using the 'reticulate' package. It allows importing and using Python modules like NumPy and SciPy directly within R, with automatic type conversions for data structures. This enables leveraging Python's extensive libraries for numerical and scientific computing. ```r library(reticulate) np <- import("numpy") arr <- np$array(c(1, 2, 3, 4, 5)) matrix <- np$array(matrix(1:9, nrow = 3)) cat("NumPy array:", arr, "\n") cat("NumPy matrix:\n") print(matrix) mean_val <- np$mean(arr) std_val <- np$std(arr) dot_product <- np$dot(matrix, c(1, 2, 3)) cat("\nMean:", mean_val, "\n") cat("Standard deviation:", std_val, "\n") cat("Dot product:", dot_product, "\n") scipy <- import("scipy") scipy_optimize <- import("scipy.optimize") ``` -------------------------------- ### Manipulate Data with Pandas DataFrame in R Source: https://context7.com/cran-task-views/numericalmathematics/llms.txt This snippet shows how to use the pandas library from Python within R for data manipulation. It creates a pandas DataFrame from an R data frame, displays the DataFrame, calculates summary statistics, and filters data based on a condition. ```r pd <- import("pandas") # Create pandas DataFrame from R data.frame df_r <- data.frame( name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 35), score = c(85.5, 92.3, 78.9) ) df_py <- r_to_py(df_r) cat("\nPandas DataFrame:\n") print(df_py) # Pandas operations summary <- df_py$describe() filtered <- df_py[df_py$age > 25] cat("\nSummary statistics:\n") print(summary) cat("\nFiltered (age > 25):\n") print(filtered) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.