When I was a student of Electronics & TeleComm, Maths was a very rigorous subject. Vector Calculus was a major portion of that Maths syllabus.
But at that time, i was not able to join the dots between different subjects.
I learned the how and what - but not the why.
It was like all different, disconnected knowledge bases... of no use whatsoever at that time.
But after many years in the software industry, when today I am again revisiting Engineering Maths, I am feeling an uncanny pleasure - because now my vision has become broad - and with software expertise - I can visualize what I once studied with a pen and paper.
I solved Maths problems during engineering- with one aim, of course, to do well in the examination.
But today I am learning Vector Calculus just for the joy of relearning.
I have started with the gradient of Vector Calculus and have plans to study Divergence and Curl to start with.
For this exploration, I chose Julia, a programming language particularly interesting for scientific computing and numerical simulation.
With packages such as Symbolics and GLMakie, we can combine symbolic mathematics with numerical computation and interactive visualisation.
The idea is simple:
Define a scalar mathematical function.
Calculate its symbolic gradient.
Evaluate the gradient numerically at selected points.
Calculate its magnitude and unit direction.
Visualise the vector field in three-dimensional space.
Experiment with different functions and observe the results.
Consider a simple function:
$$f(x,y,z) = x^2 + y^2 + z^2$$
Its gradient is:
$$\nabla f = 2x\hat{i} + 2y\hat{j} + 2z\hat{k}$$
At the point ((1,2,0)), the gradient becomes:
$$\nabla f(1,2,0) = 2\hat{i} + 4\hat{j} + 0\hat{k}$$
Its magnitude is:
$$|\nabla f| = \sqrt{2^2 + 4^2 + 0} = \sqrt{20}$$
Unit direction is:
[0.4472135954999579, 0.8944271909999159, 0.0]
The gradient points radially outward from the origin. With a three-dimensional visualisation, this behaviour becomes immediately apparent.
This is where the experience becomes exciting. We are no longer looking at a static diagram in a textbook. We are looking at a mathematical concept unfolding in space.
What makes this exercise particularly interesting is that the same approach can be extended to many engineering subjects.
We can revisit:
Vector calculus: gradient, divergence, and curl.
Electromagnetics: electric and magnetic fields, field lines, and wave propagation.
Circuit theory: transient response of RLC circuits and resonance.
Control systems: PID controllers and dynamic system response.
Mechanical engineering: vibration, spring-mass-damper systems, and numerical simulation.
Heat transfer: temperature distributions and heat diffusion.
These are not merely programming exercises. They are opportunities to build small virtual laboratories where mathematical models, numerical methods, and visual representations come together.
Source code...
using Symbolics
using LinearAlgebra
using GLMakie
using GeometryBasics: Point2f, Vec2f, Point3f, Vec3f
# -----------------------------------------
# 1. Symbolic variables
# -----------------------------------------
@variables x y z
variables = [x, y, z]
# -----------------------------------------
# 2. Allowed mathematical operations
# -----------------------------------------
const ALLOWED_OPERATORS = Set([
:+, :-, :*, :/, :^
])
const ALLOWED_FUNCTIONS = Dict{Symbol, Function}(
:sin => sin,
:cos => cos,
:tan => tan,
:exp => exp,
:log => log,
:sqrt => sqrt,
:abs => abs,
)
# -----------------------------------------
# 3. Safely parse mathematical expressions
# -----------------------------------------
function parse_math(ex)
# Numeric constants
if ex isa Number
return ex
end
# Variables and constants
if ex isa Symbol
if ex == :x
return x
elseif ex == :y
return y
elseif ex == :z
return z
elseif ex == :pi
return pi
else
error("Unknown variable or constant: $ex")
end
end
# Mathematical expressions
if ex isa Expr && ex.head == :call
operation = ex.args[1]
arguments = [parse_math(a) for a in ex.args[2:end]]
if operation == :+
return +(arguments...)
elseif operation == :-
return -(arguments...)
elseif operation == :*
return *(arguments...)
elseif operation == :/
return /(arguments...)
elseif operation == :^
return arguments[1]^arguments[2]
elseif operation == :sin
return sin(arguments...)
elseif operation == :cos
return cos(arguments...)
elseif operation == :tan
return tan(arguments...)
elseif operation == :exp
return exp(arguments...)
elseif operation == :log
return log(arguments...)
elseif operation == :sqrt
return sqrt(arguments...)
elseif operation == :abs
return abs(arguments...)
else
error("Unsupported operation: $operation")
end
end
error("Invalid mathematical expression")
end
# -----------------------------------------
# 4. Evaluate symbolic expression at a point
# -----------------------------------------
const NUMERIC_FUNCTION_CACHE = Dict{Any, Any}()
function evaluate_at(expr, point)
substitutions = Dict(
x => point[1],
y => point[2],
z => point[3]
)
numerical_expression = Symbolics.substitute(
expr,
substitutions
)
return Float64(Symbolics.value(numerical_expression))
end
# -----------------------------------------
# 5. Main gradient calculator
# -----------------------------------------
function calculate_gradient(expression, point)
parsed_expression = parse_math(
Meta.parse(expression)
)
# Symbolic gradient
gradient_expression = Symbolics.gradient(
parsed_expression,
variables
)
# Numerical gradient at selected point
gradient_value = [
evaluate_at(component, point)
for component in gradient_expression
]
# Scalar function value
function_value = evaluate_at(
parsed_expression, point
)
# Gradient magnitude
magnitude = norm(gradient_value)
# Unit direction
direction = magnitude > 0 ?
gradient_value / magnitude :
zeros(3)
return (
expression = parsed_expression,
gradient = gradient_expression,
function_value = function_value,
gradient_value = gradient_value,
magnitude = magnitude,
direction = direction
)
end
# -----------------------------------------
# 6. Visualize scalar and gradient fields
# -----------------------------------------
function visualize_gradient(result, point;
xrange = (-5.0, 5.0),
yrange = (-5.0, 5.0),
resolution = 35,
arrow_stride = 4)
# Create coordinate grids
xs = collect(range(xrange..., length=resolution))
ys = collect(range(yrange..., length=resolution))
# Keep z fixed at the user's evaluation coordinate
z0 = point[3]
# Calculate scalar field values
F = [
try
evaluate_at(result.expression, [xx, yy, z0])
catch
NaN
end
for xx in xs, yy in ys
]
# Prepare gradient arrows
positions = Point2f[]
directions = Vec2f[]
for i in 1:arrow_stride:resolution
for j in 1:arrow_stride:resolution
xx = xs[i]
yy = ys[j]
try
gx = evaluate_at(
result.gradient[1], [xx, yy, z0]
)
gy = evaluate_at(
result.gradient[2], [xx, yy, z0]
)
magnitude = hypot(gx, gy)
if isfinite(magnitude) && magnitude > 1e-10
push!(positions, Point2f(xx, yy))
# Normalize arrows to show direction clearly
push!(
directions,
Vec2f(gx / magnitude, gy / magnitude)
)
end
catch
continue
end
end
end
# Create visualization
fig = Figure(size = (950, 700))
ax = Axis(
fig[1, 1],
xlabel = "x",
ylabel = "y",
title = "Scalar Field and Gradient Vector Field",
aspect = DataAspect()
)
# Scalar field: filled contours
field_plot = contourf!(
ax, xs, ys, F,
levels = 25
)
Colorbar(
fig[1, 2],
field_plot,
label = "f(x, y, z)"
)
# Gradient field: arrows
arrows!(
ax,
positions,
directions,
color = :white,
arrowsize = 12,
linewidth = 2,
lengthscale = 0.4
)
# Mark the selected evaluation point
scatter!(
ax,
[Point2f(point[1], point[2])],
color = :red,
markersize = 14
)
display(fig)
return fig
end
# -----------------------------------------
# 7. 3D Gradient Vector Field Visualization
# -----------------------------------------
function visualize_gradient_3d(result, point;
limits = (-3.0, 3.0),
resolution = 7)
# Create a 3D coordinate grid
coordinates = collect(
range(limits[1], limits[2], length=resolution)
)
positions = Point3f[]
directions = Vec3f[]
scalar_values = Float64[]
# Evaluate the gradient at every grid point
for xx in coordinates
for yy in coordinates
for zz in coordinates
p = [xx, yy, zz]
try
gx = evaluate_at(result.gradient[1], p)
gy = evaluate_at(result.gradient[2], p)
gz = evaluate_at(result.gradient[3], p)
magnitude = sqrt(gx^2 + gy^2 + gz^2)
# Skip zero or invalid vectors
if !isfinite(magnitude) || magnitude < 1e-8
continue
end
fvalue = evaluate_at(result.expression, p)
if !isfinite(fvalue)
continue
end
push!(positions, Point3f(xx, yy, zz))
# Normalize the gradient vectors
push!(
directions,
Vec3f(
gx / magnitude,
gy / magnitude,
gz / magnitude
)
)
push!(scalar_values, fvalue)
catch
continue
end
end
end
end
# Create 3D figure
fig = Figure(size = (1000, 800))
ax = Axis3(
fig[1, 1],
xlabel = "X",
ylabel = "Y",
zlabel = "Z",
title = "3D Gradient Vector Field"
)
# Draw gradient arrows
arrow_plot = arrows!(
ax,
positions,
directions,
color = scalar_values,
colormap = :viridis,
colorrange = extrema(scalar_values),
lengthscale = 0.45
)
Colorbar(
fig[1, 2],
arrow_plot,
label = "Scalar field f(x,y,z)"
)
# Mark the selected evaluation point
scatter!(
ax,
[Point3f(point...)],
color = :red,
markersize = 18
)
display(fig)
return fig
end
# -----------------------------------------
# 8. Interactive application
# -----------------------------------------
function run_gradient_lab()
println("\n===================================")
println(" JULIA VECTOR CALCULUS LAB")
println(" GRADIENT CALCULATOR")
println("===================================\n")
println("Enter a function of x, y, z.")
println("Example: x^2 + y^2 + z^2")
println("Type 'exit' to quit.\n")
while true
print("Enter function f(x,y,z): ")
expression = strip(readline())
lowercase(expression) == "exit" && break
try
println("\nEnter evaluation coordinates:")
print("x = ")
px = parse(Float64, readline())
print("y = ")
py = parse(Float64, readline())
print("z = ")
pz = parse(Float64, readline())
point = [px, py, pz]
result = calculate_gradient(
expression, point
)
println("\n---------- RESULTS ----------")
println("\nScalar function:")
println("f(x,y,z) = ", result.expression)
println("\nSymbolic gradient:")
println("∇f = ", result.gradient)
println("\nEvaluation point:")
println(point)
println("\nFunction value:")
println(result.function_value)
println("\nNumerical gradient:")
println(result.gradient_value)
println("\nGradient magnitude:")
println(result.magnitude)
println("\nUnit direction:")
println(result.direction)
println("\nGenerating visualization...")
visualize_gradient(result, point)
# Uncomment the line below to display the 3D vector field:
# visualize_gradient_3d(result, point)
println("\n-----------------------------\n")
catch error_message
println("\nError: ", error_message)
println("Please enter a valid mathematical expression.\n")
end
end
println("\nThank you for using Vector Calculus Lab!")
end
# Start application
run_gradient_lab()