Lesson 18 · Math Functions

Math Functions

Master VB 2026's built-in Math class — absolute value, square root, power, logarithms, rounding (Floor, Ceiling, Round, Truncate), min/max, random numbers, and practical applications in finance, physics, and data processing.

Key Takeaway: All math functions live in the System.Math class, aliased as just Math in VB 2026. Important constants: Math.PI ≈ 3.14159 and Math.E ≈ 2.71828. The four rounding functions have critically different behaviour: Math.Floor always rounds down, Math.Ceiling always rounds up, Math.Truncate always rounds toward zero, and Math.Round rounds to nearest even (banker's rounding) by default. Use Math.Round(x, digits, MidpointRounding.AwayFromZero) for the conventional "round half up" most people expect.
Math.Abs(x)
Absolute value
Abs(-7.5) = 7.5
Math.Sqrt(x)
Square root
Sqrt(144) = 12
Math.Pow(x, y)
x raised to y
Pow(2,10) = 1024
Math.Log(x)
Natural log (base e)
Log(Math.E) = 1
Math.Log10(x)
Base-10 logarithm
Log10(1000) = 3
Math.Log(x, base)
Log any base
Log(8, 2) = 3
Math.Floor(x)
Round down
Floor(4.9) = 4
Math.Ceiling(x)
Round up
Ceiling(4.1) = 5
Math.Round(x, n)
Round to n decimals
Round(3.145,2)=3.14
Math.Truncate(x)
Drop fractional part
Truncate(-4.9)=-4
Math.Max(a, b)
Larger of two values
Max(3,7) = 7
Math.Min(a, b)
Smaller of two values
Min(3,7) = 3
Math.Sign(x)
-1, 0, or 1
Sign(-5) = -1
Math.PI
Constant π
3.14159265358979
Math.E
Euler's number e
2.71828182845905

18.1 Abs, Sqrt, and Pow

AbsSqrtPow.vb — Visual Basic 2026
' Math.Abs -- absolute value (removes sign)
Dim temperature = -12.5
lblAbs.Text = $"Temperature deviation: {Math.Abs(temperature)} degrees"  ' 12.5
Dim balance = -350.0
lblBalance.Text = If(balance < 0, $"Overdrawn: RM {Math.Abs(balance):F2}", $"Balance: RM {balance:F2}")

' Math.Sqrt -- square root
Dim area = 144.0
Dim side = Math.Sqrt(area)       ' 12.0
lblSide.Text = $"Side length: {side} m"

' Hypotenuse of right triangle: c = sqrt(a^2 + b^2)
Dim a = 3.0, b = 4.0
Dim hyp = Math.Sqrt(a * a + b * b)   ' 5.0
lblHyp.Text = $"Hypotenuse: {hyp}"

' Guard: Math.Sqrt of negative is Double.NaN
Dim x = -4.0
Dim root = Math.Sqrt(x)             ' Double.NaN
If Double.IsNaN(root) Then
    lblRoot.Text = "Cannot take sqrt of negative number"
End If

' Math.Pow -- x raised to the power y
lblPow.Text = Math.Pow(2, 10).ToString()   ' 1024
lblPow.Text = Math.Pow(9, 0.5).ToString()  ' 3.0  (same as Math.Sqrt(9))
lblPow.Text = Math.Pow(2, -3).ToString()   ' 0.125  (1/8)

' VB 2026 operator ^ is equivalent to Math.Pow for most cases
Dim result = 2 ^ 10    ' 1024  (same as Math.Pow(2,10))

' Compound interest: A = P * (1 + r)^n
Dim principal = 10000.0
Dim rate       = 0.05
Dim years      = 10
Dim amount = principal * Math.Pow(1 + rate, years)   ' 16288.95
lblAmount.Text = amount.ToString("C2")

18.2 Logarithms

Logarithms are the inverse of exponentiation. VB 2026 provides three logarithm functions. Math.Log(x) computes the natural logarithm (base e), Math.Log10(x) the base-10 log, and Math.Log(x, base) any arbitrary base.

Logarithms.vb — Visual Basic 2026
' Math.Log -- natural logarithm (base e)
Math.Log(Math.E)    ' 1.0  (ln e = 1)
Math.Log(1)         ' 0.0  (ln 1 = 0)
Math.Log(100)       ' 4.60517... (ln 100)

' Math.Log10 -- common logarithm (base 10)
Math.Log10(1000)   ' 3.0  (10^3 = 1000)
Math.Log10(0.01)   ' -2.0 (10^-2 = 0.01)

' Math.Log(x, base) -- logarithm of any base
Math.Log(8, 2)     ' 3.0  (2^3 = 8)
Math.Log(81, 3)    ' 4.0  (3^4 = 81)
Math.Log(100, 10)  ' 2.0  (same as Log10(100))

' Practical: how many doublings to reach a target?
Private Function DoublingsNeeded(start As Double, target As Double) As Integer
    If start <= 0 OrElse target <= start Then Return 0
    Return CInt(Math.Ceiling(Math.Log(target / start, 2)))
End Function

' Population of 1000 doubling to 1 million:
lblDoublings.Text = DoublingsNeeded(1000, 1000000).ToString()  ' 10

' Decibel level: dB = 10 * Log10(I / I0)
Private Function Decibels(intensity As Double) As Double
    Dim I0 = 1e-12     ' reference intensity (threshold of hearing)
    Return Math.Round(10 * Math.Log10(intensity / I0), 1)
End Function

lbldB.Text = Decibels(0.001).ToString()   ' 90.0 dB (busy street)

18.3 Rounding Functions — Floor, Ceiling, Round, Truncate

These four functions all "round" a number, but in very different ways. Confusing them is one of the most common sources of subtle financial calculation bugs in VB programs.

FunctionRule3.73.2-3.7-3.23.5
Math.Floor(x)Always toward −∞33-4-43
Math.Ceiling(x)Always toward +∞44-3-34
Math.Truncate(x)Always toward zero (chop)33-3-33
Math.Round(x) defaultNearest even (banker's)43-4-34
Math.Round(x, AwayFromZero)Round half up (conventional)43-4-34
Rounding.vb — Visual Basic 2026
' Math.Floor -- always rounds DOWN toward negative infinity
Math.Floor(4.9)    ' 4    -- chops down
Math.Floor(-4.1)   ' -5   -- goes MORE negative
Math.Floor(4.0)    ' 4    -- already integer, unchanged

' Math.Ceiling -- always rounds UP toward positive infinity
Math.Ceiling(4.1)  ' 5    -- chops up
Math.Ceiling(-4.9) ' -4   -- goes LESS negative
Math.Ceiling(4.0)  ' 4    -- already integer, unchanged

' Math.Truncate -- drops the fractional part (toward zero)
Math.Truncate(4.9)  ' 4    -- same as Floor for positive
Math.Truncate(-4.9) ' -4   -- DIFFERENT from Floor for negative

' Math.Round -- banker's rounding by default (half rounds to even)
Math.Round(2.5)    ' 2    -- rounds to even (NOT 3!)
Math.Round(3.5)    ' 4    -- rounds to even
Math.Round(4.5)    ' 4    -- rounds to even (NOT 5!)

' Use AwayFromZero for conventional "round half up" behaviour
Math.Round(2.5, MidpointRounding.AwayFromZero)  ' 3  (expected!)
Math.Round(3.5, MidpointRounding.AwayFromZero)  ' 4
Math.Round(4.5, MidpointRounding.AwayFromZero)  ' 5

' Round to N decimal places
Math.Round(3.14159, 2)                                      ' 3.14
Math.Round(3.14159, 4)                                      ' 3.1416
Math.Round(3.145,   2, MidpointRounding.AwayFromZero)      ' 3.15

' Practical: price rounding for retail (always round up)
Private Function RoundUpPrice(price As Decimal) As Decimal
    Return CDec(Math.Ceiling(CDbl(price) * 100) / 100)
End Function

RoundUpPrice(9.901)   ' 9.91
RoundUpPrice(9.900)   ' 9.90
Try It — Simulation 18.1: Rounding Visualiser

Enter any decimal number and see all four rounding methods side by side. The number line shows exactly where each function lands.

Rounding Visualiser
Value x:

18.4 Min, Max, Sign, and Clamp

MinMaxSign.vb — Visual Basic 2026
' Math.Max and Math.Min
Dim a = 12, b = 7
lblMax.Text = Math.Max(a, b).ToString()   ' 12
lblMin.Text = Math.Min(a, b).ToString()   ' 7

' Clamp: keep value within [lo, hi] using Min and Max
Private Function Clamp(value As Double, lo As Double, hi As Double) As Double
    Return Math.Max(lo, Math.Min(hi, value))
End Function

Clamp(-5,  0, 100)   ' 0    (below minimum)
Clamp(42,  0, 100)   ' 42   (within range)
Clamp(150, 0, 100)   ' 100  (above maximum)

' .NET 6+ also has Math.Clamp directly:
Math.Clamp(150, 0, 100)   ' 100

' Math.Sign -- returns -1, 0, or 1
Math.Sign(-42)    ' -1
Math.Sign(0)      ' 0
Math.Sign(42)     ' 1

' Practical: determine trend direction
Dim change = currentPrice - previousPrice
Dim trend = Math.Sign(change)
Select Case trend
    Case 1  : lblTrend.Text = "Rising"
    Case -1 : lblTrend.Text = "Falling"
    Case Else: lblTrend.Text = "Unchanged"
End Select

' Chain Min/Max to find largest of four values
Dim biggest = Math.Max(Math.Max(5, 3), Math.Max(8, 1))   ' 8

18.5 Random Numbers

VB 2026 provides two ways to generate random numbers: the classic Rnd() / Randomize() approach (kept for VB6 compatibility) and the modern Random class. For new code, always use Random or Random.Shared (thread-safe singleton in .NET 6+).

Random.vb — Visual Basic 2026
' Random.Shared -- thread-safe, no instantiation needed (.NET 6+)
Dim rng = Random.Shared

' Integer in [0, max)  -- note: max is EXCLUSIVE
Dim dice  = rng.Next(1, 7)      ' 1 to 6 inclusive (max = 7 exclusive)
Dim card  = rng.Next(1, 14)     ' 1 to 13
Dim index = rng.Next(arr.Length)  ' random valid array index

' Double in [0.0, 1.0)
Dim prob = rng.NextDouble()       ' e.g. 0.734...

' Scale to a range: Double in [lo, hi)
Private Function RandomDouble(lo As Double, hi As Double) As Double
    Return lo + Random.Shared.NextDouble() * (hi - lo)
End Function

Dim temp = RandomDouble(-10, 40)   ' random temperature -10 to 40 C

' Shuffle an array (Fisher-Yates)
Private Sub Shuffle(ByRef arr() As Integer)
    For i As Integer = arr.Length - 1 To 1 Step -1
        Dim j = Random.Shared.Next(i + 1)
        Dim tmp = arr(i) : arr(i) = arr(j) : arr(j) = tmp
    Next
End Sub

' Random Boolean (coin flip)
Dim heads = Random.Shared.Next(2) = 0   ' True 50% of the time

' Seeded Random for reproducible results (testing)
Dim seeded = New Random(42)       ' same seed = same sequence every run
Dim v1 = seeded.Next(100)         ' always produces same values

' Legacy VB6 style (avoid in new code)
Randomize()                          ' seed with clock
Dim r = CInt(Int((6 * Rnd()) + 1))  ' 1 to 6
Try It — Simulation 18.2: Math Function Explorer

Choose any Math function, enter argument(s), and see the VB call, the computation, and the result. Includes Abs, Sqrt, Pow, Log, Log10, Min, Max, Sign, and Clamp.

Math Function Explorer
Function:
Argument(s):

18.6 Practical Examples

Example 18.1 — Physics Toolkit

PhysicsToolkit.vb — Visual Basic 2026
' Distance fallen under gravity: d = 0.5 * g * t^2
Private Function FreeFallDistance(t As Double) As Double
    Const g = 9.81
    Return Math.Round(0.5 * g * Math.Pow(t, 2), 3)
End Function

' Speed from kinetic energy: v = sqrt(2E/m)
Private Function VelocityFromEnergy(energy As Double, mass As Double) As Double
    If mass <= 0 Then Return 0
    Return Math.Round(Math.Sqrt(2 * energy / mass), 3)
End Function

' Richter magnitude from energy ratio: M = (2/3) * Log10(E/E0)
Private Function RichterMagnitude(energy As Double) As Double
    Const E0 = 1e4
    Return Math.Round((2.0 / 3) * Math.Log10(energy / E0), 1)
End Function

' pH from hydrogen ion concentration: pH = -Log10([H+])
Private Function CalculatePH(hConc As Double) As Double
    If hConc <= 0 Then Return 0
    Return Math.Round(-Math.Log10(hConc), 2)
End Function

Example 18.2 — Statistics Helpers

StatisticsHelpers.vb — Visual Basic 2026
' Standard deviation using Math.Sqrt and Math.Pow
Private Function StdDev(values() As Double) As Double
    If values.Length = 0 Then Return 0
    Dim mean = values.Average()
    Dim sumSqDiff = values.Sum(Function(v) Math.Pow(v - mean, 2))
    Return Math.Round(Math.Sqrt(sumSqDiff / values.Length), 4)
End Function

' Euclidean distance between two 2D points
Private Function Distance(x1 As Double, y1 As Double,
                            x2 As Double, y2 As Double) As Double
    Return Math.Round(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)), 4)
End Function

' Normalise a value to [0,1] range
Private Function Normalise(value As Double, minVal As Double, maxVal As Double) As Double
    If maxVal = minVal Then Return 0
    Return Math.Round(Math.Clamp((value - minVal) / (maxVal - minVal), 0, 1), 4)
End Function
Try It — Simulation 18.3: Random Number Tools

Three random number applications: dice roller, number generator with custom range, and coin-flip probability experiment.

Random Number Tools
Dice Roller
Number Generator
Min:
Max:
Count:
Coin Flip Experiment
Flips:
Try It — Simulation 18.4: Science Calculator

Six science formulas each powered by Math functions. See the VB code and result for free fall, kinetic energy, compound interest, decibels, Richter scale, and pH.

Science Calculator
Formula:
Try It — Simulation 18.5: Statistics Workshop

Enter a dataset and compute statistics using Math functions: mean, variance, standard deviation (Math.Sqrt + Math.Pow), range (Math.Max - Math.Min), and normalised values.

Statistics Workshop
Data values (comma-separated):

18.7 GitHub Copilot — Math Patterns

GitHub Copilot — Loan Amortisation Table
You typed: ' Generate a monthly loan amortisation table: principal, rate %, years. For each month show balance, payment, interest portion, and principal portion. Use Math.Pow and Math.Round.'
' Loan amortisation table using Math.Pow and Math.Round.
Private Sub GenerateAmortTable()
    Dim P As Decimal : If Not Decimal.TryParse(txtPrincipal.Text, P) Then Return
    Dim rPct As Double : If Not Double.TryParse(txtRate.Text, rPct)   Then Return
    Dim yrs  As Integer : If Not Integer.TryParse(txtYears.Text, yrs)  Then Return

    Dim r = rPct / 100 / 12           ' monthly rate
    Dim n = yrs * 12                   ' total payments
    Dim pmt = CDec(CDbl(P) * r * Math.Pow(1 + r, n) / (Math.Pow(1 + r, n) - 1))

    Dim balance = P
    Dim totalInterest = 0D
    dgvAmort.Rows.Clear()

    For month As Integer = 1 To n
        Dim interest  = Math.Round(balance * CDec(r), 2)
        Dim principal = Math.Round(pmt - interest, 2)
        balance       = Math.Round(balance - principal, 2)
        If month = n Then balance = 0   ' eliminate rounding residual
        totalInterest += interest
        dgvAmort.Rows.Add(month, pmt.ToString("C2"), interest.ToString("C2"),
                          principal.ToString("C2"), balance.ToString("C2"))
    Next
    lblTotal.Text = $"Total interest: {totalInterest:C2}"
End Sub
GitHub Copilot — Monte Carlo Pi Estimator
You typed: ' Use Random.Shared and Math.Pow to estimate Pi with Monte Carlo simulation. Throw N random points in a unit square and check if they fall inside the unit circle.'
' Monte Carlo Pi estimation: count random points inside unit circle.
Private Function EstimatePi(iterations As Integer) As Double
    Dim inside = 0
    For i As Integer = 1 To iterations
        Dim x = Random.Shared.NextDouble()   ' in [0, 1)
        Dim y = Random.Shared.NextDouble()
        ' Point is inside unit circle if distance from origin <= 1
        If Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)) <= 1.0 Then
            inside += 1
        End If
    Next
    ' Pi/4 = circle area / square area = inside / total
    Return 4.0 * inside / iterations
End Function

Private Sub btnEstimate_Click(sender As Object, e As EventArgs) Handles btnEstimate.Click
    Dim n = CInt(nudIterations.Value)
    Dim estimate = EstimatePi(n)
    lblPi.Text   = $"Estimate: {estimate:F6}"
    lblError.Text = $"Error vs Math.PI: {Math.Abs(estimate - Math.PI):F6}"
End Sub
Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while working with Math functions:

  • "Write a Function BodyMassIndex(weight As Double, heightM As Double) that returns BMI and a String category using Math.Round and If..ElseIf"
  • "Generate 1000 normally-distributed random numbers using Box-Muller transform with Math.Sqrt, Math.Log, and Math.Cos"
  • "Calculate the standard deviation, variance, and z-scores for a Double array using Math.Pow, Math.Sqrt, and LINQ"
  • "Build a mortgage amortisation schedule into a DataGridView using Math.Pow for the monthly payment formula"

Lesson Summary

  • All math functions are in System.Math (just Math in VB). Constants Math.PI and Math.E provide the full double-precision values of π and Euler's number.
  • Math.Abs removes the sign; Math.Sqrt(x) returns the square root (returns Double.NaN for negative x, not an exception); Math.Pow(x, y) raises x to y, equivalent to the ^ operator.
  • Math.Log(x) is the natural log (base e). Math.Log10(x) is base-10. Math.Log(x, base) computes any base. All return Double.NegativeInfinity for x=0 and Double.NaN for negative x.
  • Rounding: Math.Floor always goes down; Math.Ceiling always goes up; Math.Truncate always goes toward zero; Math.Round defaults to banker's rounding. Use MidpointRounding.AwayFromZero for conventional half-up behaviour.
  • Math.Max and Math.Min work on any numeric type. Use them in combination to clamp a value: Math.Max(lo, Math.Min(hi, value)) or Math.Clamp(value, lo, hi) (.NET 6+).
  • Use Random.Shared for random numbers in .NET 6+. .Next(min, max) generates integers where max is exclusive. .NextDouble() returns [0.0, 1.0). Use a seeded New Random(seed) for reproducible tests.

Exercises

Exercise 18.1 — Geometry Calculator

  • Write a form with radio buttons for shape: Circle, Rectangle, Triangle, Sphere
  • For each shape compute area and perimeter/volume using Math.PI, Math.Sqrt, Math.Pow
  • Circle: Area = πr², Circumference = 2πr
  • Triangle (Heron's): Area = Math.Sqrt(s*(s-a)*(s-b)*(s-c)) where s = semi-perimeter
  • Sphere: Volume = (4/3)πr³, Surface = 4πr²
  • Copilot challenge: Ask Copilot to "add an Ellipse option with area = Math.PI * a * b"

Exercise 18.2 — Financial Rounding Suite

  • Create a price calculator that applies a 6% SST to a subtotal using Math.Round(x, 2, AwayFromZero)
  • Show the difference between Floor, Ceiling, Round (default), and Round (AwayFromZero) for the same price
  • Add a currency converter that uses Math.Round to display values to 4 decimal places
  • Demonstrate why banker's rounding reduces systematic bias by summing 10 x.5 values with both rounding modes
  • Copilot challenge: Ask Copilot to "add a loan payment calculator showing total interest using Math.Pow"

Exercise 18.3 — Random Number Games

  • Build a lottery number picker: choose 6 unique numbers from 1-49 using Random.Shared
  • Add a Monte Carlo Pi estimator: throw N random points, count those inside unit circle, estimate π
  • Simulate rolling two d6 1000 times, tally each sum (2-12), and display a text histogram showing the normal distribution shape
  • Copilot challenge: Ask Copilot to "use Random.Shared.GetItems to pick lottery numbers without repeats (.NET 8+)"

Next: Lesson 19 — Trigonometric Functions

Explore Math.Sin, Math.Cos, Math.Tan, their inverses, radian-degree conversions, and practical applications in graphics, physics simulations, and wave generation.

Continue »

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

Practical Math function exercises including geometry tools, financial calculators, and physics simulations.

View on Amazon →
VB Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

48 programs making extensive use of Math functions for scientific and business calculations.

View on Amazon →