Differentiate a Measure

The measure has to be differentiable (smooth and continuous).

Differentiating a function of the form sin(x)

Differentiating a function of the form sin(x) * x^3

Differentiating an equation of the form y = x^3

When differentiating the equation of the form y = x^3, note how the third derivative is not exact. This is something to be aware of in numerical analysis. Power BI’s default y axis range selection emphasises imprecision. Setting the y axis range to 5 to 7 shows how the imprecision is actually quite small.

DAX

The DAX for dy/dx is given below. In place of [y], substitute the name of the measure you want to differentiate.

If you want to take the second derivative of [y], first create a measure [dy/dx] and then use it as the “[y]” in a new measure [d2y/dx2]. If you are calculating a 2nd or higher order derivative you need to change the value of k – it should equal your order of differentiation.

dy/dx = 
/*
    The task is to differentiate measure [y] with respect to x.
    - Assume consecutive points on the x axis are equidistant.
    - Assume [y] is differentiable (smooth and continuous).

    Let 
    - the current point be (xn, yn).
    - the point to its left be (xl, yl).
    - the point to its right be (xr, yr).

    The rate of change at (xn,yn) will be calculated as:
        dy/dx = ( yr - yl ) / ( xr - xl )

    At the edges of x's domain either xl or xr won't exist.
    At the edges, blank will be returned for dy/dx.
*/

//Order of derivative
VAR k = 1

/*
    You may be taking the derivative of a derivative.
    That's to say [y] may already be a derivative.
    You need k points either side of a point to take its kth derivative.
    Near the edge of x's domain you won't have k points either side.
    So,
    - Find the domain of x
    - Check if you're near the edge.
    If you're near the edge you will end up returning blank for the derivative.
*/

//Find the domain of x.
VAR xDomain = ALL( Data[x] )

VAR NearEdgeOfDomain = 
    IF( 
        COUNTROWS( WINDOW(-k,REL,+k,xDomain) ) - 1 < 2 * k, 
        true,
        false
    )

//Find (xl, yl) and (xr, yr)
VAR xl = 
    CALCULATE( SELECTEDVALUE(Data[x]), OFFSET(-1,xDomain) )
var xr = 
    CALCULATE( SELECTEDVALUE(Data[x]), OFFSET(+1,xDomain) )
VAR yl = 
    CALCULATE( [y], OFFSET(-1,xDomain) )
VAR yr = 
    CALCULATE( [y], OFFSET(+1,xDomain) )

VAR dydx = 
    IF(
        NearEdgeOfDomain,
        BLANK(),
        DIVIDE(
            yr - yl, 
            xr - xl
        )
    )

RETURN dydx

References

Introducing DAX window functions (part 1) by Jeffrey Wang

Leave a comment