Skip to main content
Z3’s Optimize solver goes beyond finding any solution - it finds optimal solutions by minimizing or maximizing objective functions while satisfying constraints.

Optimize vs Solver

The standard Solver finds any satisfying assignment:
The Optimize solver finds the best solution according to objectives:

Basic Optimization

1

Import and create optimizer

Optimize() creates an optimizer that supports objective functions.
2

Create variables and add constraints

These define the feasible region - solutions that satisfy all constraints.
3

Add objective function

You can use minimize() or maximize() to specify what to optimize. You can even have multiple objectives.
4

Solve and extract result

Complete Example: Linear Programming

Expected output:

Multi-Objective Optimization

You can optimize multiple objectives with priorities:
Expected output:
Objectives are handled in order. Later objectives are optimized subject to earlier ones being optimal.

MaxSMT: Soft Constraints

MaxSMT finds solutions that satisfy all hard constraints while maximizing satisfied soft constraints.
1

Add hard constraints

Hard constraints must be satisfied:
2

Add soft constraints

Soft constraints are preferences, not requirements:
Higher weights mean stronger preferences. Z3 maximizes the total weight of satisfied soft constraints.
3

Solve

Complete MaxSMT Example

Expected output:
This solution satisfies all hard constraints and maximizes soft constraint satisfaction (all three soft constraints are met).

Real-World Example: Resource Allocation

Allocate limited resources across projects to maximize total value:
Expected output:
The optimizer allocates maximum hours to the highest-value project (C) while meeting minimum requirements.

Real Numbers vs Integers

Optimization works with both integer and real variables:
Expected output:

Checking Objectives

You can query the objective value:

Common Patterns

Find the cheapest solution.
Find the most profitable configuration.
Optimize primary first, then secondary given optimal primary.
Use weights to express relative importance.

Performance Considerations

Optimization is computationally harder than satisfiability checking. For large problems:
  • Simplify constraints when possible
  • Use integer variables only when needed (Real can be faster)
  • Consider setting timeouts: opt.set('timeout', 30000) for 30 seconds

Next Steps

Basic Solving

Review fundamental constraint solving

Program Verification

Use Z3 to verify program correctness