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 page solves the newsvendor problem of Chapter 7 for an item you describe: the quantity to have available for one period, what it is expected to leave over and fall short by, and what it is expected to cost and earn. It starts from the belt’s final buy under the normal model; Reset returns to it. 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.
What This Page Assumes
One period, one decision. A single order is placed before demand is seen, unsold units are salvaged at the end, and unmet demand is lost.
The costs. A selling price \(s\), a unit cost \(c\), a salvage value \(v\), and an optional penalty \(\pi\) per unit short beyond the lost margin, so that \(c_{u} = s - c + \pi\) and \(c_{o} = c - v\). Both must be positive; when one is not, the page says what the model’s answer would be and why it signals a mis-stated problem.
The demand. A Poisson, negative binomial, normal, gamma or lognormal distribution, given by its mean and variance (the Poisson by its mean alone), or built from a per-period mean and variance over several independent periods, whose means and variances add. A negative binomial needs a variance above its mean. The discrete families are limited to a mean of 50,000 units.
Stock on hand. Units already held count toward the level, and the order is the level less the stock on hand, never negative.
NoteFor anything else, use the software
Fitting a distribution to a demand history, estimating the answer by simulation, several items sharing a budget or a shelf, and salvage rules no formula takes are in the code the chapter teaches, in Using the Software, and the chapter’s workbook fits and solves the same model sheet by sheet.
Your Item
viewof price = Inputs.number({value:95,label:"Selling price, s ($)"})viewof cost = Inputs.number({value:50,label:"Unit cost, c ($)"})viewof salvage = Inputs.number({value:12,label:"Salvage value, v ($)"})viewof penalty = Inputs.number({value:0,label:"Penalty per unit short, π ($)"})viewof family = Inputs.select(newMap([["Normal","normal"], ["Gamma","gamma"], ["Lognormal","lognormal"], ["Poisson","poisson"], ["Negative binomial","nb"]]), {value:"normal",label:"Demand family"})viewof how = Inputs.select(newMap([["Its mean and variance","direct"], ["Per period, over several periods","periods"]]), {value:"periods",label:"Demand given as"})viewof mean = Inputs.number({value:33.2404,label:"Mean"})viewof variance = Inputs.number({value:613.0387,label:"Variance"})viewof periods = Inputs.number({value:14,label:"Number of periods"})viewof onHand = Inputs.number({value:0,label:"Already on hand, I"})viewof Q = Inputs.number({value:465,label:"Units available, Q"})useOptimum = {const button =html`<button type="button" class="btn btn-sm btn-outline-primary bisc-explorer-button">Use the optimal quantity</button>`; button.onclick= () => {if (!result.ok) return; viewof Q.value=+result.best.level.toFixed(2); viewof Q.dispatchEvent(newEvent("input", {bubbles:true})); };returnhtml`<div style="margin: 0.5rem 0">${button}</div>`;}resetButton([viewof price, viewof cost, viewof salvage, viewof penalty, viewof family, viewof how, viewof mean, viewof variance, viewof periods, viewof onHand, viewof Q])
import {normal, lognormal, gamma} from"./explorers/lib/continuous.js"import {poisson, negativeBinomial} from"./explorers/lib/loss.js"import {discrete, solve, evaluate, criticalRatio, underage, overage, refusal} from"./explorers/lib/newsvendor.js"fmt = x =>String(Number(x.toPrecision(6)))result = {const problems = [];const costs = {price, cost, salvage, penalty};for (const [v, name] of [[price,"selling price"], [cost,"unit cost"], [salvage,"salvage value"], [penalty,"penalty"]]) {if (!Number.isFinite(v) || v <0) problems.push(`The ${name} must be a number, 0 or more.`); }const n = how ==="periods"? periods :1;if (how ==="periods"&&!(Number.isInteger(periods) && periods >=1)) problems.push("The number of periods must be a whole number, 1 or more.");const m = mean * n, v = (family ==="poisson"? mean : variance) * n;if (!(m >0)) problems.push("The mean demand must be positive.");if (family !=="poisson"&&!(v >0)) problems.push("The variance must be positive.");if (family ==="nb"&&!(v > m)) problems.push("A negative binomial needs a variance above its mean; for a variance equal to the mean, choose the Poisson.");if ((family ==="poisson"|| family ==="nb") && m >50000) problems.push("The discrete families are limited to a mean of 50,000 units.");if (!(onHand >=0)) problems.push("The stock on hand cannot be negative.");if (!(Q >=0)) problems.push("The quantity available cannot be negative.");if (problems.length) return {ok:false, problems};const refused =refusal(costs);if (refused) return {ok:false,problems: [refused]};try {const demand = family ==="poisson"?discrete(poisson(m)) : family ==="nb"?discrete(negativeBinomial(m, v)): ({normal, gamma, lognormal})[family](m, v);const level =Math.max(demand.discrete?Math.round(Q) : Q, onHand);return {ok:true, costs, demand, m, v, n, level,best:solve(costs, demand, onHand),here:evaluate(costs, demand, level, onHand)}; } catch (e) {return {ok:false,problems: [e.message.charAt(0).toUpperCase() + e.message.slice(1) +"."]}; }}
{if (!result.ok) {returnhtml`<div class="callout callout-style-simple callout-warning"><div class="callout-body"> <p><strong>The page cannot solve this item.</strong></p> <ul>${result.problems.map(p =>html`<li>${p}</li>`)}</ul></div></div>`; }const {costs, demand, m, v, n, here, best} = result;const dollars = x =>"$"+ x.toLocaleString("en-US", {minimumFractionDigits:2,maximumFractionDigits:2});const d = (x, k =2) => x.toFixed(k);const notes = [];if (n >1) notes.push(`Over ${n} independent periods the mean is ${fmt(mean)} × ${n} = ${fmt(m)} and the variance is ${fmt(family ==="poisson"? mean : variance)} × ${n} = ${fmt(v)}.`);else notes.push(`The demand has mean ${fmt(m)}${family ==="poisson"?"":` and variance ${fmt(v)}`}.`);if (family ==="normal") notes.push(`A normal with this mean and variance puts ${(100* demand.cdf(0)).toPrecision(2)}% of its probability below zero.`);if (demand.discrete&&Math.round(Q) !== Q) notes.push("Demand is a count, so your quantity is rounded to a whole number.");const rows = [ ["Units available",d(here.level, demand.discrete?0:2),d(best.level, demand.discrete?0:2)], ["Order, (Q − I)⁺",d(here.order, demand.discrete?0:2),d(best.order, demand.discrete?0:2)], ["F(Q), the chance of leftovers",d(here.probabilityOfLeftovers,4),d(best.probabilityOfLeftovers,4)], ["Expected shortage",d(here.shortage,4),d(best.shortage,4)], ["Expected leftover",d(here.leftover,4),d(best.leftover,4)], ["Expected cost",dollars(here.expectedCost),dollars(best.expectedCost)], ["Expected profit",dollars(here.expectedProfit),dollars(best.expectedProfit)] ];returnhtml`<p>${notes.join(" ")} Here c<sub>u</sub> = ${dollars(underage(costs))} and c<sub>o</sub> =${dollars(overage(costs))}, so the critical ratio is <strong>${d(criticalRatio(costs),4)}</strong>.</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, with the critical ratio as a dashed red line and the optimal quantity, the gray vertical line, where the function first reaches it. The red dot is your quantity.
xs = {if (!result.ok) return [];const {demand, m, v} = result, s =Math.sqrt(v);const lo =Math.max(0,Math.floor(Math.min(m -4* s, result.level-1))), hi =Math.ceil(Math.max(m +4* s, result.level+1,3));const step = demand.discrete?Math.max(1,Math.ceil((hi - lo) /400)) : (hi - lo) /400;return d3.range(lo, hi + step /2, step);}result.ok? Plot.plot({style: plotStyle,height:250,marginLeft:50,marginBottom:45,x: {label:"Demand",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"F(x)",grid:true,domain: [0,1]},marks: [ Plot.line(xs.map(x => ({x,F: result.demand.cdf(x)})), {x:"x",y:"F",curve: result.demand.discrete?"step-after":"linear",stroke: theme.primary,strokeWidth:1.5}), Plot.ruleY([criticalRatio(result.costs)], {stroke: theme.accent,strokeDasharray:"5,3"}), Plot.ruleX([result.best.level], {stroke: theme.muted}), Plot.dot([{x: result.level,F: result.demand.cdf(result.level)}], {x:"x",y:"F",r:6,fill: theme.accent}) ],ariaLabel:"The demand distribution function with the critical ratio",ariaDescription:`The optimal quantity is ${result.best.level.toFixed(2)}.`}) :html``
The second plot is the expected cost against the quantity available, with your quantity as the red dot.
result.ok? Plot.plot({style: plotStyle,height:250,marginLeft:80,marginBottom:45,x: {label:"Units available, Q",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"Expected cost ($)",grid:true,domain: [0,3*Math.max(result.best.expectedCost,1e-9)]},marks: [ Plot.line(xs.filter(x => x >= onHand).map(x => ({x,c:evaluate(result.costs, result.demand, x, onHand).expectedCost})), {x:"x",y:"c",stroke: theme.muted,strokeWidth:1.5,clip:true}), Plot.dot([{x: result.level,c: result.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 $${result.best.expectedCost.toFixed(2)}.`}) :html``
Things to Try
Press Use the optimal quantity. The page builds the belt’s fourteen-week demand from the fitted weekly mean of 33.2404 and variance of 613.0387, and orders 475.18 belts, the chapter’s answer.
Change the family to the negative binomial: the order becomes 469. Change it to the Poisson, which ignores the variance: the order falls to 467, because a Poisson with this mean is far less spread than the data.
Choose one period instead of fourteen, with the normal. A normal with the weekly mean and variance puts about 9% of its probability below zero, which is why the chapter rejected it for weekly demand.
Set the salvage value to $50, the unit cost. Then \(c_{o} = 0\), and the page explains why it refuses.