Calculate Derivative of Function at a Point in R - r

Reading through this documentation in R, I don't understand how to take a derivative of the function at a specific point.
They do it here in C (with gsl_deriv_central/forward/backward), but I was wondering if there is an equivalent in R?

Just install the package numDeriv and use the grad function. Here are a few simple examples that are easy to check.
library(numDeriv)
grad(sin, 1:3)
[1] 0.5403023 -0.4161468 -0.9899925
cos(1:3)
[1] 0.5403023 -0.4161468 -0.9899925
f = function(x) x^2 + 2*x +3
grad(f, 1:3)
[1] 4 6 8
2*(1:3) + 2
[1] 4 6 8

Related

How to solve a cubic function in R

Good day to all!
I have a following cubic equation.
Left <- P^3+4*P^2+6*P
Right <- 2
How do I get R to solve for P to get Left = Right?
Thanks in advance.
1. uniroot()
You could use uniroot() to search for a root of a function with respect to its first argument.
uniroot(\(x, y) x^3 + 4*x^2 + 6*x - y, c(0, 1), y = 2, extendInt = "yes")
$root
[1] 0.278161
$f.root
[1] -1.779565e-05
$iter
[1] 6
$init.it
[1] NA
$estim.prec
[1] 6.103516e-05
2. polyroot()
If the function is a real or complex polynomial, you could specifically use polyroot(z), where z is the vector of polynomial coefficients in increasing order.
y <- 2
polyroot(c(-y, 6, 4, 1))
# [1] 0.2781631-0.000000i -2.1390815+1.616897i -2.1390815-1.616897i
Both approaches solve the equation with the root 0.278161. (Besides a real root, polyroot also gives two imaginary roots)
If you want symbolic solutions, I guess you can try Ryacas like below
> library(Ryacas)
> yac_str("Solve(P^3+4*P^2+6*P==2,P)")
[1] "{P==(71/27+Sqrt(187/27))^(1/3)-(Sqrt(187/27)-71/27)^(1/3)-4/3,P==Complex(-(4/3+((71/27+Sqrt(187/27))^(1/3)-(Sqrt(187/27)-71/27)^(1/3))/2),Sqrt(3/4)*((71/27+Sqrt(187/27))^(1/3)+(Sqrt(187/27)-71/27)^(1/3))),P==Complex(-(4/3+((71/27+Sqrt(187/27))^(1/3)-(Sqrt(187/27)-71/27)^(1/3))/2),-Sqrt(3/4)*((71/27+Sqrt(187/27))^(1/3)+(Sqrt(187/27)-71/27)^(1/3)))}"

It is possible to solve equation R that are not linear?

I want to build a function that takes E[x] and Var[X] and give me the mean and standard error of a univariate lognormal variable.
E[x] = exp(mu + theta)
Var[x] = exp(2*mu + theta)*(exp(theta) - 1)
The function would take E[x] and Var[x] as input and as output would give me theta and mu
There are several packages that provide ways and means to solve a system of nonlinear equations. One of these is nleqslv.
You nee to provide a function that function that returns the differences between the actual value of the equations and the desired value.
Load package nleqslv and define the following function
library(nleqslv)
f <- function(x,Ex,Varx) {
y<- numeric(length(x))
mu <- x[1]
theta <- x[2]
y[1] <- exp(mu+theta) - Ex
y[2] <- exp(2*mu+theta)*(exp(theta)-1) - Varx
y
}
The vector x in the function contains the values of mu and theta.
An example with Ex=2 and Varx=3 and some random starting values
xstart <- c(1,1)
nleqslv(xstart,f,Ex=2,Varx=3)
gives the following
$x
[1] -0.6931472 1.3862944
$fvec
[1] -8.095125e-11 -8.111645e-11
$termcd
[1] 1
$message
[1] "Function criterion near zero"
$scalex
[1] 1 1
$nfcnt
[1] 31
$njcnt
[1] 2
$iter
[1] 22
See the manual of nleqslv for the meaning of the different elements of the return value of nleqslv.
If you want to investigate the effect of the different solving methods try this
testnslv(xstart,f,Ex=2,Varx=3)

Finding all solutions of a non-square linear system with infinitely many solutions

In this question was found a solution to find a particular solution to a non-square linear system that has infinitely many solutions. This leads to another question:
How to find all the solutions for a non-square linear system with infinitely many solutions, with R? (see below for a possible description of the infinite set of solutions)
Example: the linear system
x+y+z=1
x-y-2z=2
is equivalent to A X = B with:
A=matrix(c(1,1,1,1,-1,-2),2,3,T)
B=matrix(c(1,2),2,1,T)
A
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 -1 -2
B
[,1]
[1,] 1
[2,] 2
We can describe the infinite set of solutions with:
x = 3/2 + (1/2) z
y = -1/2 + (-3/2) z
z in R
Thus, R could describe the set of solutions this way:
> solve2(A,B)
$principal
[1] 1 2 # this means that x and y will be described
$free
[1] 3 # this means that the 3rd variable (i.e. z) is free in the set of real numbers
$P
[1] 1.5 -0.5
$Q
[1] 0.5 -1.5
This means that every solution can be created with:
z = 236782 # any value would be ok
solve2(A,B)$P + z * solve2(A,B)$Q # this gives x and y
About the maths: there always exist such a decomposition, when the linear system has infinitely many solutions, this part is ok. The question is: is there something to do this in R?
You can solve equations like thse using the generalized inverse of A.
library(MASS)
ginv(A) %*% B
# 1.2857143
# 0.1428571
#-0.4285714
A %*% ginv(A) %*% B
# 1
# 2
So, with help from #Bhas
gen_soln <- function(vec) {
G <- ginv(A)
W <- diag(3) - G %*% A
(G %*% B + W %*% vec)
}
You can now find many solutions by providing a vector of length 3 to `gen_soln' function. For example,
one_from_inf <- gen_soln(1:3)
one_from_inf
#[1,] 1.35714286
#[2,] -0.07142857
#[3,] -0.2857142
# Test the solution.
A %*% one_from_inf
# [,1]
#[1,] 1
#[2,] 2
# Using random number generator
A %*% gen_soln(rnorm(3))
# [,1]
#[1,] 1
#[2,] 2
The general solution to
A*x = b
is
x = x0 + z
where x0 is any solution and z is in the kernel of A
As pointed out above you can find a particular solution x0 by using the generalised inverse. You can also use the SVD to find a basis for the kernel of A:
A = U*S*V'
where U and V are orthogonal and S diagonal, with, say, the last k entries on the diagonal 0 (and the others non-zero).
If follows that the last k columns of V form a basis for the kernel of A, and if we call these z1,..zk then the solutions of the original equation
are
x = x0 + c1*z1 + .. ck*zk
for any real c1..ck

Multiple roots in the complex plane with R

I've been trying to find a function that returns all complex solutions of an equation such as:
16^(1/4) = 2+i0, -2+i0, 0+i2, 0-i2
As it stands, if I enter 16^(1/4) into the console, it only returns 2. I can write a function for this but I was wondering if there is a simple way to do this in R.
You need polyroot():
polyroot(z = c(-16,0,0,0,1))
# [1] 0+2i -2-0i 0-2i 2+0i
Where z is a "vector of polynomial coefficients in increasing order".
The vector I passed to z in the example above is a compact representation of this equation:
-16x^0 + 0x^1 + 0x^2 + 0x^3 + 1x^4 = 0
x^4 - 16 = 0
x^4 = 16
x = 16^(1/4)
Edit:
If polyroot's syntax bothers you, you just could write a wrapper function that presents you with a nicer (if less versatile) interface:
nRoot <- function(x, root) {
polyroot(c(-x, rep(0, root-1), 1))
}
nRoot(16, 4)
# [1] 0+2i -2-0i 0-2i 2+0i
nRoot(16, 8)
# [1] 1.000000+1.000000i -1.000000+1.000000i -1.000000-1.000000i
# [4] 1.000000-1.000000i 0.000000+1.414214i -1.414214-0.000000i
# [7] 0.000000-1.414214i 1.414214+0.000000i

Use of constraints in R

Simple one here, i once knew this but it has been lost over the years.
Simple equation easy to code in R:
f(x,y) = 2x^2 + 4y^2 + 6x - 8y + 15
And i have constraints of x > 1 and y > -1.
I cant for the life of me remember how to write the constraints properly in R and the book i have is no use
Cheers for any help
Looking for the minimum and maximum
Define your function that takes a single vector of arguments:
myfun <- function(xy) {
x <- xy[1]
y <- xy[2]
2*x^2 + 4*y^2 + 6*x - 8*y + 15
}
Supply starting values to optim and specify your lower bounds for x and y:
starting_values <- c(0, 0)
optim(starting_values, myfun, lower=c(1, -1), method='L-BFGS-B')
optim output:
$par
[1] 1 1
$value
[1] 19
$counts
function gradient
2 2
$convergence
[1] 0
$message
[1] "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL"

Resources