Derivative of R language implementation

Source: Internet
Author: User
Tags acos asin cos sin

Objective

Higher mathematics is a basic course for every college student to learn, and it may be the most easily forgotten knowledge after the test.
I racked my brains when I was studying high numbers, but I never knew why I was learning. Life and work are basically not used, even in the computer industry and the financial industry, can directly use the high number of places also less, academic and practical application is really far from the difference.

However, the R language opens the door to a high number of applications, and the R language not only facilitates the calculation of higher mathematics, but also makes it easy to apply the high-number formula in a paper to the practice of the product.
Because R language I re-learn the high number, so that life is full of mathematics, life will become more interesting.

This section is not a complete manual of high-count calculations, only the R language implementations of derivative calculations and partial derivative calculations are presented.

Directory

    1. Derivative calculation
    2. The derivative formula of elementary function
    3. Second derivative calculation
    4. Partial derivative calculation
1. Derivative calculation

Derivative (derivative) is the basic concept of differential calculus, used to calculate the extremum of a function. The derivative is defined as when the function y=f (x) is defined in a field of x0, and when the argument x is increased Δx at x0 (the point x0+δx is still in the neighborhood), the corresponding function obtains the increment δy=f (X0+δx)-F (x0), if Δy is the ratio of Δx when Δx tends to 0 o'clock the limit exists, The function y=f (x) can be directed at the point x0, and it is called the derivative of the function y=f (x) at the point x0, which is recorded as F ' (x0), i.e.

Also recorded as Y ' |x=x0, dy/dx|x=x0 or DF (x)/dx|x=x0.

Using the R language, the Deriv () function can be used to calculate the derivative directly, for example, to calculate the derivative of y=x^3, according to the derivative calculation formula, the deformation result for manual calculation is y ' =3x^2, when x=1, y ' = 3, when x=2, y ' = 12.

The system environment in this section

    • Win7 64bit
    • r:3.1.1 x86_64-w64-mingw32/x64 (64-bit)

Implemented with the R language Program, the code is as follows.

> dx <- deriv(y ~ x^3, "x") ; dx  # 生成导数公式expression({    .value <- x^3    .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))    .grad[, "x"] <- 3 * x^2    attr(.value, "gradient") <- .grad    .value})> mode(dx)                        # 查看dx变量类型[1] "expression"> x<-1:2                          # 给自变量x赋值> eval(dx)                        # 运行求导计算[1] 1 8                           # 原函数的计算结果attr(,"gradient")                 # 使用梯度下降法,导函数的计算结果      x[1,]  3                           # x=1,dx=3*1^2=3[2,] 12                           # x=2,dx=3*2^2=12

The results calculated using the R language Program are consistent with the results of our manual calculations. But the calculation process is actually very different, we manually calculate the formula by the given derivative, the calculation after the completion. In the calculation of computer programs, the first derivative is calculated using gradient descent method, which is an optimal approximate algorithm. For manual calculation of derivative, if the function is more complex and difficult to apply the deformable formula, then the manual calculation will be very difficult, and the computer program method is the general method of derivative calculation, will not be affected by the formula difficult to deform.

We usually use the Deriv (expr, name) function to pass 2 parameters, the first parameter expr is the original function formula, with the ~ number to separate both sides of the formula, the second parameter name is used to specify the function's arguments. The Deriv () function returns an expression type variable and then runs the expression with the Eval () function to get the result, as the above code does.

If you want to call the calculation formula as a function, you also need to pass the third parameter Func and let the Func parameter be true, as the following code implements.

Calculates the derivative of the sine function y=sin (x), which is calculated according to the derivative formula, for the manual calculation of the deformation result is y ' =cos (x), when X=pi, y ' =-1, when x=4*pi, y ' = 1, where pi=π represents Pi.

> dx <- deriv(y ~ sin(x), "x", func= TRUE) ; dx      # 生成导数公式的调用函数function (x){    .value <- sin(x)    .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))    .grad[, "x"] <- cos(x)    attr(.value, "gradient") <- .grad    .value}> mode(dx)                               # 检查dx的类型[1] "function"> dx(c(pi,4*pi))                         # 以参数作为自变量,进行函数调用[1]  1.224606e-16 -4.898425e-16attr(,"gradient")      x                                  # 导函数的计算结果[1,] -1                                  # x=pi,dx=cos(pi)=-1[2,]  1                                  # x=4*pi,dx=cos(4*pi)=1
2. Derivative formula of elementary function

For the basic elementary function derivation number, the derivative formula can be calculated directly by hand, the following is the derivative formula of elementary function.

函数          原函数            导函数常数函数      y=C               y‘=0幂函数        y=x^n             y‘=n*x^(n-1)指数函数      y=a^x             y‘=a^x*ln(a)              y=exp(1)^x        y‘=exp(1)^x对数函数      y=log(x,base=a)   y‘=1/(x*ln(a)) (a>0,且a!=1,x>0)              y=ln(x)           y‘=1/x正弦函数      y=sin(x)          y‘=cos(x)余弦函数      y=cos(x)          y‘=-sin(x)正切函数      y=tan(x)          y‘=sec(x)^2=1/cos(x)^2余切函数      y=cot(x)          y‘=-csc(x)^2=1/sin(x)^2正割函数      y=sec(x)          y‘=sec(x)*tan(x)余割函数      y=csc(x)          y‘=-csc(x)*cot(x)反正弦函数    y=arcsin(x)       y‘=1/sqrt(1-x^2)反余弦函数    y=arccos(x)       y‘=-1/sqrt(1-x^2)反正切函数    y=arctan(x)       y‘=1/(1+x^2)反余切函数    y=arccot(x)       y‘=-1/(1+x^2)反正割函数    y=arcsec(x)       y‘=1/abs(x)*(x^2-1)反余割函数    y=arccsc(x)       y‘=-1/abs(x)*(x^2-1)

Comment on the formula:

    • Y is the original function, X is the argument of the Y function, and y ' is the guide function of the Y function.
    • C,n,a is a constant.
    • ln represents the logarithm of the base of the natural constant E
    • Exp (1) denotes the natural constant E
    • Log (x,base=a) indicates a logarithm with a base of constant a
    • sqrt means open square
    • ABS denotes absolute value
    • secant function sec, calculation method is Sec=1/cos (x)
    • The residual function csc, calculated as Csc=1/sin (x)
    • cotangent function Cot, calculation method is Cot=1/tan (x)

Note: The above formula does not exactly match the R language function

Next, we calculate the first-order derivative of these unary elementary functions separately. Set Y as the original function, X is the argument of the Y function, and there is only one argument.

Constant function

Calculate the derivative of the y=3+10*x function, according to the derivative formula, for manual calculation of the deformation result is Y ' =0+10*x, the derivative of the constant term 3 is 0, when x=1, y ' = 10.

> dx<-deriv(y~ 3+10*x,"x",func = TRUE)  # 以函数形式生成导数公式> dx(1)                                 # 传入自变量,并计算[1] 13                                  # 原函数计算结果y=3+10*1=13attr(,"gradient")      x[1,] 10         # 导函数计算结果y‘=10*1=10

Power function

Calculates the derivative of the Y=X^4 function, calculates the formula according to the derivative, the deformation result for the manual calculation is y ' =4*x^3, when x=2, y ' = 32.

> dx<-deriv(y~x^4,"x",func = TRUE)> dx(2)[1] 16attr(,"gradient")      x[1,] 32         # 导函数计算结果y‘=4*x^3=4*2^3=32

exponential function

Calculates the derivative of the Y=4^x function, which is calculated according to the derivative, the deformation result for manual calculation is y ' =4^x*ln (4), when x=2, y ' = 22.18071.

> dx<-deriv(y~4^x ,"x",func = TRUE)> dx(2)[1] 16attr(,"gradient")            x[1,] 22.18071   # 导函数计算结果y‘=4^x*log(4)=4*2^3=22.18071

The derivative of the Y=exp (1) ^x function is calculated, and the deformation result for manual calculation is y ' =exp (1) ^x when x=2, y ' =y=7.389056, according to the derivative formula.

> dx<-deriv(y~exp(1)^x ,"x",func = TRUE)> dx(2)[1] 7.389056attr(,"gradient")            x[1,] 7.389056   # 导函数计算结果y‘=exp(1)^x=exp(1)^2=7.389056

Logarithmic functions

Calculates the derivative of the Y=LN (x) function, which is calculated according to the derivative, and the deformation result for manual calculation is y ' =1/x, when x=2, y ' = 0.5.

> dx<-deriv(y~log(x),"x",func = TRUE)> dx(2)[1] 0.6931472attr(,"gradient")       x[1,] 0.5   # 导函数计算结果y‘=1/x=1/2=0.5

Calculates the derivative of the Y=LOG2 (x) function, which is calculated according to the derivative, the deformation result for manual calculation is y ' =1/(X*log (2)), when x=3, y ' = 0.4808983.

But when programming with R language, we can only calculate the derivative of the logarithm based on the natural constant, for the original function is not the logarithm of the base of the natural constant, first we have to change to the logarithm of the base of the natural constant and then the derivative calculation, according to the logarithm of the bottom-changing formula, the logarithm of the base of 2 is converted to Log (x)/log (2),

> dx<-deriv(y~log(x)/log(2),"x",func = TRUE)> dx(3)[1] 1.584963attr(,"gradient")             x[1,] 0.4808983         # 导函数计算结果y‘=1/(x*log(2)=1/(3*log(2)=0.4808983

sine function

Calculates the derivative of the Y=sin (x) function, which is calculated according to the derivative formula, for the manual calculation of the deformation result is y ' =cos (x), when X=pi, y ' =-1, where pi=π represents Pi.

> dx<-deriv(y~sin(x),"x",func = TRUE)> dx(pi)[1] 1.224606e-16attr(,"gradient")      x[1,] -1   # 导函数计算结果y‘=cos(x)=cos(pi)=-1

cosine function

Calculates the derivative of the Y=cos (x) function, which is calculated according to the derivative, which is used to manually calculate the deformation result as Y ' =-sin (x), when X=pi/2, y ' =-1.

> dx<-deriv(y~cos(x),"x",func = TRUE)> dx(pi/2)[1] 6.123032e-17attr(,"gradient")      x[1,] -1  # 导函数计算结果y‘=-sin(x)=-sin(pi/2)=-1

Tangent function

Calculates the derivative of the Y=tan (x) function, which is calculated according to the derivative, the deformation result for manual calculation is y ' =sec (x) ^2=1/cos (x) ^2, when x=pi/6, y ' = 1.333333.

> dx<-deriv(y~tan(x),"x",func = TRUE)> dx(pi/6)[1] 0.5773503attr(,"gradient")            x[1,] 1.333333  # 导函数计算结果y‘=1/cos(x)^2=1/cos(pi/6)^2=1.333333

cotangent function

Calculate the derivative of the Y=cot (x) function, because the R language does not have a cot () function, so according to the triangular formula we do the original function of Y=cot (x) =1/tan (x) after the derivative calculation, according to the derivative formula, for the manual calculation of the deformation result is y ' =-CSC (x) ^2=- 1/sin (x) ^2, when X=pi/6, y ' =-4.

> dx<-deriv(y~1/tan(x),"x",func = TRUE)> dx(pi/6)[1] 1.732051attr(,"gradient")      x[1,] -4  # 导函数计算结果y‘=-1/sin(x)^2=-1/sin(pi/6)^2=-4

Inverse chord function

Calculates the derivative of the Y=asin (x) function, which is calculated according to the derivative, and the deformation result for manual calculation is y ' =1/sqrt (1-x^2), when x=pi/6, y ' = 1.173757.

> dx<-deriv(y~asin(x),"x",func = TRUE)> dx(pi/6)[1] 0.5510696attr(,"gradient")            x[1,] 1.173757  # 导函数计算结果y‘=1/sqrt(1-x^2)=1/sqrt(1-(pi/6)^2)=1.173757

Inverse cosine function

Calculates the derivative of the Y=acos (x) function, which is calculated according to the derivative formula, for the manual calculation of the deformation result of Y ' =-1/sqrt (1-x^2), when X=pi/8, y ' =-1.08735.

> dx<-deriv(y~acos(x),"x",func = TRUE)> dx(pi/8)[1] 1.167232attr(,"gradient")            x[1,] -1.08735    # 导函数计算结果y‘=-1/sqrt(1-x^2)=-1/sqrt(1-(pi/8)^2)=-1.08735

Inverse tangent function

Calculates the derivative of the Y=atan (x) function, which is calculated according to the derivative, and the deformation result for manual calculation is y ' =1/(1+x^2), when x=pi/6, y ' = 0.7848335.

> dx<-deriv(y~atan(x),"x",func = TRUE)> dx(pi/6)[1] 0.4823479attr(,"gradient")             x[1,] 0.7848335   # 导函数计算结果y‘= 1/(1+x^2) = 1/(1+(pi/6)^2)=0.7848335
3. Second derivative calculation

When we take a multiple successive derivation of a function, the number of derivatives is formed.
In general, the derivative of the function y=f (x) y ' =f ' (x) is still the function of x, we put the derivative of y ' =f ' (x) called the second derivative of the function y=f (x), which is recorded as Y ", i.e.

The derivative of the first derivative is called the second derivative, the derivative of the second derivative is called the third derivative, the derivative of the N-1 derivative is called the N-order derivative, and the derivative of the second order is customarily called the derivatives number.

For example, the second derivative derivative y "of the Y=sin (a*x) function is computed, where a is a constant, and according to the derivative formula, the deformation result for the manual calculation is the first derivative of y ' =a*cos (a*x), and the derivative formula for Y ' re-derivation is, y" =-a^2*sin (a*x)

Program implementation with R language

> a<-2                 # 设置a的值> dx<-deriv(y~sin(a*x),"x",func = TRUE) # 生成一阶导数公式> dx(pi/3)                              # 计算一阶导数[1] 0.8660254attr(,"gradient")      x[1,] -1     # 导函数计算结果y‘= a*cos(a*x)=2*cos(2*pi/3)=-1> dx<-deriv(y~a*cos(a*x),"x",func = TRUE)    # 对一阶导函数求导> dx(pi/3)[1] -1attr(,"gradient")             x[1,] -3.464102     # 导函数计算结果y‘= -a^2*sin(a*x)=-2^2*sin(2*pi/3)=-3.464102

The second derivative of the above calculation, we are hand-divided into two derivative calculation, the use of Deriv3 () function is actually combined into one-step calculation.

> dx<-deriv3(y~sin(a*x),"x",func = TRUE)  # 生成二阶导数公式> dx(pi/3)                                # 计算导数[1] 0.8660254attr(,"gradient")      x[1,] -1         # 一阶导数结果attr(,"hessian"), , x             x[1,] -3.464102  # 二阶导数结果

We calculate another second derivative, calculate y=a*x^4+b*x^3+x^2+x+c, where a,b,c is a constant a=2,b=1,c=3,
According to the derivative calculation formula, the deformation result for manual calculation is the first derivative of y ' =2*x^4+x^3+x^2+x+3=4*2*x^3+3*x^2+2*x+1, when x=2, y ' = 81,
To Y ' re-derivation formula variant for, Y "=3*4*2*x^2+2*3*x+2, when x=2, y" = 110.

> dx<-deriv3(y~a*x^4+b*x^3+x^2+x+c,"x",func=function(x,a=2,b=1,c=3){})  # 通过func参数,指定常数值> dx(2)[1] 49attr(,"gradient")      x[1,] 81           # 一阶导数结果attr(,"hessian"), , x       x[1,] 110          # 二阶导数结果

In this way, the second derivative is calculated directly, and the second derivative in the R language can be obtained directly, and it is necessary to calculate the derivative of the higher order to get the other mathematical tools.

4. Partial derivative calculation

In a unary function, we already know that the derivative is the rate of change of the function. For the two-dollar function, we should also study its "rate of change". However, because of the number of independent variables, the situation will be more complex. In mathematics, the derivative of a multivariable function is its derivative of one of the variables and keeps the other variable constant (relative to the full derivative, where all the variables are allowed to change).
The operator symbol for the partial derivative is: ∂. Remember as ∂f/∂x or F ' x. The partial derivative reflects the rate of change in the positive direction of the function along the axis, which is useful in vector analysis and differential geometry.

In the Xoy plane, when the moving point is changed by P (x0,y0) in different directions, the change in function f (x, y) is generally different, so it is necessary to study the rate of change of f (x, y) along different directions at (X0,Y0) points. Here we only learn the change rate of f (x, y) in the x0y plane along parallel to the x0y axis and two special azimuth movements parallel to the Y axis.

Bias in x direction:
There is a two-tuple function z=f (x, y), and the point (X0,Y0) is a point within its definition field d. Place y in y0 and let X have an increment x in x0, corresponding function z=f (x, y) has an increment (called the offset increment of x) z=f (x0+ x,y0)-F (x0,y0). If the z-to-X ratio is present at the x→0 limit, then this limit is called the derivative of the z=f (x, Y) to X (partial derivative) at (x0,y0). Recorded as F ' x (X0,y0).

Bias in the y direction:
The derivative of the function z=f (x, y) at x at (x0,y0) is actually the derivation of the unary function z=f (x,y0) at x0 when y is fixed to y0 as a constant. Similarly, the x is fixed to x0, let y have increment y, if the limit exists then this limit is called function z= (x, y) at (x0,y0) the partial derivative of Y. Recorded as F ' Y (x0,y0)

Similarly, we can use the Deriv () function of the R language to calculate the partial derivative. Below we calculate a two-dollar function f (x, y) =2*x^2+y+3*x*y^2 partial derivative, because each point on the two-dollar function surface has an infinite number of tangents, describing the derivative of this function is very difficult. If you let one of the variable y values be a constant, then you can find the partial derivative of another argument x, namely ∂f/∂x.

Below we respectively to the X, y two independent variable partial derivative, sets the variable y as the constant, calculates the x partial derivative ∂f/∂x=4*x+3*y^2, when X=1,y=1, X's partial derivative ∂f/∂x=4*x+3*y^2=7. Set the variable x as a constant, calculate the partial derivative of y ∂f/∂y=1+6*x*y, when x=1,y=1, the partial derivative of y ∂f/∂x=1+6*x*y=7.

Implemented with the R language program.

> fxy = expression(2*x^2+y+3*x*y^2)     # 二元函数公式> dxy = deriv(fxy, c("x", "y"), func = TRUE)> dxyfunction (x, y){    .expr4 <- 3 * x    .expr5 <- y^2    .value <- 2 * x^2 + y + .expr4 * .expr5    .grad <- array(0, c(length(.value), 2L), list(NULL, c("x","y")))    .grad[, "x"] <- 2 * (2 * x) + 3 * .expr5    .grad[, "y"] <- 1 + .expr4 * (2 * y)    attr(.value, "gradient") <- .grad    .value}> dxy(1,1)                          # 设置自变量[1] 6attr(,"gradient")     x y                            # 计算结果,x的偏导数为7,y的偏导数为7[1,] 7 7

The program calculation results of partial derivative are consistent with the results of manual calculation. We then ask for a partial derivative of the complex function, which computes a two-tuple function f (x, y) =x^y + exp (× * y) + x^2–2 * x * y + y^3 + sin (x*y) at point (1,3) and point (0,0).

R Language Program implementation.

> fxy = expression(x^y + exp(x * y) + x^2 - 2 * x * y + y^3 + sin(x*y))> dxy = deriv(fxy, c("x", "y"), func = TRUE)> dxy(1,3)        # 设置自变量[1] 43.22666attr(,"gradient")            x        y[1,] 56.28663 44.09554        # 计算结果,x的偏导数为56.28663,y的偏导数为 44.09554> dxy(0,0)[1] 2attr(,"gradient")       x    y[1,] NaN -Inf                 # 计算结果,x的偏导数无意义,y的偏导数负无穷大

For the results of the calculation, there are objections to the classmate, you can try hands-on calculation.

In this paper, we have mastered the R language for higher mathematics derivative calculation method, really is very convenient, this is more dynamic learning higher number.

Reprint please specify the source:
http://blog.fens.me/r-math-derivative/

Derivative of R language implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.