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}
$$"


No comments: