Friday, December 04, 2026

Using Computer Algebra Systems as an MCP server for Gen AI

In my explorations with Julia (I am doing the Advent of Code 2026 using Julia) I discovered that there was a standard way of making an MCP server that used Julia libraries. [ModelContextProtocol.jl](https://github.com/JuliaServices/ModelContextProtocol.jl) 

What this means I can connect a Gen AI model to a CAS, and it will use the CAS to do real math, not just guess at the mathematics.

In addition, going back to my earlier explorations, there are standard instructions on creating an MCP server with [Giac.jl](https://discourse.julialang.org/t/ann-giac-jl-julia-interface-to-the-giac-computer-algebra-system/136681/9)

And with a little bit of AI help, I set up an MCP server that had a description of 

"Evaluate a symbolic or numeric math expression using Giac (e.g. 'factor(x^2 - 1)', 'integrate(sin(x), x)', 'solve(x^2 - 2 = 0, x)')"


Trial 1:  Use giac to find the solution


Firing up the MCP server inside VS Code, I gave it the following prompt:


`using giac find the critical point of the function $g⁡(饾懃,饾懄)=饾懃2+2⁢饾懃⁢饾懄−4⁢饾懄2+4⁢饾懃−6⁢饾懄+4$`


And it responded


```

Used MCP tool: giac/giac_eval


Using Giac on $g(x, y) = x^2 + 2xy - 4y^2 + 4x - 6y + 4$:


### 1. Gradient

$$g_x(x, y) = 2x + 2y + 4, \qquad g_y(x, y) = 2x - 8y - 6$$


### 2. Solve $\nabla g(x, y) = (0, 0)$

`solve([2*x + 2*y + 4 = 0, 2*x - 8*y - 6 = 0], [x, y])` → **`(-1, -1)`**


Value at the critical point:

$$g(-1, -1) = 5$$


### 3. Classification (Second Derivative Test)

`hessian(g, [x, y])` →

$$H_g(-1, -1) = \begin{pmatrix} 2 & 2 \\ 2 & -8 \end{pmatrix}, \qquad \det H_g = -20 < 0$$


Therefore, **$(-1, -1)$ is a saddle point** (with $g(-1, -1) = 5$).

```


Important note: the LLM is using the CAS to solve the problem, not trying to do this based on its training. Which means that if I gave it a math problem, it would use the CAS to derive the result and it is actually creditable.


Trial 2: Use giac to derive a solution


Let's try again, but I want it to derive the answer. Note that I don't tell it to use Giac, but the MCP server with Giac is running.


`Find the critical point of the function 饾憮⁡(饾懃,饾懄)=√(4⁢饾懄2−9⁢饾懃2+24⁢饾懄+36⁢饾懃+36)`


Response:


```

Used MCP tool: giac/giac_eval


Let $g(x, y) = 4y^2 - 9x^2 + 24y + 36x + 36$, so $f(x, y) = \sqrt{g(x, y)}$.


### 1. Compute the Partial Derivatives

$$f_x(x, y) = \frac{-18x + 36}{2\sqrt{g(x, y)}} = \frac{-9(x - 2)}{\sqrt{g(x, y)}}, \qquad f_y(x, y) = \frac{8y + 24}{2\sqrt{g(x, y)}} = \frac{4(y + 3)}{\sqrt{g(x, y)}}$$


### 2. Solve $\nabla f(x, y) = (0, 0)$

Setting the numerators equal to zero (verified with Giac):

- $-9(x - 2) = 0 \implies x = 2$

- $4(y + 3) = 0 \implies y = -3$


Check that $(2, -3)$ lies in the interior of the domain:

$$g(2, -3) = 36 > 0 \implies f(2, -3) = \sqrt{36} = 6$$


### 3. Classification (Second Derivative Test)

The Hessian at $(2, -3)$ (from Giac) is:

$$H_f(2, -3) = \begin{pmatrix} -3/2 & 0 \\ 0 & 2/3 \end{pmatrix}$$

Since $\det H_f(2, -3) = (-3/2)(2/3) - 0^2 = -1 < 0$, the interior critical point **$(2, -3)$ is a saddle point** (with $f(2, -3) = 6$).


*(Note: On the domain boundary $4(y+3)^2 - 9(x-2)^2 + 36 = 0$, $f(x, y) = 0$ is the global minimum and $\nabla f$ does not exist.)*

```


So the LLM took the derivatives then verified it with Giac (presumably if it was wrong, it would have corrected the partial derivatives).  Then presented the answers showing its work.  It also provided commentary along the way.


Trial 3.  Derive the equations for performance measures of a queueing system


Let's try something more complicated. How about a set of queueing models (because I am actually going to have to do this in the near future).



`using giac derive steady state performance measures for m/m/1 queues. Include a probability of exceeding a threshold time`


Output in the appendix after the reflection.


Reflection


1. My fellow data scientists and I have always stated axiomatically "Gen AI does not do math" based on our observing errors in reading tables, creating charts, and even mathematical operations. But this is Gen AI using a Computer Algebra System, and CAS can do math, accurately.

2. This must be what all the math people are seeing when as Gen AI models are writing these proofs. Yes, Gen AI can hallucinate, but if it driving a CAS to check its results, then it may actually be right.  And the proof verification systems can guide the structure of the proof to make sure it is complete.

3. When I was teaching supply chain to graduate students, I had an exam question that had the students take a standard supply chain model (newsvendor, EOQ) and I would add a complication and they would have to derive the new version of the equation. That was supposed to be job security, because the textbook models don't work with the complications of the real world. This makes that type of exercise incredibly easy. All you need is to know what needs to be done, and the Gen AI with CAS can do it.


-----


Teaching Note: Steady-State Analysis of the \(M/M/1\) Queue

Symbolic Derivations of Expected Times, Queue Lengths, and Waiting Times with Giac.jl

Authors

Louis Luangkesorn

Gemini 4 Neon

1 Learning Objectives

By the end of this note, you should be able to:

  1. Formulate the \(M/M/1\) queue as a continuous-time birth–death Markov chain and state its stability condition.
  2. Derive the expected interarrival time \(E[T_a]\) and expected service time \(E[S]\) from their exponential densities.
  3. Derive closed-form expressions for the expected number of customers in the system (\(L\)) and in the queue (\(L_q\)).
  4. Apply Little’s Law (and verify via PASTA and the sojourn-time distribution) to obtain the expected time in the system (\(W\)) and expected wait in the queue (\(W_q\)).
  5. Derive the probabilities of exceeding a waiting-time threshold \(t\) in the queue (\(P(W_q^{\text{rv}} > t)\)) and in the system (\(P(W^{\text{rv}} > t)\)).
  6. Verify each symbolic step using the computer algebra system Giac.jl.

2 Model Setup and Assumptions

In Kendall’s notation, an \(M/M/1\) queueing system has:

  • \(M\) (Markovian arrivals): Customers arrive according to a Poisson process with rate \(\lambda > 0\). Equivalently, interarrival times \(T_a\) are i.i.d. \(\text{Exponential}(\lambda)\) with density \[f_{T_a}(t) = \lambda e^{-\lambda t}, \qquad t \ge 0.\]
  • \(M\) (Markovian service): Service times \(S\) are i.i.d. \(\text{Exponential}(\mu)\) with service rate \(\mu > 0\) and density \[f_S(t) = \mu e^{-\mu t}, \qquad t \ge 0,\] independent of the arrival process.
  • \(1\) (Single server): One server operates under a First-Come, First-Served (FCFS) discipline with infinite waiting-room capacity.

Define the traffic intensity (server utilization) as

\[\rho = \frac{\lambda}{\mu}.\]

For a steady-state (stationary) distribution to exist, arrivals must be slower than service on average:

\[\rho < 1 \iff \lambda < \mu.\]


3 Expected Interarrival Time and Expected Service Time

For any exponential random variable \(X \sim \text{Exponential}(r)\) with rate \(r > 0\), integration by parts gives:

\[E[X] = \int_0^{\infty} t \, r e^{-r t} \, dt = \left[-t e^{-r t}\right]_0^{\infty} + \int_0^{\infty} e^{-r t} \, dt = 0 + \frac{1}{r} = \frac{1}{r}.\]

Applying this to the arrival and service processes yields:

  • Expected interarrival time: \[E[T_a] = \int_0^{\infty} t \, \lambda e^{-\lambda t} \, dt = \frac{1}{\lambda}\]
  • Expected service time: \[E[S] = \int_0^{\infty} t \, \mu e^{-\mu t} \, dt = \frac{1}{\mu}\]

Let us load our helper script and verify these integrals symbolically with Giac.jl:

include("mm1_queue.jl")

d = derive_mm1()
println("E[T_a] = ", d.E_interarrival)
println("E[S]   = ", d.E_service)
Trying integration by part
No checks were made for singular points of antiderivative lambda*(-t*exp(-lambda*t)/lambda-1/lambda^2*exp(-lambda*t)) for definite integration in [0,+infinity]
Trying integration by part
No checks were made for singular points of antiderivative mu*(-t*exp(-mu*t)/mu-1/mu^2*exp(-mu*t)) for definite integration in [0,+infinity]
Trying integration by part
No checks were made for singular points of antiderivative (mu-lambda)*(t*exp((-mu+lambda)*t)/(-mu+lambda)-1/(lambda^2-2*lambda*mu+mu^2)*exp(lambda*t-mu*t)) for definite integration in [0,+infinity]
No checks were made for singular points of antiderivative (mu-lambda)*exp((-mu+lambda)*x)/(-mu+lambda) for definite integration in [t,+infinity]
No checks were made for singular points of antiderivative (mu-lambda)*exp((-mu+lambda)*x)/(-mu+lambda) for definite integration in [t,+infinity]
No checks were made for singular points of antiderivative lambda/mu*exp((-mu+lambda)*t)/(-mu+lambda) for definite integration in [0,+infinity]
No checks were made for singular points of antiderivative exp((-mu+lambda)*t)/(-mu+lambda) for definite integration in [0,+infinity]
E[T_a] = 1/lambda
E[S]   = 1/mu

4 Steady-State Distribution \(P_n\)

Let \(N(t) \in \{0, 1, 2, \dots\}\) be the number of customers in the system (in queue plus in service) at time \(t\). Because both interarrival and service times are memoryless, \(\{N(t)\}\) is a birth–death chain with constant birth rate \(\lambda\) and constant death rate \(\mu\):

flowchart LR
    S0((0)) -->|"位"| S1((1))
    S1 -->|"渭"| S0
    S1 -->|"位"| S2((2))
    S2 -->|"渭"| S1
    S2 -->|"位"| SD["…"]
    SD -->|"渭"| S2
    SD -->|"位"| Sn((n))
    Sn -->|"渭"| SD
    Sn -->|"位"| SR["…"]
    SR -->|"渭"| Sn

Let \(P_n = \lim_{t \to \infty} \mathbb{P}(N(t) = n)\). Across the cut between states \(n\) and \(n+1\), the flow out of \(\{0,\dots,n\}\) must equal the flow into \(\{0,\dots,n\}\) (detailed balance):

\[\lambda P_n = \mu P_{n+1} \implies P_{n+1} = \frac{\lambda}{\mu} P_n = \rho P_n, \qquad n = 0, 1, 2, \dots\]

By induction,

\[P_n = \rho^n P_0.\]

Using the normalization condition \(\sum_{n=0}^{\infty} P_n = 1\) with \(0 < \rho < 1\):

\[P_0 \sum_{n=0}^{\infty} \rho^n = P_0 \cdot \frac{1}{1 - \rho} = 1 \implies P_0 = 1 - \rho.\]

Hence the steady-state number of customers in the system follows a geometric distribution on \(\{0, 1, 2, \dots\}\):

\[P_n = (1 - \rho)\rho^n, \qquad n = 0, 1, 2, \dots\]

println("sum(rho^n, n=0..∞) = ", d.geom_sum)
println("P_0                = ", d.P0)
sum(rho^n, n=0..∞) = -1/(rho-1)
P_0                = -rho+1

(Note: Giac prints \(-\frac{1}{\rho - 1}\), which is algebraically identical to \(\frac{1}{1 - \rho}\).)


5 Expected Number in the System (\(L\))

By definition, the expected number of customers in the system is

\[L = E[N] = \sum_{n=0}^{\infty} n P_n = (1 - \rho) \sum_{n=0}^{\infty} n \rho^n.\]

To evaluate \(\sum_{n=0}^{\infty} n \rho^n\) for \(|\rho| < 1\), differentiate the geometric series \(\sum_{n=0}^{\infty} \rho^n = (1 - \rho)^{-1}\) with respect to \(\rho\) and multiply by \(\rho\):

\[\sum_{n=1}^{\infty} n \rho^n = \rho \frac{d}{d\rho}\left(\frac{1}{1 - \rho}\right) = \frac{\rho}{(1 - \rho)^2}.\]

Substituting back:

\[L = (1 - \rho) \cdot \frac{\rho}{(1 - \rho)^2} = \frac{\rho}{1 - \rho}.\]

Substituting \(\rho = \lambda / \mu\):

\[L = \frac{\lambda / \mu}{1 - \lambda / \mu} = \frac{\lambda}{\mu - \lambda}.\]

println("L (in terms of rho)       = ", d.L_rho)
println("L (in terms of lambda,mu) = ", d.L_lm)
L (in terms of rho)       = -rho/(rho-1)
L (in terms of lambda,mu) = -lambda/(lambda-mu)

6 Expected Number in the Queue (\(L_q\))

When there are \(n \ge 1\) customers in the system, \(1\) customer is in service and \(n - 1\) customers are waiting in the queue (when \(n = 0\), the queue is empty). Thus:

\[L_q = E[N_q] = \sum_{n=1}^{\infty} (n - 1) P_n = (1 - \rho) \sum_{n=1}^{\infty} (n - 1) \rho^n.\]

Split the sum into two terms:

\[\begin{aligned} L_q &= \sum_{n=1}^{\infty} n P_n - \sum_{n=1}^{\infty} P_n \\ &= L - (1 - P_0) \\ &= \frac{\rho}{1 - \rho} - \rho \\ &= \frac{\rho - \rho(1 - \rho)}{1 - \rho} = \frac{\rho^2}{1 - \rho}. \end{aligned}\]

Substituting \(\rho = \lambda / \mu\):

\[L_q = \frac{(\lambda/\mu)^2}{1 - \lambda/\mu} = \frac{\lambda^2}{\mu(\mu - \lambda)}.\]

Notice also the intuitive conservation identity:

\[L - L_q = \rho,\]

which is the expected number of customers currently in service (the server is busy with probability \(1 - P_0 = \rho\)).

println("L_q (in terms of rho)       = ", d.Lq_rho)
println("L_q (in terms of lambda,mu) = ", d.Lq_lm)
println("L - L_q                     = ", d.L_minus_Lq)
L_q (in terms of rho)       = -rho^2/(rho-1)
L_q (in terms of lambda,mu) = -lambda^2/(lambda*mu-mu^2)
L - L_q                     = rho

7 Expected Wait (Sojourn Time) in the System (\(W\))

7.1 Method 1: Little’s Law

For any stable queueing system, Little’s Law relates the long-run average number of customers in the system to the arrival rate and average time in the system:

\[L = \lambda W \implies W = \frac{L}{\lambda} = \frac{1}{\lambda} \cdot \frac{\lambda}{\mu - \lambda} = \frac{1}{\mu - \lambda}.\]

7.2 Method 2: PASTA and Memorylessness (Intuitive Check)

Because arrivals follow a Poisson process, PASTA (Poisson Arrivals See Time Averages) ensures that an arriving customer observes the steady-state distribution \(P_n\), and therefore finds \(L\) customers ahead of them on average. By the memoryless property of the exponential service time, the customer currently in service has remaining service time with mean \(1/\mu\), and each waiting customer (as well as the arriving customer themselves) also requires mean service time \(1/\mu\). Hence:

\[W = \frac{L + 1}{\mu} = \frac{\frac{\lambda}{\mu - \lambda} + 1}{\mu} = \frac{1}{\mu - \lambda}.\]

In fact, one can show that the total time in the system \(T_{\text{sys}}\) is itself \(\text{Exponential}(\mu - \lambda)\) with PDF \(f_W(t) = (\mu - \lambda)e^{-(\mu - \lambda)t}\), whose mean is directly \(\frac{1}{\mu - \lambda}\).

println("W (Little's Law) = ", d.W_lm)
println("W (PASTA check)  = ", d.W_pasta)
println("W (sojourn PDF)  = ", d.W_sojourn_pdf)
W (Little's Law) = -1/(lambda-mu)
W (PASTA check)  = -1/(lambda-mu)
W (sojourn PDF)  = -1/(lambda-mu)

8 Expected Wait in the Queue (\(W_q\))

The total time a customer spends in the system equals their waiting time in the queue plus their service time:

\[W = W_q + E[S] = W_q + \frac{1}{\mu}.\]

Solving for \(W_q\):

\[W_q = W - \frac{1}{\mu} = \frac{1}{\mu - \lambda} - \frac{1}{\mu} = \frac{\mu - (\mu - \lambda)}{\mu(\mu - \lambda)} = \frac{\lambda}{\mu(\mu - \lambda)} = \frac{\rho}{\mu - \lambda}.\]

Equivalently, by Little’s Law applied to the queue (\(L_q = \lambda W_q\)):

\[W_q = \frac{L_q}{\lambda} = \frac{1}{\lambda} \cdot \frac{\lambda^2}{\mu(\mu - \lambda)} = \frac{\lambda}{\mu(\mu - \lambda)}.\]

println("W_q (Little's Law) = ", d.Wq_lm)
println("Check W - W_q      = ", d.W_minus_Wq)
W_q (Little's Law) = -lambda/(lambda*mu-mu^2)
Check W - W_q      = 1/mu

9 Probability of Waiting Over a Threshold Time \(t\)

Beyond averages, service-level targets often ask for the probability that a customer’s wait exceeds a threshold \(t \ge 0\).

9.1 Queue Waiting Time Exceeding \(t\): \(P(W_q^{\text{rv}} > t)\)

By PASTA, an arriving customer finds \(N = 0\) with probability \(P_0 = 1 - \rho\) (no queue wait, \(W_q^{\text{rv}} = 0\)) and finds \(N = k \ge 1\) with probability \(P_k = (1 - \rho)\rho^k\). Conditioned on waiting (\(N \ge 1\), probability \(1 - P_0 = \rho\)), the customer sees \(k \ge 1\) customers ahead with probability \((1 - \rho)\rho^{k-1}\) and must wait for \(k\) exponential(\(\mu\)) service completions (\(\text{Erlang}(k, \mu)\)):

\[\begin{aligned} f_{W_q \mid W_q > 0}(x) &= \sum_{k=1}^{\infty} (1 - \rho)\rho^{k-1} \frac{\mu^k x^{k-1} e^{-\mu x}}{(k - 1)!} \\ &= (1 - \rho)\mu e^{-\mu x} \sum_{j=0}^{\infty} \frac{(\rho \mu x)^j}{j!} \\ &= (1 - \rho)\mu e^{-\mu(1 - \rho)x} = (\mu - \lambda)e^{-(\mu - \lambda)x}, \qquad x > 0. \end{aligned}\]

Integrating from \(t\) to \(+\infty\) and multiplying by \(P(W_q^{\text{rv}} > 0) = \rho\):

\[P(W_q^{\text{rv}} > t) = \rho \, e^{-(\mu - \lambda)t} = \rho \, e^{-\mu(1 - \rho)t}, \qquad t \ge 0.\]

9.2 Total System Time Exceeding \(t\): \(P(W^{\text{rv}} > t)\)

Because the total sojourn time \(W^{\text{rv}} = W_q^{\text{rv}} + S\) is \(\text{Exponential}(\mu - \lambda)\) with density \(f_W(x) = (\mu - \lambda)e^{-(\mu - \lambda)x}\), its tail probability is:

\[P(W^{\text{rv}} > t) = \int_t^{\infty} (\mu - \lambda)e^{-(\mu - \lambda)x}\,dx = e^{-(\mu - \lambda)t} = e^{-\mu(1 - \rho)t}, \qquad t \ge 0.\]

println("f_{W_q|wait}(x) = ", d.f_Wq_cond)
println("P(W_q > t)      = ", d.P_Wq_gt_t)
println("P(W > t)        = ", d.P_W_gt_t)
println("∫P(W_q > t) dt  = ", d.check_Wq_tail)
println("∫P(W > t) dt    = ", d.check_W_tail)
f_{W_q|wait}(x) = -lambda*exp(-mu*x)*exp(lambda*x)+mu*exp(-mu*x)*exp(lambda*x)
P(W_q > t)      = lambda/mu*exp(lambda*t-mu*t)
P(W > t)        = exp(lambda*t-mu*t)
∫P(W_q > t) dt  = -lambda/(lambda*mu-mu^2)
∫P(W > t) dt    = -1/(lambda-mu)

10 Summary of \(M/M/1\) Formulas (\(\rho = \lambda / \mu < 1\))

Quantity Symbol In terms of \(\rho\) and \(\mu\) In terms of \(\lambda\) and \(\mu\)
Server utilization \(\rho\) \(\rho\) \(\dfrac{\lambda}{\mu}\)
Probability system is empty \(P_0\) \(1 - \rho\) \(1 - \dfrac{\lambda}{\mu}\)
Expected interarrival time \(E[T_a]\) \(\dfrac{1}{\rho \mu}\) \(\dfrac{1}{\lambda}\)
Expected service time \(E[S]\) \(\dfrac{1}{\mu}\) \(\dfrac{1}{\mu}\)
Expected number in system \(L\) \(\dfrac{\rho}{1 - \rho}\) \(\dfrac{\lambda}{\mu - \lambda}\)
Expected number in queue \(L_q\) \(\dfrac{\rho^2}{1 - \rho}\) \(\dfrac{\lambda^2}{\mu(\mu - \lambda)}\)
Expected wait in system \(W\) \(\dfrac{1}{\mu(1 - \rho)}\) \(\dfrac{1}{\mu - \lambda}\)
Expected wait in queue \(W_q\) \(\dfrac{\rho}{\mu(1 - \rho)}\) \(\dfrac{\lambda}{\mu(\mu - \lambda)}\)
Queue wait threshold (\(t \ge 0\)) \(P(W_q^{\text{rv}} > t)\) \(\rho\,e^{-\mu(1 - \rho)t}\) \(\dfrac{\lambda}{\mu}e^{-(\mu - \lambda)t}\)
System time threshold (\(t \ge 0\)) \(P(W^{\text{rv}} > t)\) \(e^{-\mu(1 - \rho)t}\) \(e^{-(\mu - \lambda)t}\)

11 Worked Numerical Example

Suppose a single-server help desk receives calls according to a Poisson process at rate \(\lambda = 4\) calls/hour, and call durations are exponentially distributed with service rate \(\mu = 5\) calls/hour. Suppose also we want the probability a caller waits more than \(t = 30\) minutes (\(0.5\) hours).

m = mm1_metrics(4, 5; t = 0.5)
r(x) = round(x; digits = 4)

println("Utilization (rho):                ", r(m.rho), " (80%)")
println("Idle probability (P_0):           ", r(m.P0), " (20%)")
println("Expected interarrival time E[T]:  ", r(m.E_interarrival), " hr (", r(m.E_interarrival * 60), " min)")
println("Expected service time E[S]:       ", r(m.E_service), " hr (", r(m.E_service * 60), " min)")
println("Expected number in system (L):    ", r(m.L), " customers")
println("Expected number in queue (L_q):   ", r(m.Lq), " customers")
println("Expected time in system (W):      ", r(m.W), " hr (", r(m.W * 60), " min)")
println("Expected wait in queue (W_q):     ", r(m.Wq), " hr (", r(m.Wq * 60), " min)")
println("P(W_q > 30 min):                  ", r(m.prob_wait_gt_t), " (", round(100 * m.prob_wait_gt_t; digits = 1), "%)")
println("P(W   > 30 min):                  ", r(m.prob_sys_gt_t), " (", round(100 * m.prob_sys_gt_t; digits = 1), "%)")
Utilization (rho):                0.8 (80%)
Idle probability (P_0):           0.2 (20%)
Expected interarrival time E[T]:  0.25 hr (15.0 min)
Expected service time E[S]:       0.2 hr (12.0 min)
Expected number in system (L):    4.0 customers
Expected number in queue (L_q):   3.2 customers
Expected time in system (W):      1.0 hr (60.0 min)
Expected wait in queue (W_q):     0.8 hr (48.0 min)
P(W_q > 30 min):                  0.4852 (48.5%)
P(W   > 30 min):                  0.6065 (60.7%)

Interpretation: Even though the server is idle \(20\%\) of the time (\(P_0 = 0.20\)), the high utilization (\(\rho = 0.80\)) combined with exponential variability causes an average of \(L_q = 3.2\) callers waiting in line and an average queue wait of \(W_q = 48\) minutes — four times the \(12\)-minute average service time. Moreover, \(48.5\%\) of callers wait longer than \(30\) minutes in the queue (\(P(W_q^{\text{rv}} > 0.5) = 0.8 e^{-0.5} \approx 0.4852\)), and \(60.7\%\) spend more than \(30\) minutes total in the system (\(P(W^{\text{rv}} > 0.5) = e^{-0.5} \approx 0.6065\)).


Sunday, November 29, 2026

Using LLM and CAS and Julia to derive the newsvendor model

I took a few hours to play with LLMs. The goals for this particular explorations was to use LLM to use various Julia CAS on an operations research problem:

1. Use LLM with Julia. Large Language Models (LLM) tend to be better when used with mainstream languages, in part because of the rich training data available on Github (i.e. both source code and commit messages). I had previously tried LLM with Clojure, and the thin training data in the form of limited documentation that did not keep up with the library development was evident in the results.

2. Use with Computer Algebra Systems (CAS).  It is well established that we don't use LLM for computation, instead we use LLM to write numerical code then run the numerical code. Now, I want to see the LLM do actual math, through using CAS.

3. See where it trips up. Because that is what I (and my partners on projects involving LLMs) do.

## Setup


I am using Visual Studio Code within Windows Subsystem for Linux (WSL). I use Antigravity (Gemini) as an extension so it considers my open files and workspace as part of the context.  For this exploration, I used Gemini 4 Neon (Medium). 


## Symbolic Math in Julia


I set up 5 CAS in Julia.  Note: I am hardly a specialists in CAS/Computational symbolic math, so take all opinions with a hefty grain of salt.


1. Sympy.jl   This calls out to the SymPy CAS, which runs in Python, through the Julia PyCall. SymPy is a pure Python CAS.  SymPy is probably described as wide and shallow. Covers lots of topics, but not at a deep level.  Probably equivalent to an undergrad in math. While it does not necessarily have depth, the shear number of developers and the ease of access through Python has given it a level of quality for general use.

2. Symj.jl  This is being developed by the same person who maintains Sympy.jl. The goal is to create a Julia equivalent of SimPy that did not have to call out to Python. It heavily uses Anthropic Claude in the development and is trained on the SymPy issue tracker, i.e. it knows of every problem SymPy ran into and the path that eventually resolved it (or what pathways have failed)

3. Giac.jl   This is the Julia interface to the Giac CAS written in C++. Giac is also the CAS behind XCAS, Geogebra, HP Prime CAS, and some TI calculators with CAS.  Also include PARI/GP.

4. Symbolics.jl  This is a pure Julia CAS and what you get if you work through JuliaSymbolics.  The developers like to claim that they are the One True CAS for Julia, but in the world of CAS, there is no such thing, as everyone has specialties.

5. OSCAR (Open Source Computer Algebra System).  This is a combination of several CAS, each with their own specialties (sort of like SageMath, but less universal).  It includes AbstractAlgebra.jl, Nemo (includes FLINT, Arb, and ANTIC), Hecke, Singular, GAP, and Polymake.  Most of these libraries are originally written in C++, but OSCAR makes them behave like Julia libraries (take and return Julia objects that can be further manipulated.  As a combination of several C++ libraries, this takes by far the longest to install and to use.


I had Gemini do the setup with the following prompts:


```

Set up a Julia 1.13 workspace in /home/louis/learning/julia/juliamath:

add Symbolics.jl Oscar.jl giac.jl SymJ.jl Sympy.jl packages

```

Gemini than verified that the packages were compiled and installed and also gave me hints on working with several CAS

```

Pkg.precompile() completed cleanly across all dependencies.

Verified import Symbolics, Oscar, Giac, SymJ, SymPy in the workspace environment — all five load cleanly.

Tip: Since these CAS packages export overlapping names (such as simplify, diff, expand, solve), prefer import Symbolics, Oscar, Giac, SymJ, SymPy when using more than one in the same session. (Note: Oscar/Polymake prints a benign WSL warning about wslview if you use Polymake's visual viewer.)

```

## Explorations

For each of these five CAS, I had Gemini create Pluto notebooks that followed examples in the Sympy documentation. This is somewhat cheating, as the examples were all thing that Sympy could do so it did not address strengths of the other CAS. But it was a good start.

```

for each of the five CAS, create a Jupyter notebook corresponding to each of the following tutorials: 

https://docs.sympy.org/latest/tutorials/intro-tutorial/intro.html 

https://docs.sympy.org/latest/tutorials/intro-tutorial/simplification.html 

https://docs.sympy.org/latest/tutorials/intro-tutorial/calculus.html 

https://docs.sympy.org/latest/tutorials/intro-tutorial/solvers.html 

https://docs.sympy.org/latest/tutorials/intro-tutorial/matrices.html 

https://docs.sympy.org/latest/tutorials/physics/mechanics/duffing-example.html 

https://docs.sympy.org/latest/tutorials/physics/mechanics/rollingdisc_example.html 

https://docs.sympy.org/latest/tutorials/physics/mechanics/bicycle_example.html 

https://docs.sympy.org/latest/tutorials/physics/continuum_mechanics/beam_problems.html 

https://docs.sympy.org/latest/tutorials/physics/control/control_problems.html

```

OSCAR was clearly the heaviest resource intensive one for this.  Many times I touched OSCAR it ended up crashing my WSL.  SymJ also got stuck, although Gemini got this working with extra attention.

Next I generated Jupyter Notebooks for all of these, because I got tired of bouncing between VS Code and the browser to inspect everything.

The different CAS did have some differences in their approaches.

CASFolderNotebooks (all verified exit 0)Notes
SymPy.jlsrc/sympy01_intro.jl – 10_control_problems.jl (10)Direct Julia port including sympy.physics.mechanics, continuum_mechanics.beam, and physics.control.
Symbolics.jlsrc/symbolics01_intro.jl – 10_control_problems.jl (10)Native Differential(t) Euler–Lagrange, 3D kinematics, Carvallo–Whipple eigenvalues, Macaulay beam solver (SymBeam), and symbolic transfer functions (SymTF).
Giac.jlsrc/giac01_intro.jl – 10_control_problems.jl (10)Native Giac.Commands & GiacMatrix derivations, laplace/ilaplace, desolve, Macaulay beam solver (GiacBeam), and MIMO/multi-loop control reduction.
Oscar.jlsrc/oscar01_intro.jl – 10_control_problems.jl (10)Ring-theoretic formulation over QQ, QQBar, polynomial rings, fraction fields Frac(QQ[s]), power series QQ[[t]], Groebner bases, exact algebraic mechanics modulo s^2 + c^2 - 1, and certified bicycle eigenvalues.
SymJ.jlsrc/symj01_intro.jl – 10_control_problems.jl (10)Pure-Julia SymJ derivations using diff, limit, series, solve/solveset/dsolve, LinearAlgebra on Matrix{Sym}, laplace_transform/inverse_laplace_transform, and native Macaulay beam & control helpers.

Some spot checking of the code identified a few errors.  In giac it tried to use the `to_giac()` function in a context where `to_giac()` was not defined for that combination of argument types.  in Sympy it used an `end=` argument for various functions, but because `end` is a keyword in Julia, Sympy.jl cannot use it.  Once prompted with the error, Gemini was able to create corrections for these across all of the files.

## Extending Symbolics.jl


Along the theme that there is no One CAS to Rule Them All, Symbolics.jl can potentially use additional extensions.  

```

are there any notebooks in symbolics that could be redone with Nemo or Maxima

how about with SymbolicIntegrationMaxima

```

Gemini identified several notebooks where Symbolics.jl could be more direct by using Nemo.jl or the Symbolic integration capabilities of Maxima, as Nemo and Maxima have algebraic and calculus capabilities that Symbolics.jl lacks.

So, I had Gemini create a version of the Symbolics.jl notebooks that used Neon or Maxima as appropriate.

Pluto .jlJupyter .ipynb (executed)Extensions Used & Key Upgrades
01_intro_ext.jl01_intro_ext.ipynbNemo (factor_use_nemo, symbolic_solve for roots & exact eigenvalues) + SymbolicIntegrationMaxima (integrate(exp(x)*sin(x)+exp(x)*cos(x), x, M), integrate(sin(x^2), x, -Inf, Inf, M)).
02_simplification_ext.jl02_simplification_ext.ipynbNemo (factor_use_nemo for univariate/multivariate polynomial factoring and automatic denominator factoring in apart_nemo) + SymbolicIntegrationMaxima (maxima_simplify).
03_calculus_maxima.jl03_calculus_maxima.ipynbSymbolicIntegrationMaxima (integrate for indefinite, definite, improper, parametric with assumptions=(a > 0,), plus maxima_numeric to 30 digits) + SymbolicLimits (rational & one-sided limits).
04_solvers_nemo.jl04_solvers_nemo.ipynb(Previously created) Nemo + Groebner for univariate, periodic, multiplicity, linear, and nonlinear symbolic_solve.
05_matrices_nemo.jl05_matrices_nemo.ipynbNemo (factor_use_nemo on charpoly + symbolic_solve(cp ~ 0, 位; dropmultiplicity = false) for exact eigenvalues, multiplicities, and M=PDP−1M = P D P^{-1}M=PDP−1 diagonalization).
—12_newsvendor_model_maxima.ipynbSymbolicIntegrationMaxima + Latexify: directly integrates ∫−∞z蠒(u) du\int_{-\infty}^{z}\phi(u)\,du∫−∞z​蠒(u)du, ∫−∞zu蠒(u) du\int_{-\infty}^{z} u\phi(u)\,du∫−∞z​u蠒(u)du, and ∫z∞蠒(u) du\int_{z}^{\infty}\phi(u)\,du∫z∞​蠒(u)du via MaximaMethod(), assembles E[螤(Q)]\mathbb{E}[\Pi(Q)]E[螤(Q)] & ddQE[螤(Q)]\frac{d}{dQ}\mathbb{E}[\Pi(Q)]dQd​E[螤(Q)] symbolically, renders all outputs in text/latex, and cross-checks against maxima_numeric (rtol < 1e-10).

Where the initial versions had (to me strange) workarounds based on the capabilities of Symbolics.jl, the new versions were more direct solutions.


##  Adding Maxima.jl


There is also a Maxima.jl package that calls to Maxima directly.  I have already installed Maxima (a Common Lisp based CAS that is also used in SageMath) so I had Gemini install this as well.  During installation it identified a problem (as Maxima.jl is not actively maintained)


```

Maxima.jl v0.1.2 (the latest version in Julia General and on nsmith5/Maxima.jl master, last updated years ago) deadlocks inside using Maxima (__init__()) against your installed Maxima 5.49.0:

```

Gemini recommended a patch and made that work.  Then went ahead and created Maxima versions of all of the SymPy examples and the newsvendor example. 

#Pluto .jlJupyter .ipynb (executed)Highlights
0101_intro.jl01_intro.ipynbsqrt(8), expand, factor, diff, integrate, limit, solve, ode2, eigenvalues, tex1
0202_simplification.jl02_simplification.ipynbratsimp, factor, partfrac, trigsimp/trigexpand/trigreduce, radcan, logcontract, continued fractions
0303_calculus.jl03_calculus.ipynbMixed partials, indefinite/improper/2D Gaussian integrate, bfloat, one-sided limit, taylor, finite-difference weights
0404_solvers.jl04_solvers.ipynbsolve, multiplicities, find_root (Lambert WWW), linsolve, algsys, ode2
0505_matrices.jl05_matrices.ipynbinvert, determinant, echelon, nullspace, columnspace, charpoly, eigenvalues, eigenvectors, exponentialize
0606_duffing_example.jl06_duffing_example.ipynbEuler–Lagrange equations for Duffing oscillator + pendulum, zero residual vs. SymPy, symbolic acceleration solve
0707_rollingdisc_example.jl07_rollingdisc_example.ipynb3D lean-frame Kane’s method & contact constraint forces, verified zero residual
0808_bicycle_example.jl08_bicycle_example.ipynbCarvallo–Whipple benchmark A(v)\mathbf{A}(v)A(v), charpoly, allroots, confirming self-stability at v=5 m/sv = 5\text{ m/s}v=5 m/s
0909_beam_problems.jl09_beam_problems.ipynbMacaulay equilibrium for cantilever (Ex. 1: R1=−52,M1=158R_1 = -52, M_1 = 158R1​=−52,M1​=158) & symbolic fixed–fixed beam (Ex. 7: −Fl3/(192EI)-Fl^3/(192 EI)−Fl3/(192EI))
1010_control_problems.jl10_control_problems.ipynbNative ilt impulse/step responses, MIMO feedback (I + P.C)^(-1).P, multi-loop block diagram reduction
11—11_elliptic_curve.ipynbSymbolic tangent slope via diff and exact modular inverse via inv_mod on E:y2≡x3+2x+2(mod17)E : y^2 \equiv x^3 + 2x + 2 \pmod{17}E:y2≡x3+2x+2(mod17) (order 19)
12—12_newsvendor_model.ipynbDirect symbolic integrate of Normal demand branches, find_root, direct definite integral cross-check (rtol < 1e-8), sensitivity table, and full tex1 → text/latex rendered outputs

This also had lots of commentary because Maxima is quite different. Gemini had to go several rounds on several of these examples, and this also shows issues with working with a very old CAS and not well maintained interface. It also had trouble rendering the output (probably a result of issues with the interface library).


## Initial thoughts

These were interesting overview of basic commands.  Looking at the simplification, calculus, and solver (algebra) documentation provided some instruction on use.  The physics examples (duffing, rolling disc, bicycle, beam, and control systems) were different across the CAS, but not being a physicist I could not tell what the impact of those differences were.  So next I'll try something I actually know, because I am working on a tutorial to use AI to create an AI Skill on it. The Newsvendor problem.

## Newsvendor

The Newsvendor problem is a single period inventory ordering problem where there is a known demand distribution, and you decide what to order based on ordering costs, revenue per unit sale, and salvage costs for what you don't sell.  When I taught supply chain for graduate students, I would include an exam question where I would have the students derive an extension on the newsvendor problem (or another similarly basic model). This tended to be a memorable experience for the MS students. And the PhD students could tell their advisors that this class was not a waste of time.

Goal for this exercise was to create a workbook that would walk a student through the newsvendor problem, then an example.

The biggest surprise with the Newsvendor problem was that a couple of the CAS did not use algebraic solutions. Sympy, SimJ, and Giac all did algebraic solutions which I could follow because that is how I would have done it.  Symbolic and OSCAR did series expansions. (Symbolics used a derivative expansion while OSCAR used exact power series expansion).  All of the CAS did end up with the same results.

Note: I attach the Giac output as that is the most generally accessible as Giac can be used standalone; within Xcas, Qcas, and TeXEmacs; and from Python, Java (JNI), or Javascript.

## Overall thoughts

1. LLM is much better with a non-mainstream language.  There are still signs, especially with interfaces to more mainstream languages, it will make errors (e.g. when the Julia call to a C++ or Python library requires adjusting how the function is called).  Note that it helps that Julia libraries are pretty well documented, however the C++ and Python libraries documentation and examples can be found in orders of magnitude more volume.

2. It was fascinating watching Gemini try to use each CAS idiomatically, especially the little notes for each of my OSCAR files that explain that OSCAR has a different set of capabilities that the LLM will apply. I'm guessing it is because they are well documented (especially the ones that are built on established codes like Giac, Sympy, and the libraries in OSCAR)

3. Yes, LLM still makes mistakes.  When the mistakes are pointed out (error messages), it figures things out.


Note: if you are going to try this with Python, you can use the SymPy and giacpy libraries.  You can also use SageMath as a Kernel in VS Code Jupyter Notebook, but I somewhat remember installing SageMath is a bit of a commitment.


For R, you can use the caracas package (which is really SymPy). There is an interface to YACAS, but that may not be as solid as these other libraries.



# Appendix: The Newsvendor Model with Normal Demand (Giac.jl Tutorial)

Gemini (Antigravity) prompt

using symj write a tutorial that explains and derives the standard newsvendor model with normal demand distribution.  Create and solve an example. Do this in a jupyter notebook.
repeat the newsvendory model for giac symbolics oscar and sympy

This Jupyter notebook provides a complete, step-by-step symbolic derivation and worked numerical example of the standard Newsvendor (single-period inventory) model with Normal demand using Giac.jl with full LaTeX rendering of all generated symbolic expressions.

What You Will Learn

  1. Problem formulation: unit economics, underage cost $c_u$, overage cost $c_o$, and the piecewise profit function $\Pi(Q, D)$.
  2. General derivation via Leibniz’s integral rule: deriving the first-order optimality condition, the Critical Fractile $F(Q^*) = \frac{c_u}{c_u + c_o}$, and proving global concavity.
  3. Normal demand specialization: verifying $\Phi’(z) = \phi(z)$ and $(-\phi(z))’ = z\phi(z)$ symbolically in Giac, deriving $Q^* = \mu + z^\sigma$, and deriving $\mathbb{E}[\Pi(Q^)] = (p - c)\mu - (p - s)\sigma\phi(z^*)$.
  4. Worked numerical example: solving the artisan bakery problem with Giac’s fsolve and cross-checking against Giac’s symbolic/numeric integrate.
begin
    import Pkg
    Pkg.activate(joinpath(isempty(@__DIR__) ? pwd() : @__DIR__, "..", ".."))
end
begin
    using Giac
    using Giac.Commands: diff, integrate, simplify, expand, factor, normal, solve, fsolve, evalf, erf, latex
    using Latexify

    as_giac(v::GiacExpr) = v
    as_giac(v) = giac_eval(string(v))
    to_f64(v::GiacExpr) = parse(Float64, string(evalf(v, 16)))

    function render_eqs(pairs::Pair...)
        rows = String[]
        for (lhs, rhs) in pairs
            rhs_tex = rhs isa GiacExpr ? strip(string(latex(rhs)), ['"', '$']) : string(rhs)
            push!(rows, "$(lhs) &= $(rhs_tex)")
        end
        return Latexify.LaTeXStrings.LaTeXString("\$\$\n\\begin{aligned}\n" * join(rows, " \\\\\n") * "\n\\end{aligned}\n\$\$")
    end
end
render_eqs (generic function with 1 method)

1. Problem Formulation & Unit Economics

For retail price $p$, purchase cost $c$, salvage value $s$ ($s < c < p$), order quantity $Q$, and realized demand $D = x$:

begin
    @giac_var Q x p c s mu sigma z

    c_u = p - c
    c_o = c - s

    Pi_low = expand(p * x + s * (Q - x) - c * Q)
    Pi_high = expand((p - c) * Q)

    boundary_jump = simplify(substitute(Pi_low, x => Q) - substitute(Pi_high, x => Q))
    @assert string(boundary_jump) == "0"

    dPi_low_dQ = diff(Pi_low, Q)
    dPi_high_dQ = diff(Pi_high, Q)

    render_eqs(
        "c_u" => c_u,
        "c_o" => c_o,
        "\\Pi_1(Q, x)" => Pi_low,
        "\\Pi_2(Q, x)" => Pi_high,
        "\\Pi_1(Q, Q) - \\Pi_2(Q, Q)" => boundary_jump,
        "\\frac{\\partial \\Pi_1}{\\partial Q}" => dPi_low_dQ,
        "\\frac{\\partial \\Pi_2}{\\partial Q}" => dPi_high_dQ,
    )
end
L"$$
\begin{aligned}
c_u &= p-c \\
c_o &= c-s \\
\Pi_1(Q, x) &= -Q c+Q s+p x-s x \\
\Pi_2(Q, x) &= -Q c+Q p \\
\Pi_1(Q, Q) - \Pi_2(Q, Q) &= 0 \\
\frac{\partial \Pi_1}{\partial Q} &= -c+s \\
\frac{\partial \Pi_2}{\partial Q} &= -c+p
\end{aligned}
$$"

2. General Derivation: Leibniz’s Rule & the Critical Fractile

Solving $\frac{d}{dQ}\mathbb{E}[\Pi(Q)] = -c_o F(Q) + c_u (1 - F(Q)) = 0$ gives the Critical Fractile $F(Q^*) = \frac{p - c}{p - s}$ and second derivative $-(p - s)f(Q) < 0$.

let
    @giac_var F_Q f_Q

    dE_dQ = expand(dPi_low_dQ * F_Q + dPi_high_dQ * (1 - F_Q))
    sol_list = solve(dE_dQ, F_Q)
    crit_fractile = normal(giac_eval("(" * string(sol_list) * ")[0]"))
    @assert string(normal(crit_fractile - c_u / (c_u + c_o))) == "0"

    # Second derivative by chain rule: d/dQ [dE_dQ(F(Q))] = (d/dF_Q dE_dQ) * f(Q)
    d2E_dQ2 = factor(diff(dE_dQ, F_Q) * f_Q)

    render_eqs(
        "\\frac{d}{dQ}\\mathbb{E}[\\Pi(Q)]" => dE_dQ,
        "F(Q^*)" => crit_fractile,
        "\\frac{d^2}{dQ^2}\\mathbb{E}[\\Pi(Q)]" => d2E_dQ2,
    )
end
L"$$
\begin{aligned}
\frac{d}{dQ}\mathbb{E}[\Pi(Q)] &= -F_{Q} p+F_{Q} s-c+p \\
F(Q^*) &= \frac{-c+p}{p-s} \\
\frac{d^2}{dQ^2}\mathbb{E}[\Pi(Q)] &= -f_{Q} \left(p-s\right)
\end{aligned}
$$"

3. Specialization to Normal Demand $D \sim \mathcal{N}(\mu, \sigma^2)$

Using Giac’s erf, exp, sqrt, and pi, we verify $\Phi’(z) = \phi(z)$, $(-\phi(z))’ = z\phi(z)$, and the closed-form expected profit $\mathbb{E}[\Pi(\mu + z\sigma)]$.

begin
    g_pi = giac_eval("pi")
    phi(u) = exp(-u^2 / 2) / sqrt(2 * g_pi)
    Phi(u) = (1 + erf(u / sqrt(as_giac(2)))) / 2

    check_cdf = simplify(diff(Phi(z), z) - phi(z))
    check_first_moment = simplify(diff(-phi(z), z) - z * phi(z))
    @assert string(check_cdf) == "0" && string(check_first_moment) == "0"

    E_Pi_z = (p - c) * mu - (p - s) * sigma * phi(z) + ((p - c) - (p - s) * Phi(z)) * sigma * z
    dE_dz = simplify(diff(E_Pi_z, z))
    expected_dE_dz = sigma * ((p - c) - (p - s) * Phi(z))
    @assert string(simplify(expand(dE_dz - expected_dE_dz))) == "0"

    E_Pi_star_formula = (p - c) * mu - (p - s) * sigma * phi(z)

    render_eqs(
        "\\phi(z)" => phi(z),
        "\\Phi(z)" => Phi(z),
        "\\Phi'(z) - \\phi(z)" => check_cdf,
        "(-\\phi(z))' - z\\phi(z)" => check_first_moment,
        "\\mathbb{E}[\\Pi(\\mu + z\\sigma)]" => E_Pi_z,
        "\\frac{d}{dz}\\mathbb{E}[\\Pi(\\mu + z\\sigma)]" => dE_dz,
        "\\mathbb{E}[\\Pi(Q^*)]" => E_Pi_star_formula,
    )
end
"\$\$\n\\begin{aligned}\n\\phi(z) &= \\frac{\\mathrm{e}^{-\\frac{z^{2}}{2}}
}{\\sqrt{2 \\pi }} \\\\\n\\Phi(z) &= \\frac{1+\\mathrm{erf}\\left(\\frac{z}
{\\sqrt{2}}\\right)}{2} \\\\\n\\Phi'(z) - \\phi(z) &= 0 \\\\\n(-\\phi(z))' 
- z\\phi(z) &= 0 \\\\\n\\mathbb{E}[\\Pi(\\mu + z\\sigma)] &= \\left(p-c\\ri
ght) \\mu-\\frac{\\l" ⋯ 251 bytes ⋯ "\\sigma \\mathrm{erf}\\left(\\frac{1}{
2} z \\sqrt{2}\\right)+p \\sigma+s \\sigma \\mathrm{erf}\\left(\\frac{1}{2}
 z \\sqrt{2}\\right)+s \\sigma}{2} \\\\\n\\mathbb{E}[\\Pi(Q^*)] &= \\left(p
-c\\right) \\mu-\\frac{\\left(p-s\\right) \\sigma \\mathrm{e}^{-\\frac{z^{2
}}{2}}}{\\sqrt{2 \\pi }}\n\\end{aligned}\n\$\$"

4. Worked Numerical Example: Artisan Bakery

$p = $12$, $c = $5$, $s = $2$, $D \sim \mathcal{N}(100, 20^2)$. Solve $\Phi(z^) = 7/10$ using Giac’s fsolve and cross-check $\mathbb{E}[\Pi(Q^)]$ against direct integration via Giac’s integrate.

begin
    sub_params(ex) = substitute(ex, Dict(p => 12, c => 5, s => 2, mu => 100, sigma => 20))

    cu_val = sub_params(c_u)
    co_val = sub_params(c_o)
    CR_exact = normal(cu_val / (cu_val + co_val))

    z_star = to_f64(giac_eval("normal_icdf(7/10)"))
    Q_star = 100.0 + z_star * 20.0

    E_Pi_closed = to_f64(substitute(sub_params(E_Pi_star_formula), z => as_giac(z_star)))

    f_normal_x = sub_params(phi((x - mu) / sigma) / sigma)
    Pi_low_num = substitute(sub_params(Pi_low), Q => as_giac(Q_star))
    Pi_high_num = substitute(sub_params(Pi_high), Q => as_giac(Q_star))

    E_Pi_quad = to_f64(integrate(Pi_low_num * f_normal_x, x, as_giac(-60), as_giac(Q_star))) +
                to_f64(integrate(Pi_high_num * f_normal_x, x, as_giac(Q_star), as_giac(260)))

    @assert isapprox(E_Pi_closed, E_Pi_quad; rtol=1e-7)

    E_Pi_mean = to_f64(substitute(sub_params(E_Pi_z), z => as_giac(0)))
    det_profit = to_f64(sub_params((p - c) * mu))

    println("Underage cost c_u = \$", cu_val, ", Overage cost c_o = \$", co_val)
    println("Critical Fractile CR = ", CR_exact, " (", to_f64(CR_exact), ")")
    println("Optimal z*           = ", round(z_star; digits=6))
    println("Optimal Order Q*     = ", round(Q_star; digits=2), " loaves")
    println("Deterministic profit = \$", round(det_profit; digits=2))
    println("E[Pi(Q*)] (closed)   = \$", round(E_Pi_closed; digits=4))
    println("E[Pi(Q*)] (quad)     = \$", round(E_Pi_quad; digits=4))
    println("E[Pi(mu=100)]        = \$", round(E_Pi_mean; digits=4))
    println("Gain over ordering 渭 = \$", round(E_Pi_closed - E_Pi_mean; digits=4))

    render_eqs(
        "c_u" => cu_val,
        "c_o" => co_val,
        "\\text{CR}" => CR_exact,
        "f_D(x)" => f_normal_x,
        "z^*" => round(z_star; digits=6),
        "Q^*" => round(Q_star; digits=2),
        "\\mathbb{E}[\\Pi(Q^*)]_{\\text{closed}}" => round(E_Pi_closed; digits=4),
        "\\mathbb{E}[\\Pi(Q^*)]_{\\text{quad}}" => round(E_Pi_quad; digits=4),
        "\\mathbb{E}[\\Pi(\\mu)]" => round(E_Pi_mean; digits=4),
    )
end
Underage cost c_u = $7, Overage cost c_o = $3
Critical Fractile CR = 7/10 (0.7)
Optimal z*           = 0.524401
Optimal Order Q*     = 110.49 loaves
Deterministic profit = $700.0
E[Pi(Q*)] (closed)   = $630.4615
E[Pi(Q*)] (quad)     = $630.4615
E[Pi(mu=100)]        = $620.2115
Gain over ordering 渭 = $10.2499
L"$$
\begin{aligned}
c_u &= 7 \\
c_o &= 3 \\
\text{CR} &= \frac{7}{10} \\
f_D(x) &= \frac{\mathrm{e}^{-\frac{\left(\frac{x-100}{20}\right)^{2}}{2}}}{
\sqrt{2 \pi }\cdot 20} \\
z^* &= 0.524401 \\
Q^* &= 110.49 \\
\mathbb{E}[\Pi(Q^*)]_{\text{closed}} &= 630.4615 \\
\mathbb{E}[\Pi(Q^*)]_{\text{quad}} &= 630.4615 \\
\mathbb{E}[\Pi(\mu)] &= 620.2115
\end{aligned}
$$"

5. Sensitivity Analysis: Profit Across Order Quantities $Q$

let
    E_Pi_of_z = sub_params(E_Pi_z)
    Q_grid = [70.0, 80.0, 90.0, 100.0, Q_star, 120.0, 130.0, 140.0]

    println("  Order Q   |   z = (Q-渭)/蟽  |  Service Level 桅(z) |  Expected Profit E[螤(Q)]")
    println("------------|----------------|---------------------|-------------------------")
    profits = Float64[]
    for qv in Q_grid
        zv = (qv - 100.0) / 20.0
        sl = to_f64(substitute(Phi(z), z => as_giac(zv)))
        ep = to_f64(substitute(E_Pi_of_z, z => as_giac(zv)))
        push!(profits, ep)
        marker = isapprox(qv, Q_star; atol=1e-6) ? "  <-- OPTIMUM" : ""
        println(
            lpad(string(round(qv; digits=2)), 10), "  |  ",
            lpad(string(round(zv; digits=3)), 12), "  |  ",
            lpad(string(round(100 * sl; digits=2)) * "%", 17), "  |  \$",
            lpad(string(round(ep; digits=2)), 8), marker
        )
    end

    @assert argmax(profits) == 5
    render_eqs("\\mathbb{E}[\\Pi(100 + 20z)]" => simplify(E_Pi_of_z))
end
Order Q   |   z = (Q-渭)/蟽  |  Service Level 桅(z) |  Expected Profit E[螤(Q
)]
------------|----------------|---------------------|-----------------------
--
      70.0  |          -1.5  |              6.68%  |  $  484.14
      80.0  |          -1.0  |             15.87%  |  $  543.34
      90.0  |          -0.5  |             30.85%  |  $  590.44
     100.0  |           0.0  |              50.0%  |  $  620.21
    110.49  |         0.524  |              70.0%  |  $  630.46  <-- OPTIMU
M
     120.0  |           1.0  |             84.13%  |  $  623.34
     130.0  |           1.5  |             93.32%  |  $  604.14
     140.0  |           2.0  |             97.72%  |  $   578.3
L"$$
\begin{aligned}
\mathbb{E}[\Pi(100 + 20z)] &= \frac{-100 z \sqrt{\pi } \mathrm{erf}\left(\f
rac{1}{2} z \sqrt{2}\right) \mathrm{e}^{\frac{z^{2}}{2}}+40 z \sqrt{\pi } \
mathrm{e}^{\frac{z^{2}}{2}}-100 \sqrt{2}+700 \sqrt{\pi } \mathrm{e}^{\frac{
z^{2}}{2}}}{\sqrt{\pi } \mathrm{e}^{\frac{z^{2}}{2}}}
\end{aligned}
$$"