Skip to main content

Featured Post

Why I Wrote The Sheet Mechanic (And Why Calculations Aren’t Enough)

For engineers who already know the math—but still lose projects. For the last few years, I’ve been sharing technical guides here on Mechanical Design Handbook —how to size a motor, how to calculate fits, and (as you recently read) how to choose between timing belts and ball screws. But after 25 years in industrial automation, I realized something uncomfortable: Projects rarely fail because the math was wrong. They fail because: The client changed the scope three times in one week. A critical vendor lied about a shipping date (and no one verified it). The installation technician couldn’t fit a wrench into the gap we designed. University taught us the physics. It didn’t teach us the reality. That gap is why I wrote my new book, The Sheet Mechanic . This is not a textbook. It is a field manual for the messy, political, and chaotic space between the CAD model and the factory floor. It captures the systems I’ve used to survive industrial projec...
NEW RELEASE: Stop trying to be a Hero. Start being a Mechanic. Get "The Sheet Mechanic" on Amazon »
Disclosure: As an Amazon Associate, I earn from qualifying purchases.

Calculate First Derivatives with Numerical Method Using Excel VBA

In the previous post, Numerical Methods - First derivative using Excel formula, we learned how to calculate the first derivative of functions using standard formulas in the spreadsheet grid.

While effective, that method can be cumbersome to set up for repeated use. In this post, let's see how we can simplify the process by creating a reusable custom function using Excel VBA (Visual Basic for Applications). Instead of downloading a pre-made file, follow the steps below to build this powerful tool yourself.

Advertisement

The VBA Code Solution

The following code implements the Five-Point Stencil method for high precision. It defines the mathematical function f(x) and a derivative function fDeriv(x).

Step 1: Open Excel and press Alt+F11 to open the VBA Editor.
Step 2: Go to Insert > Module.
Step 3: Copy and paste the code below into the module window.

' ================================================
' Created by Suparerg Suksai
' Mechanical Design Handbook
' First Derivative - Numerical Methods
' ================================================

Function f(x As Double) As Double
    ' Define your function here.
    ' Example: 5(x-3)^3 - 4x^2 - sin(2x)
    f = 5 * (x - 3) ^ 3 - 4 * x ^ 2 - Sin(2 * x)
End Function

Function fDeriv(x As Double) As Double
    Const h = 0.00001 ' Step size for numerical precision
    
    ' 5-Point Stencil Formula for First Derivative
    fDeriv = (-f(x + 2 * h) + 8 * f(x + h) - 8 * f(x - h) + f(x - 2 * h)) / (12 * h)
End Function

The section inside Function f(x) is the equation we want to differentiate. You can simply replace that line with any mathematical function you need to solve. The derivative logic remains the same.

Verification: Checking the Accuracy

To prove this works, let's verify the code against an analytical calculation.
The function used in the code above is:

f(x) = 5(x-3)3 - 4x2 - sin(2x)

Using calculus rules, the exact first derivative is:
f'(x) = 15(x-3)2 - 8x - 2cos(2x)

Let's test this at x = 7:
f'(7) = 15(7-3)2 - 8(7) - 2cos(14)
f'(7) = 15(16) - 56 - 2(0.1367)
f'(7) ≈ 183.7265

Advertisement

Using the Function in Excel

Now, go back to your spreadsheet. In any cell, simply type:
=fDeriv(7)

Screenshot of Excel VBA First Derivative Calculation Result
Figure 1: The custom function returns the highly accurate result (183.7265) directly in the cell.

The result matches our manual calculation perfectly.

This technique is a building block for more complex engineering tools. In fact, we will use this exact fDeriv function to power the Newton-Raphson Root Finding Method in our next tutorial.

Comments

Popular posts from this blog

Roberts straight-line mechanism

Figure 1: A modern linear ball slide (like this THK model) is the contemporary solution for precise straight-line motion. Many modern engineering applications require components to move in a precise linear fashion, known as " straight-line motion ". Today, we take this for granted. We can simply purchase an off-the-shelf Linear Motion Guide that moves a device accurately along a rail with low friction. The Historical Challenge: Making a Straight Line However, in the late 17th and early 18th centuries—before the development of high-precision milling machines—it was extremely difficult to manufacture long, perfectly flat surfaces. Creating a sliding joint without significant backlash was nearly impossible. During that era, engineers had to rely on Linkages . Much thought was given to the problem of attaining a straight-line motion using only revolute (hinge) connections, which were much easier to manufacture. The most famous early result was...

Dowel Pins & Locating Pins: The Basics of Fixture Design

Dowel pins are precision cylindrical pins used for accurate part alignment in assemblies. They control position, not clamping force. This guide explains tolerances, fits, sizing rules, and design best practices. Figure 1: A typical fixture setup. Notice how dowel pins (silver) provide precise location, while bolts (not shown here) provide the clamping force. In the world of Precision Engineering , the difference between a high-quality product and a scrap part often comes down to microns. While bolts hold parts together, they are terrible at positioning them. This is where Dowel Pins and Locating Pins become essential components in industrial tooling . Advertisement What is a Dowel Pin? Dowel pins are precision-ground fasteners used to secure the relative position of two parts. They are typically machined to extremely tight tolerances (often within 0.0001 inches) and are available in materials like: Hardened Steel: For high-wea...

Engineering Guide: Flexible Couplings & Universal Joint Design

Flexible couplings and universal joints explained for mechanical power transmission, covering misalignment types, angular velocity variation, and practical engineering limits. Figure 1: Flexible couplings transmit torque while accommodating axial, radial, and angular misalignment. 1. Flexible Couplings Shafts that are out of alignment ( misalignment ) either laterally or angularly can be connected using various designs of flexible couplings . These couplings also allow a limited amount of axial movement (end float) in one or both shafts, protecting bearings from excessive loads. There are several common design methodologies: Disk & Diaphragm: Transmit torque through metallic disks or flexible diaphragms. Excellent for high speed and zero backlash. Elastomeric: Flanges contain projections that engage molded rubber, urethane, or spiders. These dampen vibration and accommodate uneven motion. Link & Belt: A simpler design consisting of f...