SQL Server GRAD Function
Updated 2024-03-05 17:03:47.060000
Description
Use the scalar function GRAD to numerically compute the gradient of a function
\nabla{F}\left(x,y,z\right)=\left(\frac{dF}{dx},\frac{dF}{dy},\frac{dF}{dz}\right)
using central finite difference.
Syntax
SELECT [westclintech].[wct].[GRAD] (
<@Func, nvarchar(max),>
,<@VarNames, nvarchar(4000),>
,<@X, nvarchar(4000),>
,<@H, float,>)
Arguments
@Func
The function to be evaluated, as a string. The function must be in the form of a SELECT statement.
@VarNames
The names of the variables.
@X
The starting point for the minimization.
@H
Step size.
Return Type
nvarchar(max)
Remarks
If Func returns a NULL then NULL is returned.
If Func is not a valid SELECT statement then NULL is returned.
If no solution is found then NULL is returned.
If X is NULL then @X = ''.
If H is NULL then H = 0.
Examples
Example #1
Calculate the gradient of
\frac{x^3}{y^2}\times{z^2}+\frac{12xy}{2z}
at the point (1,1,1). Since the result is returned as a string, we will use the MATRIX function to unpack the results into a vector format.
SELECT RowNum,
ItemValue
FROM wct.MATRIX(wct.GRAD('SELECT POWER(@x,3) / POWER(@y,2) * POWER(@z,2) + 12*@x*@y
/ 2*@z', '@x,@y,@z', '1,1,1', NULL));
This produces the following result.
| RowNum | ItemValue |
|---|---|
| 0 | 8.99999999801187 |
| 1 | 3.99999999899416 |
| 2 | 7.99999999828166 |
Example #2
Using the same function from the previous formula we use the FDERIV function to demonstrate the calculation of the gradient.
SELECT wct.FDERIV(
REPLACE(
REPLACE('SELECT POWER(@x,3) / POWER(@y,2) * POWER(
@z,2) + 12*@x*@y / 2*@z', '@y', 1),
'@z',
1
),
'@x',
1,
1,
NULL,
'C'
) as [dF/dx],
wct.FDERIV(
REPLACE(
REPLACE('SELECT POWER(@x,3) / POWER(@y,2) * POWER(
@z,2) + 12*@x*@y / 2*@z', '@x', 1),
'@z',
1
),
'@y',
1,
1,
NULL,
'C'
) as [dF/dy],
wct.FDERIV(
REPLACE(
REPLACE('SELECT POWER(@x,3) / POWER(@y,2) * POWER(
@z,2) + 12*@x*@y / 2*@z', '@x', 1),
'@y',
1
),
'@z',
1,
1,
NULL,
'C'
) as [dF/dz];
This produces the following result.
| dF/dx | dF/dy | dF/dz |
|---|---|---|
| 8.99999999801187 | 3.99999999899416 | 7.99999999828166 |
See Also
JACOBIAN - Numerically compute the Jacobian matrix
NEWTON - Find the root of a univariate function
SECANT - Find the root of single-variable continuous function.
BRENT - Find the root of a continuous function of on variable