Piecewise Functions

Define functions with different formulas in different regions, essential for modeling discontinuous behavior, conditional logic, step functions, and threshold-based systems.

📐

Mathematical Definition

Piecewise function:

f(x)={f1(x)if C1(x) f2(x)if C2(x)  fn(x)if Cn(x) fdefaultotherwisef(x) = \begin{cases} f_1(x) & \text{if } C_1(x) \ f_2(x) & \text{if } C_2(x) \ \vdots & \ f_n(x) & \text{if } C_n(x) \ f_{\text{default}} & \text{otherwise} \end{cases}

Code Examples

Absolute Value Function

|x| = { x if x ≥ 0, -x if x < 0 }

let x = symbol!(x);

let abs_x = Expression::piecewise(
    vec![
        (expr!(x), expr!(x >= 0)),
        (expr!(-x), expr!(x < 0)),
    ],
    None,
);

Heaviside Step Function

H(x) = { 0 if x < 0, 1 if x ≥ 0 }

let x = symbol!(x);

let heaviside = Expression::piecewise(
    vec![
        (expr!(0), expr!(x < 0)),
        (expr!(1), expr!(x >= 0)),
    ],
    None,
);

Tax Bracket Example

Progressive tax with income thresholds

let income = symbol!(income);

// 10% on first $10k, 12% on next $30k, 22% on remainder
let tax = Expression::piecewise(
    vec![
        (expr!(0.10 * income), expr!(income <= 10000)),
        (expr!(1000 + 0.12 * (income - 10000)), expr!(income <= 40000)),
    ],
    Some(expr!(4600 + 0.22 * (income - 40000))),
);

// Calculate tax for $50,000
let tax_owed = tax.substitute(&income, &expr!(50000));
// Result: 4600 + 0.22 * 10000 = $6,800

Differentiation of Piecewise

Derivative computed piece-by-piece

let x = symbol!(x);

// f(x) = { x^2 if x ≥ 0, -x^2 if x < 0 }
let f = Expression::piecewise(
    vec![
        (expr!(x^2), expr!(x >= 0)),
        (expr!(-x^2), expr!(x < 0)),
    ],
    None,
);

// Derivative
let df = f.derivative(&x, 1);
// Result: { 2x if x ≥ 0, -2x if x < 0 }

🔗 Related Topics