theme = Generators.observe(notify => {const read = () => {const css =getComputedStyle(document.body);const v = (name, fallback) => (css.getPropertyValue(name).trim() || fallback);return {dark:document.body.classList.contains("quarto-dark"),fg:v("--bs-body-color","#212529"),bg:v("--bs-body-bg","#ffffff"),muted:v("--bs-secondary-color","#6c757d"),grid:v("--bs-border-color","#dee2e6"),primary:v("--bs-link-color","#0d6efd"),accent:v("--bs-danger","#dc3545"),good:v("--bs-success","#198754") }; };// Quarto swaps stylesheets when the theme changes, and the new variables apply only once// the stylesheet has loaded; read them again shortly after, and keep the last reading.let last ="";const emit = () => {const t =read();const key =JSON.stringify(t);if (key !== last) { last = key;notify(t); } };const update = () => { emit();setTimeout(emit,100);setTimeout(emit,400); };update();const observer =newMutationObserver(update); observer.observe(document.body, {attributes:true,attributeFilter: ["class"]});return () => observer.disconnect();})
plotStyle = ({// "inherit" takes the page's text color directly, so axes and labels follow a theme// switch even before the plot redraws.color:"inherit",background:"transparent",fontSize:"13px",overflow:"visible"})
themedButton = (label, counterLabel =null) => {const button =html`<button type="button" class="btn btn-sm btn-outline-primary bisc-explorer-button">${label}</button>`;// The counter shows which run is on screen, so every press visibly does something and a// reader can tell runs apart. It reads 1 at page load and after Reset.const counter = counterLabel?html`<span class="bisc-run-counter" aria-live="polite"></span>`:null;const form =html`<form class="bisc-explorer-control">${button}${counter ||""}</form>`;const show = () => { if (counter) counter.textContent=`${counterLabel}${form.value+1}`; }; form.value=0;show(); button.onclick= () => { form.value+=1; form.dispatchEvent(newEvent("input", {bubbles:true})); };// Reset sets the value back to 0 and dispatches input; refresh the counter either way. form.addEventListener("input", show);return form;}
resetButton = (controls, label ="Reset to the starting values") => {// This runs once per page, because the cell that calls it depends on the controls// themselves (viewof), not on their values; so these are the values at page load.const start = controls.map(c => c.value);const button =html`<button type="button" class="btn btn-sm btn-outline-primary bisc-explorer-button">${label}</button>`; button.onclick= () => { controls.forEach((c, k) => { c.value= start[k]; c.dispatchEvent(newEvent("input", {bubbles:true})); }); };returnhtml`<div style="margin: 0.5rem 0">${button}</div>`;}
// A small seeded generator (mulberry32), so a run can be repeated.makeRandom = (seed) => {let a = seed >>>0;return () => { a = (a +0x6D2B79F5) >>>0;let t = a; t =Math.imul(t ^ (t >>>15), t |1); t ^= t +Math.imul(t ^ (t >>>7), t |61);return ((t ^ (t >>>14)) >>>0) /4294967296; };}
This explorer solves the two one-time purchases of Chapter 7 and shows where the critical ratio puts the order on the demand distribution. The first is the last order for the mower deck belt: it costs $50, sells for $95, and scraps at $12, and demand over the fourteen remaining weeks has mean 465.37 and variance 8,582.54 belts squared. The second is the utility’s one-time buy of spare transformers: each costs $3,800 and scraps at $900, a shortage is covered by an emergency purchase at $9,500, and failures are Poisson with mean 6.
Let \(c_{u}\) represent the cost of a unit short and \(c_{o}\) the cost of a unit left over. The best quantity available for the period satisfies
\[
F(Q^{*}) = \frac{c_{u}}{c_{u} + c_{o}}
\]
and the expected cost of any \(Q\) is \((c_{u} + c_{o})G^{1}(Q) + c_{o}(Q - E[X])\), where \(G^{1}(Q)\) is the expected shortage. For a count, \(Q^{*}\) is the smallest whole number whose distribution function reaches the ratio. The page runs in your browser and records nothing. Its formulas are a restatement in JavaScript of the book’s code, and they are tested against that code. For an item of your own, use the general explorer.
{const dollars = x =>"$"+ x.toLocaleString("en-US", {minimumFractionDigits:2,maximumFractionDigits:2});const n = (x, d =2) => x.toFixed(d);const ratio =criticalRatio(costs);const notes = [];if (which ==="transformer"&& family !=="normal") notes.push("The transformer's demand is Poisson; the belt's demand model does not apply to it.");if (Q < stock) notes.push(`You cannot have fewer than the ${stock} already on hand, so the page uses ${stock}.`);const rows = [ ["Units available",n(here.level,0),n(best.level,2)], ["Order, (Q − I)⁺",n(here.order,0),n(best.order,2)], ["F(Q), the chance of leftovers",n(here.probabilityOfLeftovers,4),n(best.probabilityOfLeftovers,4)], ["Expected shortage, G¹(Q)",n(here.shortage,4),n(best.shortage,4)], ["Expected leftover",n(here.leftover,4),n(best.leftover,4)], ["Expected cost",dollars(here.expectedCost),dollars(best.expectedCost)], ["Expected profit",dollars(here.expectedProfit),dollars(best.expectedProfit)] ];returnhtml`<p>Here c<sub>u</sub> = ${dollars(underage(costs))} and c<sub>o</sub> = ${dollars(overage(costs))}, so the critical ratio is <strong>${n(ratio,4)}</strong>. ${notes.join(" ")}</p> <table class="table table-sm" style="max-width: 42rem"> <thead><tr><th>Measure</th><th>Your quantity</th><th>The optimum</th></tr></thead> <tbody>${rows.map(r =>html`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`)}</tbody> </table>`;}
The first plot is the demand distribution function. The dashed red line is the critical ratio, and the optimal quantity, the gray vertical line, is where the distribution function first reaches it. The red dot is your quantity. Notice that the ratio is the probability of having too much at the optimum.
xs = which ==="belt"? d3.range(150,801,2) : d3.range(0,16,1)Plot.plot({style: plotStyle,height:250,marginLeft:50,marginBottom:45,x: {label: which ==="belt"?"Belts":"Transformers",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"F(x)",grid:true,domain: [0,1]},marks: [ which ==="belt"&& family !=="nb"? Plot.line(xs.map(x => ({x,F: demand.cdf(x)})), {x:"x",y:"F",stroke: theme.primary,strokeWidth:1.5}): Plot.line(xs.map(x => ({x,F: demand.cdf(x)})), {x:"x",y:"F",curve:"step-after",stroke: theme.primary,strokeWidth:1.5}), Plot.ruleY([criticalRatio(costs)], {stroke: theme.accent,strokeDasharray:"5,3"}), Plot.ruleX([best.level], {stroke: theme.muted}), Plot.dot([{x: level,F: demand.cdf(level)}], {x:"x",y:"F",r:6,fill: theme.accent}) ],ariaLabel:"The demand distribution function with the critical ratio",ariaDescription:`The critical ratio is ${criticalRatio(costs).toFixed(4)} and the optimal quantity is ${best.level.toFixed(2)}.`})
The second plot is the expected cost against the quantity available. The red dot is your quantity. Notice how flat the bottom is: a few units either way cost little.
Plot.plot({style: plotStyle,height:250,marginLeft:70,marginBottom:45,x: {label: which ==="belt"?"Belts available, Q":"Transformers available, Q",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"Expected cost ($)",grid:true,domain: [0,3* best.expectedCost]},marks: [ Plot.line(xs.filter(x => x >= stock).map(x => ({x,c:evaluate(costs, demand, x, stock).expectedCost})), {x:"x",y:"c",stroke: theme.muted,strokeWidth:1.5,clip:true}), Plot.dot([{x: level,c: here.expectedCost}], {x:"x",y:"c",r:6,fill: theme.accent,clip:true}) ],ariaLabel:"Expected cost against the quantity available",ariaDescription:`The least expected cost is $${best.expectedCost.toFixed(2)} at ${best.level.toFixed(2)}. Your quantity costs $${here.expectedCost.toFixed(2)}.`})
Things to Try
Press Use the optimal quantity with the normal model. The critical ratio is \(45/83 = 0.5422\) and the order is 475.18 belts, at an expected cost of $3,050.43 and an expected profit of $17,891.01.
Set \(Q = 465\), the mean, and then \(Q = 700\). The first costs $3,068.88, 0.6% more than the optimum; the second costs $8,930.03, nearly three times as much.
Switch the belt’s demand model. The normal says 475, the lognormal 466, and the gamma and the exact negative binomial both 469, where \(F(468) = 0.5392\) falls short of the ratio and \(F(469) = 0.5434\) clears it.
Back on the normal, raise the penalty to $40. The ratio rises to \(85/123 = 0.6911\) and the order to 511.58 belts.
With no penalty, set 120 belts already on hand. The level stays at 475.18, so the order is 355.18. With 600 on hand the order is zero.
Choose the spare transformers. The ratio is \(5{,}700/8{,}600 = 0.6628\); \(F(6) = 0.6063\) falls short and \(F(7) = 0.7440\) clears it, so buy 7, at an expected cost of $7,802.36.
Check What You Found
Check what you found
1. For the belt under the normal model, a penalty of $40 for each dealer turned away raises the order from 475.18 to 511.58 belts. What moved it?
2. With 120 belts already on hand, the optimal order is 355.18 belts. With 600 on hand it is zero. Why?