Saturday, November 21, 2026

The Invention of Blood Pressure: From a Horse’s Artery to the Cuff That Changed Medicine

How an eighteenth-century experiment, a column of mercury, an inflatable cuff and the sounds of flowing blood transformed one of the most important measurements in modern healthcare.

A number that changed medicine

Imagine visiting a physician in the early nineteenth century. The physician feels your pulse, observes your complexion and asks about your symptoms. Perhaps the pulse seems unusually forceful. But the physician cannot tell you that your blood pressure is 160/100 mmHg. Those numbers do not yet belong to routine medical practice.

Today, blood-pressure measurement is so familiar that we rarely notice the extraordinary scientific achievement behind it. A cuff is wrapped around an arm, inflated, and released. Two numbers appear on a screen. They can guide decisions about stroke prevention, kidney disease, pregnancy, surgery and long-term cardiovascular care.

How did humans learn to measure a force acting deep inside living arteries without opening the body? The answer took almost three centuries of discoveries in anatomy, fluid mechanics, acoustic science and instrument design.

1. Before blood pressure: discovering circulation

In 1628, English physician William Harvey published De Motu Cordis, assembling experimental arguments that blood circulates continuously through the body and the heart works as a pump. He studied the direction of flow, venous valves and the astonishing quantity of blood expelled by the heart. The volume was far too great to be continuously manufactured and consumed as earlier theories implied.

Harvey had no modern pressure gauge. Nevertheless, his model made pressure a natural physiological question. If blood circulates through a closed vascular system, what force moves it, and how does that force vary during the heartbeat?

2. 1733: Stephen Hales and the horse experiment

English clergyman and scientist Stephen Hales performed the first widely recognised direct measurement of arterial blood pressure. He connected a long vertical glass tube to an artery in a horse and watched blood rise in it. His experiments were described in Haemastaticks (1733). In a commonly cited experiment, the blood column rose to roughly eight feet, about 2.5 metres.

The physics was hydrostatic: arterial pressure supported a column of liquid. For a fluid of density ρ, a column of height h under gravity g exerts pressure P = ρgh.

For an illustrative 2.5-metre blood column, taking blood density as 1,060 kg/m³ and g = 9.81 m/s²:

P ≈ 1,060 × 9.81 × 2.5 ≈ 26,000 pascals ≈ 195 mmHg.

This is a hydrostatic conversion, not a modern reconstruction of the horse's clinically meaningful systolic and diastolic values. The experiment was invasive, but it proved that an invisible physiological force could become a number. [1, 2]

3. Why mercury came to dominate

Hales’ towering tube was hardly a bedside instrument. A denser liquid requires a shorter column to represent the same pressure. Mercury is about 13.6 times as dense as water; mercury manometers therefore made pressure apparatus much more compact. Nineteenth-century investigators, including Jean Léonard Marie Poiseuille, advanced the use of mercury pressure measurement in physiological experiments.

The legacy is embedded in the units. 120 mmHg means a pressure equivalent to that exerted by a mercury column 120 mm high under standard conditions. Even digital semiconductor pressure sensors generally report results in millimetres of mercury. The metal largely departed from clinical devices, but its units remain.

4. The non-invasive problem

Direct arterial measurement was experimentally revealing but not appropriate for routine clinical encounters. Nineteenth-century researchers explored whether external compression could reveal the pressure inside an artery.

Karl von Vierordt studied how external pressure could suppress an arterial pulse. Étienne-Jules Marey pioneered recording physiological movement and pulse waveforms. This shift was crucial: a clinician's subjective sensation could now be represented as a reproducible mechanical trace.

But estimating arterial pressure from a local pulse was difficult. Tissue thickness, placement, contact force and anatomy all modified the signal. The instrument needed a more standardised interface to the body.

5. Von Basch and the early sphygmomanometer

During the 1880s, Samuel Siegfried Karl Ritter von Basch developed a practical apparatus for estimating arterial pressure non-invasively. It applied pressure over an artery through a small contact element, coupled with a manometer. The point of pulse suppression helped indicate systolic pressure.

It was a major advance, but small contact regions were sensitive to placement and local anatomy. What if compression could be spread more evenly around an entire arm?

6. 1896: Riva-Rocci invents the cuff-based method

In 1896, Italian physician Scipione Riva-Rocci described the apparatus that became the ancestor of the familiar upper-arm sphygmomanometer: an inflatable cuff, rubber inflation bulb and mercury manometer. The cuff compressed the brachial artery; the physician then gradually released pressure and observed when the peripheral pulse returned.

That return provided an estimate of systolic pressure. The original system did not yet routinely deliver the systolic/diastolic pair. Nevertheless, the architecture was established:

Inflatable cuff → controlled arterial compression → measured external pressure → observation of arterial response.

This was an elegant physiological experiment packaged for repeated bedside use. [1–3]

7. The forgotten innovation: cuff width

Riva-Rocci's early cuffs were relatively narrow. A narrow cuff generally needs higher pressure to occlude the underlying artery, potentially producing falsely high values. Later investigators, including Heinrich von Recklinghausen, helped establish the need for wider cuffs.

This is more than a detail about fit. It illustrates that the instrument changes the mechanical conditions under which the measurement is made. The cuff, arm tissues and artery form a coupled system.

Modern clinical practice still struggles with the same issue. A cuff that is too small can overestimate blood pressure; a cuff that is too large can underestimate it. Correct sizing is fundamental to trustworthy measurement.

8. 1905: Korotkoff hears something new

In 1905, Russian surgeon Nikolai Sergeyevich Korotkoff described sounds that appeared and changed when an inflated arm cuff was slowly deflated and a stethoscope was placed over the brachial artery downstream of the cuff.

The first reproducible tapping sounds mark the conventional systolic endpoint. In adults, disappearance of the sounds usually marks the diastolic endpoint, although special circumstances may warrant interpreting muffling as an alternative.

Two previously independent innovations had joined forces: the stethoscope contributed an acoustic signal; the sphygmomanometer contributed a pressure scale. [3, 4]

The five Korotkoff phases

Phase What is heard Interpretation
I First clear repetitive tapping Systolic-pressure reference
II Softer or swishing sounds Transitional behaviour
III Louder, crisper sounds Continued pulsatile flow through a compressed artery
IV Distinct muffling Alternative diastolic landmark in selected circumstances
V Disappearance of sounds Usual adult diastolic-pressure reference

The mechanism involves pulsatile blood flow and rapid mechanical behaviour of a partially compressed artery. Saying merely that “turbulence makes the sound” oversimplifies a complex fluid–structure interaction.

9. What do the two numbers mean?

Systolic blood pressure (SBP) represents the peak arterial pressure during the cardiac cycle, conventionally associated with ventricular ejection. Diastolic blood pressure (DBP) represents its minimum.

For an illustrative reading of 120/80 mmHg, the pulse pressure is:

PP = SBP − DBP = 120 − 80 = 40 mmHg.

Mean arterial pressure (MAP) is the time average of pressure over a cycle. At ordinary heart rates, a useful approximation is:

MAP ≈ DBP + (SBP − DBP)/3 ≈ 93.3 mmHg.

It is only an approximation. The actual waveform depends on cardiac timing, arterial properties and physiological conditions. Two numbers summarise a dynamic process rather than describing it completely.

10. Why blood pressure persists between beats

The heart ejects blood intermittently, but arterial flow continues even during diastole. Elastic arteries expand during ejection and recoil afterward. A simple Windkessel model captures this interaction between arterial compliance and resistance:

C · dP/dt = Qᵢₙ − P/R

Here C denotes effective arterial compliance, Qᵢₙ denotes inflow and R denotes effective peripheral resistance (with pressure defined relative to a chosen downstream reference). This simple model helps explain why blood pressure depends on more than cardiac contractile force. Vessel stiffness, resistance and circulating volume also matter.

11. From a sign to a silent disease

Reliable measurement changed what physicians considered a disease risk. A person could have elevated pressure for years without symptoms. Repeated measurements helped establish connections with stroke, heart failure, kidney injury and vascular disease. Elevated pressure became measurable, monitorable and, crucially, treatable before catastrophic complications occurred.

This shift helped create preventive cardiovascular medicine. An apparently ordinary cuff revealed a silent risk that symptoms alone might miss.

12. Manufacturers and the march toward everyday care

Industrial manufacturing brought the technology beyond specialist settings. Baumanometer, Riester and Welch Allyn became associated with clinical blood-pressure equipment. Later, companies including Omron, A&D, Microlife and SunTech Medical helped develop electronic home and ambulatory monitoring products.

These names represent major historical and technological lineages, not a current market-share ranking. The apparatus changed from a mercury column and hand bulb to a mass-manufactured system of sensors and embedded computation.

13. Why mercury eventually lost its place

Mercury manometers offered a clear physical pressure reference when properly maintained. But mercury is toxic when released, and the devices required maintenance and skilled observers. Aneroid gauges and electronic monitors offered more practical alternatives, while introducing their own calibration and algorithmic challenges.

The move to electronics raised a new question: how can a device estimate systolic and diastolic pressures without a human listening to Korotkoff sounds?

The answer lies in tiny pressure oscillations inside the cuff. They had been observed long before microprocessors existed. Modern electronics made it possible to interpret them automatically.

The blood-pressure cuff was about to become a computer.

Next: Part II, “When the Blood Pressure Cuff Became a Computer.”

References and further reading

  1. Royal College of Physicians of Edinburgh. Blood Pressure in the College Collections.
  2. History and evolution of blood pressure measurement (2024).
  3. History of Blood Pressure Measurement in Newborns and Infants (2023).
  4. Principles and techniques of blood pressure measurement.
  5. Automated oscillometric blood pressure measuring devices: how they work and what they measure (2022).

This is a science-and-technology history article, not medical advice. Measurements and prototype examples are educational; seek qualified clinical guidance for diagnosis and treatment.

Friday, November 20, 2026

From Spa Mist to Smart Mesh: The Remarkable History and Future of the Nebuliser

A child sits at a kitchen table with a plastic mask over her face. A small machine hums beside her. A white cloud curls through a transparent tube and disappears with each breath.

It looks simple.

Inside that cloud, however, is the end result of nearly two centuries of experimentation involving spa physicians, perfume atomisers, steam engines, rubber bulbs, compressed air, ultrasonic crystals, microprocessors and microscopic vibrating meshes.

The nebuliser is one of those medical technologies whose importance is easy to underestimate precisely because it has become so familiar. Its basic job sounds almost trivial: take a liquid medicine and transform it into droplets small enough to travel with inhaled air into the respiratory tract.

Doing that reliably, efficiently and safely turned out to be anything but trivial.

And the history of the nebuliser is therefore not merely the history of a medical appliance. It is a story about learning to engineer a cloud.

Before the nebuliser: medicine enters the lungs

Humans discovered the lung as a route for administering drugs thousands of years before anyone understood aerosol physics.

Historical accounts describe medicinal inhalation in ancient India, where preparations containing plants such as Datura were burned or smoked for respiratory symptoms. Similar practices involving plants containing anticholinergic compounds existed elsewhere in the ancient world. Hippocrates is also associated with an early inhalation apparatus consisting of a vessel and tube.

These treatments exploited an important biological fact long before its mechanisms were understood: the respiratory tract provides an enormous interface between the outside world and the body.

But smoke and vapour are not nebulised droplets.

That distinction matters.

For centuries, inhalation therapy largely meant creating vapour by heating a substance. In 1778, British physician John Mudge described an inhaler based on a modified pewter tankard. Air passed through heated water before being inhaled. Devices of this type helped establish inhalation as a legitimate therapeutic route, but they still depended mainly on evaporation and steam.

The conceptual breakthrough of the nineteenth century was different:

What if a liquid medicine itself could be shattered into tiny airborne droplets?

That question created the nebuliser.

The spa that helped inspire aerosol medicine

One of the unexpected ancestors of the nebuliser was the nineteenth-century European spa.

Mineral-water treatments were fashionable, and physicians experimented with ways of exposing the respiratory tract to mineral waters. In 1849, a French physician, Auphan, developed an apparatus at Euzet-les-Bains in which mineral water was projected against a surface, breaking the liquid into droplets that could be inhaled.

It was essentially an inhalation room filled with artificial spray.

The principle was crude, but profound.

Liquid did not have to become vapour to enter the respiratory tract. It could become droplets instead.

The next logical question was obvious: could the inhalation room be shrunk into a machine?

1858: the nebuliser becomes portable

In 1858, French physician Jean Sales-Girons introduced his pulvérisateur.

A hand-operated pump forced medicated liquid through the apparatus and against an impact surface, producing a spray that patients could inhale through a funnel-shaped opening.

For the first time, the cloud had left the spa.

The patient could bring the aerosol generator to the medicine instead of travelling to an inhalation room.

Sales-Girons' apparatus is therefore widely regarded as the first portable therapeutic nebuliser or atomiser and one of the crucial starting points of modern aerosol medicine.

Yet there was still a problem.

Making droplets was easy.

Making droplets of the correct size was much harder.

Large droplets crash into the mouth and upper airway. Very tiny particles may behave differently again. Effective pulmonary delivery therefore depends on creating an aerosol whose aerodynamic properties allow a useful fraction of the drug to travel sufficiently deep into the respiratory tract.

The history of the nebuliser would increasingly become a history of controlling particle size.

1862: Bernoulli and Venturi enter the clinic

A particularly important engineering leap arrived only a few years later.

In 1862, J. Bergson developed the Hydrokonium, an air-jet atomiser in which fast-moving air passed across the opening of another tube containing liquid. The pressure difference drew liquid upward and fragmented it into droplets.

The device exploited principles associated with Daniel Bernoulli and Giovanni Battista Venturi.

This architecture became the ancestor of the modern jet nebuliser.

A second innovation was equally important: the baffle.

Producing aerosol creates droplets of many sizes. A baffle acts as a tiny traffic controller. Large droplets collide with it and fall back into the reservoir, while smaller droplets remain suspended in the airflow and can travel toward the patient.

This distinction separates a simple spray atomiser from the more sophisticated idea of a nebuliser.

The machine is not merely making droplets. It is selecting them.

By the 1860s, designs described by figures such as Louis Waldenburg were already incorporating features that performed this function.

Remarkably, the basic physics remains visible in many jet nebulisers today.

Rubber, glass and the first truly personal nebulisers

Late nineteenth-century developments in rubber manufacturing transformed nebulisers again.

Glass medicine reservoirs could now be connected to squeezable rubber bulbs. Compressing the bulb sent a pulse of air through the atomising mechanism.

No steam boiler.

No large pump.

No electricity.

Suddenly aerosol therapy became substantially more portable.

One particularly influential figure was American physician Allen DeVilbiss.

DeVilbiss specialised in diseases of the nose and throat and was dissatisfied with existing spray devices. He developed a medical atomiser around 1887, patented an atomiser in 1888 and founded the DeVilbiss Manufacturing Company. His designs became widely used, and the company subsequently expanded atomisation technology into perfume sprays and even paint-spraying equipment.

It is a lovely example of technologies cross-pollinating between medicine and industry.

The same physical problem, turning liquid into controlled droplets, appeared in respiratory medicine, perfume bottles and paint shops.

The compressor changes everything

Hand bulbs were portable but inconsistent.

The next revolution came from replacing the patient's hand with a mechanical source of compressed air.

By the early 1930s, electrically powered compressed-air systems such as the Pneumostat appeared. These machines could produce aerosol more continuously and predictably than manually operated devices.

The nebuliser now acquired the basic architecture familiar to generations of patients:

compressor → tubing → medication chamber → aerosol → mouthpiece or mask

Early electric systems were expensive and cumbersome, but electrification gradually made aerosol therapy more reproducible.

Then another apparently mundane technology transformed nebulisers: plastic.

The Wright nebuliser and the importance of a tiny hole

In the 1950s, the Wright nebuliser demonstrated how enormously important manufacturing precision could be.

Injection-moulded plastics allowed designers to manufacture Venturi openings and internal geometries far more consistently. The resulting devices generated finer aerosols, including droplets in the range useful for lower-airway delivery.

The breakthrough was not a dramatic new source of energy. It was better control over geometry.

The nozzle became precise.

The baffle became precise.

The aerosol became more predictable.

This is one of the recurring lessons in medical-device history: sometimes the revolution is hiding inside a fraction of a millimetre.

Then the nebuliser gained a competitor

In 1956, Riker Laboratories introduced the first pressurised metered-dose inhaler.

The MDI was compact, fast and extraordinarily portable. Instead of sitting beside a compressor for several minutes, many patients could carry their medication in a pocket.

Nebulisers did not disappear.

Instead, their role became clearer.

They were particularly valuable when patients could not easily coordinate inhaler actuation with breathing, when large drug doses or liquid formulations were required, in paediatric care, during acute respiratory illness and for medicines not easily formulated for conventional inhalers.

Competition from the pocket inhaler therefore did something productive: it forced nebulisers to evolve.

1962: using sound to make a cloud

The next major technology did away with the compressed-air jet.

Robert Lang introduced an ultrasonic nebuliser in 1962 using a piezoelectric crystal.

Apply an electrical signal to a piezoelectric material and it changes shape. Drive it rapidly enough and it produces high-frequency vibrations. Those vibrations can transfer energy into a liquid and create aerosol droplets.

Ultrasonic nebulisers offered high aerosol output and could be quieter and more compact than traditional compressor-driven machines.

But they also introduced new problems.

The technology could heat the liquid. Early devices suffered reliability problems. Different drug formulations behaved differently under ultrasonic conditions. Changing liquid volumes altered loading on the piezoelectric system.

The lesson would become increasingly important:

A nebuliser and a medicine cannot always be treated as independent products.

The device can affect the drug.

The drug can affect the device.

The rise of respiratory engineering specialists

As aerosol therapy matured, specialised companies began shaping different branches of the technology.

PARI, founded in Germany in 1906, became one of the most influential names in aerosol therapy. The company developed a large-volume nebuliser by 1920, patented a fine-atomising nozzle in 1953 and introduced the PARI BOY in 1968, helping make compressor nebulisation practical in the home. Decades later, PARI would become an important developer of vibrating-membrane systems and drug-device combinations.

DeVilbiss represents another historical lineage, beginning with Allen DeVilbiss's nineteenth-century medical atomisers.

Omron would become particularly important in portable mesh nebulisation.

Trudell Medical introduced the AEROECLIPSE breath-actuated nebuliser in 1998, addressing one of the fundamental inefficiencies of conventional continuous nebulisation: why generate expensive aerosol while the patient is breathing out?

Philips Respironics and its predecessor organisations helped develop Adaptive Aerosol Delivery systems such as HaloLite, Prodose and the I-neb.

And Aerogen, based in Galway, Ireland, became a prominent specialist in vibrating-mesh aerosol delivery, particularly in acute and critical care. Aerogen says its vibrating-mesh technology has been used to treat more than 30 million patients across 80 countries.

These companies should not be interpreted as a strict current market-share ranking. Rather, they represent some of the major technological lineages that shaped modern nebulisation.

The great leap: vibrating mesh

If the compressor nebuliser represents the classic twentieth-century nebuliser, the vibrating-mesh nebuliser represents one of the most important transitions into the twenty-first.

The concept is beautifully simple.

Imagine an extremely thin membrane perforated with thousands of microscopic holes.

Now vibrate it extremely rapidly.

Liquid is pushed through those tiny apertures, emerging as a remarkably controlled aerosol.

No roaring compressor is required.

The result can be small, battery-powered, quiet and highly efficient.

Omron was an important early commercial developer. Its NE-U03 mesh nebuliser appeared in Japan in 1993. Continued development led to systems such as the MicroAir NE-U22, launched in 2002. Modern descendants can fit in the palm of a hand.

PARI's eFlow platform, introduced in 2005, similarly used vibrating-membrane technology to shorten treatment times and enable compact drug-delivery systems.

Aerogen developed vibrating-mesh systems particularly suited to hospital and ventilator environments.

The change may sound incremental until one considers what was disappearing:

the bulky compressor,

the long tube,

much of the noise,

a considerable amount of residual drug,

and part of the treatment time.

The nebuliser was becoming something patients could carry rather than something they had to sit beside.

From continuous clouds to intelligent doses

There remained a fundamental inefficiency.

A normal person breathes in.

Then out.

A conventional nebuliser may continue creating aerosol during both phases.

The drug produced during exhalation can therefore be wasted.

Engineers began teaching nebulisers to watch the patient breathe.

Adaptive Aerosol Delivery technology took this concept further. The HaloLite system, commercially introduced in 1997, monitored breathing patterns and timed aerosol delivery to inspiration. Later systems included Prodose and the I-neb.

The I-neb combined adaptive delivery with vibrating-mesh technology. Its electronics analysed breathing and released aerosol during selected portions of inhalation rather than simply producing an uninterrupted cloud.

This represents a philosophical change in nebuliser design.

The old machine asked:

Can I produce aerosol?

The intelligent machine asks:

When should I produce it, how much should I produce, and where in the respiratory tract do I want it to go?

That is an enormous conceptual leap.

The three great technological families

Today's nebulisers largely descend from three approaches.

Jet nebulisers use compressed gas flowing through a narrow opening to create low pressure that draws medication into the airflow and breaks it into droplets. They are robust, familiar and comparatively inexpensive, but compressors are bulky and noisy, treatment can be relatively slow and drug can be wasted.

Ultrasonic nebulisers use high-frequency vibrations generated by piezoelectric elements. They can provide rapid output and quiet operation but are not ideal for every formulation, particularly when heating or molecular stability becomes important.

Vibrating-mesh nebulisers force liquid through microscopic openings in a rapidly vibrating membrane. They can achieve high delivery efficiency, low residual volume, portability and quiet operation, though cost, cleaning, clogging and compatibility with particular formulations remain important considerations. Modern reviews increasingly describe mesh platforms as particularly attractive for the development of new nebulised pharmaceuticals.

The trend is therefore not simply toward smaller nebulisers.

It is toward more controlled nebulisers.

The next frontier: the nebuliser becomes part of the medicine

Perhaps the most profound change now occurring is that pharmaceutical companies increasingly cannot think about the molecule and nebuliser separately.

A fragile biological molecule may tolerate one aerosol-generation mechanism and be damaged by another.

For example, research on inhaled biological therapeutics has shown that aerosolisation stresses can influence protein stability, while vibrating-mesh systems may sometimes cause less aggregation than particular jet systems.

This encourages the emergence of the drug-device combination.

Instead of inventing a medicine and later asking which nebuliser can deliver it, developers can optimise the formulation and aerosol generator together.

PARI's eFlow platforms are an example of this broader direction, in which specific aerosol systems are developed alongside pharmaceutical applications.

The nebuliser is slowly becoming less like a generic appliance and more like part of the pharmaceutical formulation itself.

Future 1: biologics will demand gentler clouds

Traditional nebulised drugs are often relatively small molecules or salts.

The future pipeline is far more ambitious.

Proteins.

Peptides.

Antibody fragments.

Enzymes.

Nucleic acids.

Gene therapies.

These molecules are fragile compared with many conventional respiratory drugs.

A nebuliser must therefore do something astonishingly delicate: subject a biological molecule to enormous physical forces, transform the liquid containing it into microscopic airborne droplets, transport those droplets through the device and respiratory tract, and still leave the therapeutic molecule functional when it arrives.

Recent reviews suggest inhaled biologics could become increasingly important for respiratory diseases because local delivery may produce high concentrations in the lung while reducing systemic exposure. The major hurdles remain formulation stability, aerosolisation stress, immune responses, pulmonary barriers and reliable delivery.

This may be one reason vibrating-mesh technologies become even more important.

The next generation of nebulisers may be designed not merely around droplet diameter but around molecular survival.

Future 2: RNA in a mist

Here the story becomes especially futuristic.

Researchers are investigating pulmonary delivery of siRNA, mRNA and other nucleic-acid therapeutics.

Nebulisation is appealing because it can potentially deliver relatively large amounts of liquid during normal tidal breathing. But RNA molecules and their nanoparticle carriers must survive aerosolisation, mucus, immune defence, enzymatic degradation and cellular uptake before reaching their molecular targets.

Research published in 2026 describes inhalable RNA nanomedicines for applications ranging from protein replacement and gene silencing to vaccination, cancer therapy and genome editing, while emphasising that formulation, nanocarrier and inhalation device must ultimately function as one integrated product.

Imagine the progression:

The nineteenth-century nebuliser delivered mineral water.

The twentieth-century nebuliser delivered bronchodilators and antibiotics.

A future nebuliser may deliver genetic instructions.

That is an extraordinary technological arc.

Future 3: the cloud will learn when you breathe

Smart nebulisation is likely to become less about putting Bluetooth into a medical device and more about making aerosol generation responsive to respiratory physiology.

Pressure and flow sensors can already detect breathing patterns.

Future systems can push this further through improved breath synchronisation, personalised flow profiles, dose verification, treatment logging and potentially feedback systems that coach patients toward more reproducible inhalation patterns.

The ideal system would know:

whether the patient actually inhaled,

how strongly they inhaled,

how long the breath lasted,

how much drug left the reservoir,

when aerosol was produced,

and whether the prescribed dose was probably deposited.

Some of these functions already exist in partial form. The future will be about integrating them more seamlessly and reliably.

The nebuliser is gradually turning from a pump into a measurement instrument.

Future 4: targeting regions within the lung

Future aerosol medicine may also care increasingly about where particles land.

Particle size, inhalation flow, timing and breathing pattern all influence deposition.

Aerosol generated early in a slow inspiration may behave differently from aerosol released at another point in the respiratory cycle.

Adaptive systems already demonstrate the possibility of targeting aerosol delivery to particular portions of inhalation.

Combine that with better modelling of respiratory airflow, individual lung geometry and disease-specific airway obstruction, and a more ambitious vision emerges:

not simply pulmonary drug delivery,

but regional pulmonary drug delivery.

One could imagine treatment parameters optimised differently for central airway disease, peripheral lung disease, pulmonary infection, fibrosis or particular genetic disorders.

The cloud becomes navigational.

Future 5: portability will continue, but simplicity will matter

There is a temptation in medical technology to assume that the future must contain more electronics.

History offers a warning.

Many successful respiratory devices succeeded because they became simpler.

Portable mesh nebulisers are attractive precisely because they remove compressors and tubing. Modern Omron MicroAir systems, for example, are handheld, battery-powered and based on vibrating-mesh technology.

The winning future device may therefore be technologically sophisticated inside but almost invisible to the patient.

One reservoir.

One button.

Quiet operation.

Fast treatment.

Minimal cleaning.

Clear confirmation that the dose was delivered.

Sophisticated engineering hidden behind simple behaviour.

That is harder to accomplish than adding another screen.

The unresolved problems

Nebulisers still have weaknesses.

Cleaning is critical because medication chambers, masks and mouthpieces can become contaminated.

Tiny mesh apertures can clog.

Viscous liquids and suspensions may not behave like simple solutions.

Different devices can generate different aerosol characteristics from the same medicine.

Hospital nebulisation raises infection-control questions, particularly when treating patients with transmissible respiratory diseases.

Treatment time remains important for adherence.

High-performance electronic systems can cost considerably more than basic compressor nebulisers.

And every improvement in delivery efficiency makes dosing precision more important. A drug dose developed around an inefficient nebuliser cannot automatically be transferred to a highly efficient mesh system without considering how much medicine actually reaches the patient.

These are not peripheral engineering details.

They are part of pharmacology.

The major players in the modern story

Several companies illustrate the different technological paths the field has taken.

PARI spans much of modern nebuliser history, from early large-volume systems and compressor nebulisers to eFlow vibrating-membrane platforms and pharmaceutical partnerships.

Omron helped push mesh nebulisation into extremely portable consumer devices, with a commercial lineage extending from the NE-U03 in the 1990s to modern MicroAir systems.

Aerogen has specialised strongly in vibrating-mesh technology for acute and critical-care environments.

Philips Respironics and predecessor organisations played an influential role in adaptive, breath-responsive aerosol delivery through systems such as HaloLite, Prodose and I-neb.

Trudell Medical contributed important breath-actuated technology through the AEROECLIPSE platform.

DeVilbiss represents one of the oldest threads in the story, tracing atomisation technology back to Allen DeVilbiss's work in the 1880s.

There are many additional manufacturers and pharmaceutical-device partnerships worldwide, but these names illustrate how the industry evolved from mechanical atomisation into increasingly specialised respiratory drug-delivery platforms.

From machine to platform

Perhaps the best way to understand the nebuliser's future is to stop thinking of it as a machine.

The nineteenth-century nebuliser was a machine for making spray.

The twentieth-century nebuliser became a machine for producing respirable aerosol.

The early twenty-first-century nebuliser became a device for efficiently delivering controlled doses.

The next generation is becoming something larger:

a pulmonary drug-delivery platform.

Its performance may involve aerosol physics, formulation chemistry, fluid mechanics, sensors, electronics, algorithms, patient behaviour and molecular biology simultaneously.

That transformation is particularly significant because the lungs offer something medicine desperately wants: direct access to an enormous biological surface without a needle.

For respiratory disease, that can mean placing a therapy close to its target while limiting exposure elsewhere in the body.

For some future systemic therapies, the lung itself may even become an entry point to the bloodstream.

A cloud nearly two centuries in the making

Look again at that familiar white mist leaving a nebuliser.

Inside it are ideas inherited from nineteenth-century mineral spas.

There is Bernoulli's pressure principle.

There is Venturi flow.

There are lessons from perfume atomisers.

There is precision plastic moulding.

There are piezoelectric crystals.

There are membranes perforated with microscopic holes.

There are microprocessors watching a patient inhale.

And increasingly, there may be proteins, antibodies, nanoparticles and strands of RNA travelling inside the droplets.

The history of nebulisation is therefore a wonderful example of technological evolution without a single dramatic endpoint.

Each generation solved one more problem.

First, make liquid airborne.

Then make the droplets smaller.

Then make their size predictable.

Then make the machine portable.

Then make it quiet.

Then reduce wasted drug.

Then synchronise it with breathing.

Then protect fragile molecules.

Now the challenge is becoming still more ambitious:

Can we engineer not merely an aerosol, but the precise journey of a therapeutic molecule from a reservoir, through a cloud, into the correct region of the lung and finally into the correct cell?

If that happens, the nebuliser of the future may look almost nothing like the brass, glass and rubber machines from which it descended.

But its fundamental purpose will remain wonderfully unchanged.

Turn medicine into a cloud.

And let the patient breathe it in.

Monday, November 9, 2026

Building dshapiro(), pshapiro(), qshapiro() and rshapiro() from Scratch in Base R

In the previous post, we examined the Shapiro-Wilk normality test and the familiar R convention of using four functions for a probability distribution:

Prefix Meaning Normal example
d Density dnorm()
p Cumulative probability pnorm()
q Quantile qnorm()
r Random generation rnorm()

But Base R does not provide:

dshapiro()
pshapiro()
qshapiro()
rshapiro()

Why not?

The reason is important. The Shapiro-Wilk statistic W does not have a simple probability distribution such as the normal, t, chi-square or F distribution. Its null distribution depends strongly on the sample size n, and the p-values reported by shapiro.test() are obtained using numerical approximations.

That does not stop us from building our own educational d, p, q and r functions.

We can approximate the null distribution of W using Monte Carlo simulation.

1. What distribution are we actually studying?

Suppose:

X1, X2, ..., Xn ~ Normal

For each random sample, calculate the Shapiro-Wilk statistic:

W = Shapiro-Wilk statistic

If we repeat this experiment thousands of times, we obtain a distribution of W under the null hypothesis.

That distribution is:

The sampling distribution of the Shapiro-Wilk W statistic when the data are truly normal.

This is the distribution we will use to construct:

  • dshapiro() = approximate density of W;
  • pshapiro() = approximate cumulative probability for W;
  • qshapiro() = approximate quantiles of W;
  • rshapiro() = random values of W under normality.

2. A crucial fact: the distribution depends on sample size

Unlike the standard normal distribution, the distribution of W changes with n.

For example, the distribution of W for:

n = 10
n = 30
n = 100

will be different.

Therefore every function we write must include n as an argument.

Conceptually:

pshapiro(w, n = 30)

means:

For samples of size 30 drawn from a normal population, what proportion of Shapiro-Wilk W statistics are less than or equal to w?

3. First build rshapiro()

The most natural function to build first is rshapiro().

To generate one random Shapiro-Wilk W value:

  1. generate n observations from a normal distribution;
  2. run shapiro.test();
  3. extract W.

Then repeat this procedure as many times as requested.

4. Base R implementation of rshapiro()

rshapiro <- function(
  N,
  n,
  mean = 0,
  sd = 1
) {

  # N = number of W statistics to generate
  # n = sample size used for each Shapiro-Wilk test

  if (N < 1)
    return(numeric(0))

  if (n < 3)
    stop("Shapiro-Wilk requires at least 3 observations")

  if (n > 5000)
    stop("Base R shapiro.test() allows at most 5000 observations")

  if (sd <= 0)
    stop("sd must be positive")

  # Create storage for simulated W statistics
  W <- numeric(N)

  # Repeat N times
  for (i in seq_len(N)) {

    # Generate a sample from a normal population
    x <- rnorm(
      n = n,
      mean = mean,
      sd = sd
    )

    # Calculate Shapiro-Wilk statistic
    W[i] <- unname(
      shapiro.test(x)$statistic
    )
  }

  return(W)
}

5. Demonstrating rshapiro()

Generate ten Shapiro-Wilk statistics for samples of size 20:

set.seed(123)

rshapiro(
  N = 10,
  n = 20
)

You might obtain values such as:

0.963
0.974
0.952
0.983
0.968
...

Notice that most values are close to 1 because the underlying samples were generated from a normal distribution.

6. Generate the complete null distribution

For teaching purposes, generate a much larger number of W statistics:

set.seed(123)

W30 <- rshapiro(
  N = 10000,
  n = 30
)

Now inspect the distribution:

hist(
  W30,
  breaks = 50,
  probability = TRUE,
  main = "Null distribution of Shapiro-Wilk W",
  xlab = "W"
)

This is an approximation to the sampling distribution of W for:

n = 30

7. Why the mean and standard deviation do not matter

Try:

set.seed(123)

W1 <- rshapiro(
  N = 5000,
  n = 30,
  mean = 0,
  sd = 1
)

set.seed(123)

W2 <- rshapiro(
  N = 5000,
  n = 30,
  mean = 100,
  sd = 25
)

Compare:

mean(W1)
mean(W2)

sd(W1)
sd(W2)

They will be essentially identical.

This illustrates an important property of the Shapiro-Wilk test:

The W statistic is invariant to changes in location and scale.

Therefore:

Normal(0,1)

is sufficient when simulating the null distribution.

8. Building pshapiro()

The p-function for a distribution gives:

P(W ≤ w)

For example:

pshapiro(
  q = 0.95,
  n = 30
)

asks:

Under normality, what fraction of samples of size 30 produce W less than or equal to 0.95?

9. Monte Carlo implementation of pshapiro()

pshapiro <- function(
  q,
  n,
  B = 10000,
  lower.tail = TRUE,
  seed = NULL
) {

  # q = observed W value
  # n = sample size
  # B = number of Monte Carlo simulations

  if (!is.null(seed))
    set.seed(seed)

  if (n < 3)
    stop("n must be at least 3")

  if (n > 5000)
    stop("n cannot exceed 5000")

  # Generate null distribution of W
  Wnull <- rshapiro(
    N = B,
    n = n
  )

  # Empirical cumulative probability
  p <- sapply(
    q,
    function(value) {
      mean(Wnull <= value)
    }
  )

  # Return lower or upper tail
  if (!lower.tail)
    p <- 1 - p

  return(p)
}

10. Demonstrating pshapiro()

set.seed(100)

pshapiro(
  q = 0.95,
  n = 30,
  B = 20000
)

Suppose this returns approximately:

0.17

This means:

About 17% of normally distributed samples of size 30 produce a Shapiro-Wilk W statistic of 0.95 or smaller.

11. Why Shapiro-Wilk uses the lower tail

For Shapiro-Wilk:

small W = stronger departure from normality

Therefore the p-value is based on:

P(W ≤ Wobserved)

rather than the upper tail.

This is different from many familiar test statistics such as chi-square or F, where large values provide evidence against the null hypothesis.

12. Compare pshapiro() with shapiro.test()

Generate a sample:

set.seed(42)

x <- rnorm(30)

test <- shapiro.test(x)

test

Extract W:

Wobs <- unname(
  test$statistic
)

Wobs

Now estimate its p-value by simulation:

pshapiro(
  q = Wobs,
  n = length(x),
  B = 50000,
  seed = 100
)

Compare with:

test$p.value

The values should be reasonably similar, although they will not be identical.

Why?

Our function uses Monte Carlo simulation, whereas shapiro.test() uses specialised analytical approximations.

13. A better Monte Carlo p-value

A simple simulation can occasionally return p = 0 if no simulated W is as small as the observed value.

A common finite-simulation correction is:

p = (number of simulated W ≤ observed W + 1) / (B + 1)

We can modify pshapiro() accordingly.

pshapiro <- function(
  q,
  n,
  B = 10000,
  lower.tail = TRUE,
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  if (n < 3)
    stop("n must be at least 3")

  if (n > 5000)
    stop("n cannot exceed 5000")

  Wnull <- rshapiro(
    N = B,
    n = n
  )

  p <- sapply(
    q,
    function(value) {

      lower <-
        (sum(Wnull <= value) + 1) /
        (B + 1)

      if (lower.tail)
        return(lower)

      return(1 - lower)
    }
  )

  return(p)
}

14. Building qshapiro()

The q-function is the inverse of the p-function.

It answers:

What value of W corresponds to a particular cumulative probability?

For example:

qshapiro(
  p = 0.05,
  n = 30
)

asks:

What is approximately the lower 5th percentile of W when n = 30 and the data are normal?

This value acts as an approximate 5% critical value.

15. Base R implementation of qshapiro()

qshapiro <- function(
  p,
  n,
  B = 10000,
  lower.tail = TRUE,
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  if (any(p < 0 | p > 1))
    stop("p must lie between 0 and 1")

  if (n < 3)
    stop("n must be at least 3")

  if (n > 5000)
    stop("n cannot exceed 5000")

  # Generate null distribution
  Wnull <- rshapiro(
    N = B,
    n = n
  )

  # Convert upper-tail probabilities if requested
  probs <- p

  if (!lower.tail)
    probs <- 1 - p

  # Empirical quantiles
  result <- quantile(
    Wnull,
    probs = probs,
    names = FALSE,
    type = 8
  )

  return(result)
}

16. Demonstrating qshapiro()

set.seed(123)

qshapiro(
  p = 0.05,
  n = 30,
  B = 50000
)

Suppose this gives:

0.93

Then approximately 5% of normal samples of size 30 generate:

W ≤ 0.93

Thus 0.93 is an approximate 5% critical value.

17. Demonstrating the p-q relationship

Suppose:

crit <- qshapiro(
  p = 0.05,
  n = 30,
  B = 50000,
  seed = 10
)

crit

Now evaluate its cumulative probability:

pshapiro(
  q = crit,
  n = 30,
  B = 50000,
  seed = 20
)

The answer should be close to:

0.05

This illustrates the same relationship we see with:

pnorm(qnorm(0.05))

18. Building dshapiro()

The d-function is slightly more complicated.

For a continuous distribution:

d(x) = probability density at x

But we do not have a closed-form density equation for W.

Instead, we can:

  1. simulate thousands of W values;
  2. estimate their density using kernel density estimation;
  3. interpolate that density at the requested W value.

19. Base R implementation of dshapiro()

dshapiro <- function(
  x,
  n,
  B = 20000,
  bw = "nrd0",
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  if (n < 3)
    stop("n must be at least 3")

  if (n > 5000)
    stop("n cannot exceed 5000")

  # Simulate null distribution
  Wnull <- rshapiro(
    N = B,
    n = n
  )

  # Kernel density estimate
  dens <- density(
    Wnull,
    bw = bw,
    from = 0,
    to = 1
  )

  # Interpolate density at requested x values
  answer <- approx(
    x = dens$x,
    y = dens$y,
    xout = x,
    rule = 2
  )$y

  # W cannot theoretically be outside 0 to 1
  answer[x < 0 | x > 1] <- 0

  return(answer)
}

20. Demonstrating dshapiro()

dshapiro(
  x = 0.95,
  n = 30,
  B = 50000,
  seed = 123
)

This gives an estimated probability density around:

W = 0.95

Remember:

A density is not a probability.

For a continuous statistic:

P(W = 0.95) = 0

The density describes how concentrated the probability distribution is near 0.95.

21. Plotting our estimated Shapiro-Wilk density

wgrid <- seq(
  0.80,
  1,
  length.out = 200
)

dens30 <- dshapiro(
  x = wgrid,
  n = 30,
  B = 50000,
  seed = 123
)

plot(
  wgrid,
  dens30,
  type = "l",
  lwd = 2,
  xlab = "Shapiro-Wilk W",
  ylab = "Estimated density",
  main = "Estimated null density of W, n = 30"
)

22. Comparing different sample sizes

This is one of the most informative demonstrations.

wgrid <- seq(
  0.75,
  1,
  length.out = 300
)

d10 <- dshapiro(
  wgrid,
  n = 10,
  B = 30000,
  seed = 1
)

d30 <- dshapiro(
  wgrid,
  n = 30,
  B = 30000,
  seed = 2
)

d100 <- dshapiro(
  wgrid,
  n = 100,
  B = 30000,
  seed = 3
)

plot(
  wgrid,
  d10,
  type = "l",
  lwd = 2,
  xlab = "W",
  ylab = "Estimated density",
  main = "Null distribution of W depends on sample size"
)

lines(
  wgrid,
  d30,
  lwd = 2,
  lty = 2
)

lines(
  wgrid,
  d100,
  lwd = 2,
  lty = 3
)

legend(
  "topleft",
  legend = c(
    "n = 10",
    "n = 30",
    "n = 100"
  ),
  lty = c(1, 2, 3),
  lwd = 2
)

As n increases, the distribution of W becomes increasingly concentrated near 1.

This is why a value such as:

W = 0.97

may be completely ordinary for a small sample but unusually low for a very large sample.

23. Collecting all four functions together

Here are the complete educational functions in one block.

############################################################
# rshapiro()
############################################################

rshapiro <- function(
  N,
  n
) {

  if (N < 1)
    return(numeric(0))

  if (n < 3)
    stop("n must be at least 3")

  if (n > 5000)
    stop("n cannot exceed 5000")

  W <- numeric(N)

  for (i in seq_len(N)) {

    x <- rnorm(n)

    W[i] <-
      unname(
        shapiro.test(x)$statistic
      )
  }

  return(W)
}


############################################################
# pshapiro()
############################################################

pshapiro <- function(
  q,
  n,
  B = 10000,
  lower.tail = TRUE,
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  Wnull <- rshapiro(
    N = B,
    n = n
  )

  p <- sapply(
    q,
    function(value) {

      lower <-
        (sum(Wnull <= value) + 1) /
        (B + 1)

      if (lower.tail)
        return(lower)

      return(1 - lower)
    }
  )

  return(p)
}


############################################################
# qshapiro()
############################################################

qshapiro <- function(
  p,
  n,
  B = 10000,
  lower.tail = TRUE,
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  if (any(p < 0 | p > 1))
    stop("p must lie between 0 and 1")

  Wnull <- rshapiro(
    N = B,
    n = n
  )

  probs <- p

  if (!lower.tail)
    probs <- 1 - p

  quantile(
    Wnull,
    probs = probs,
    names = FALSE,
    type = 8
  )
}


############################################################
# dshapiro()
############################################################

dshapiro <- function(
  x,
  n,
  B = 20000,
  bw = "nrd0",
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  Wnull <- rshapiro(
    N = B,
    n = n
  )

  dens <- density(
    Wnull,
    bw = bw,
    from = 0,
    to = 1
  )

  answer <- approx(
    x = dens$x,
    y = dens$y,
    xout = x,
    rule = 2
  )$y

  answer[
    x < 0 |
    x > 1
  ] <- 0

  return(answer)
}

24. Demonstrating all four functions

############################################################
# Choose sample size
############################################################

n <- 30


############################################################
# r: generate random W values
############################################################

set.seed(1)

rshapiro(
  N = 5,
  n = n
)


############################################################
# p: cumulative probability
############################################################

pshapiro(
  q = 0.95,
  n = n,
  B = 30000,
  seed = 1
)


############################################################
# q: lower 5% critical value
############################################################

qshapiro(
  p = 0.05,
  n = n,
  B = 30000,
  seed = 1
)


############################################################
# d: estimated density
############################################################

dshapiro(
  x = 0.95,
  n = n,
  B = 30000,
  seed = 1
)

25. Reproducing a complete Shapiro-Wilk test manually

Now we can use our functions to construct an approximate Shapiro-Wilk test.

set.seed(123)

x <- rnorm(
  30,
  mean = 50,
  sd = 10
)

# Calculate observed W
Wobs <-
  unname(
    shapiro.test(x)$statistic
  )

Wobs

Now obtain our Monte Carlo p-value:

p_manual <- pshapiro(
  q = Wobs,
  n = length(x),
  B = 50000,
  seed = 999
)

p_manual

Compare with R:

shapiro.test(x)$p.value

The two values should usually be close.

26. Writing our own complete my_shapiro_test()

my_shapiro_test <- function(
  x,
  B = 50000,
  seed = NULL
) {

  # Remove missing values
  x <- x[!is.na(x)]

  n <- length(x)

  if (n < 3)
    stop("At least 3 observations are required")

  if (n > 5000)
    stop("At most 5000 observations are allowed")

  # Calculate observed Shapiro-Wilk statistic
  Wobs <-
    unname(
      shapiro.test(x)$statistic
    )

  # Estimate lower-tail probability
  pvalue <- pshapiro(
    q = Wobs,
    n = n,
    B = B,
    seed = seed
  )

  result <- list(
    statistic = Wobs,
    p.value = pvalue,
    sample.size = n,
    simulations = B
  )

  return(result)
}

Example:

set.seed(42)

x <- rnorm(30)

my_shapiro_test(
  x,
  B = 50000,
  seed = 100
)

Compare:

shapiro.test(x)

27. Test our implementation on non-normal data

Generate exponential observations:

set.seed(50)

x <- rexp(
  30,
  rate = 1
)

my_shapiro_test(
  x,
  B = 50000,
  seed = 100
)

shapiro.test(x)

Both procedures should generally indicate strong evidence against normality.

28. Visualising the observed statistic inside the null distribution

This is perhaps the best way to understand a hypothesis test.

set.seed(50)

x <- rexp(30)

Wobs <-
  unname(
    shapiro.test(x)$statistic
  )

set.seed(100)

Wnull <- rshapiro(
  N = 50000,
  n = length(x)
)

hist(
  Wnull,
  breaks = 60,
  probability = TRUE,
  main = "Observed W within the null distribution",
  xlab = "Shapiro-Wilk W"
)

abline(
  v = Wobs,
  lwd = 3
)

For strongly non-normal data, the observed W will sit deep in the lower tail.

The p-value is simply the fraction of the null distribution lying at or below that observed value.

29. Mark the rejection region

critical <-
  quantile(
    Wnull,
    0.05
  )

critical

Then:

hist(
  Wnull,
  breaks = 60,
  main = "Shapiro-Wilk null distribution",
  xlab = "W"
)

abline(
  v = critical,
  lwd = 2,
  lty = 2
)

abline(
  v = Wobs,
  lwd = 3
)

The rejection rule is approximately:

Reject H0 if W ≤ W0.05

30. Understanding d, p, q and r through Shapiro-Wilk

We can now express the four functions conceptually.

rshapiro()

Generates random Shapiro-Wilk statistics:

Normal samples → Shapiro-Wilk test → random W values

pshapiro()

Calculates:

P(W ≤ w)

qshapiro()

Finds w such that:

P(W ≤ w) = p

dshapiro()

Estimates the local probability density:

fW(w)

31. Comparing with the normal d-p-q-r functions

Purpose Normal distribution Shapiro-Wilk W distribution
Density dnorm() dshapiro()
Cumulative probability pnorm() pshapiro()
Quantile qnorm() qshapiro()
Random generation rnorm() rshapiro()

32. One important difference

For the normal distribution:

dnorm()
pnorm()
qnorm()
rnorm()

are based on well-established numerical algorithms for a mathematically defined probability distribution.

Our:

dshapiro()
pshapiro()
qshapiro()
rshapiro()

are Monte Carlo approximations.

Their precision therefore depends on:

  • the number of simulations B;
  • the random seed;
  • the kernel bandwidth used for density estimation.

33. Monte Carlo error

Suppose the true probability is p.

If we estimate it from B simulations, the Monte Carlo standard error is approximately:

SE = √[p(1-p)/B]

For:

p = 0.05
B = 10000

the standard error is approximately:

√[(0.05 × 0.95) / 10000] ≈ 0.0022

Increasing B reduces simulation noise.

34. Demonstrating Monte Carlo variability

pshapiro(
  0.95,
  n = 30,
  B = 1000,
  seed = 1
)

pshapiro(
  0.95,
  n = 30,
  B = 1000,
  seed = 2
)

pshapiro(
  0.95,
  n = 30,
  B = 1000,
  seed = 3
)

The answers will vary slightly.

Now increase B:

pshapiro(
  0.95,
  n = 30,
  B = 100000,
  seed = 1
)

The estimate becomes more stable.

35. A faster approach: simulate once and reuse

The functions above regenerate the null distribution every time. This is useful pedagogically, but inefficient.

For repeated calculations, generate the distribution once:

set.seed(123)

Wnull30 <- rshapiro(
  N = 100000,
  n = 30
)

Then use it directly.

p-function

mean(
  Wnull30 <= 0.95
)

q-function

quantile(
  Wnull30,
  0.05
)

d-function

d <- density(
  Wnull30,
  from = 0,
  to = 1
)

approx(
  d$x,
  d$y,
  xout = 0.95
)$y

This is dramatically faster when many calculations are needed.

36. Create a reusable Shapiro distribution object

We can take this idea one step further.

make_shapiro_distribution <- function(
  n,
  B = 100000,
  seed = NULL
) {

  if (!is.null(seed))
    set.seed(seed)

  W <- rshapiro(
    N = B,
    n = n
  )

  density_object <-
    density(
      W,
      from = 0,
      to = 1
    )

  result <- list(
    n = n,
    B = B,
    W = W,
    density = density_object
  )

  class(result) <-
    "shapiro_distribution"

  return(result)
}

Create one:

SW30 <-
  make_shapiro_distribution(
    n = 30,
    B = 100000,
    seed = 123
  )

37. Use the stored distribution

Cumulative probability

mean(
  SW30$W <= 0.95
)

Critical value

quantile(
  SW30$W,
  0.05
)

Density

approx(
  SW30$density$x,
  SW30$density$y,
  xout = 0.95
)$y

38. Why this exercise is statistically useful

Building these functions reveals something deeper about hypothesis testing.

Every classical test requires:

  1. a test statistic;
  2. a null distribution for that statistic;
  3. an observed statistic;
  4. a tail probability.

For Shapiro-Wilk:

Data
↓
Wobserved
↓
Compare with null distribution of W
↓
P(W ≤ Wobserved)
↓
p-value

39. The same idea appears in many statistical tests

For a t-test:

test statistic → t distribution → p-value

For a chi-square test:

test statistic → chi-square distribution → p-value

For ANOVA:

F statistic → F distribution → p-value

For Shapiro-Wilk:

W statistic → W null distribution → p-value

The only major difference is that the W distribution is more complicated and depends explicitly on sample size.

40. Final perspective

Base R does not provide:

dshapiro()
pshapiro()
qshapiro()
rshapiro()

because the Shapiro-Wilk statistic does not belong to a simple named probability family with a convenient closed-form density.

But simulation allows us to construct all four operations.

rshapiro()
simulate W under normality

pshapiro()
estimate P(W ≤ w)

qshapiro()
find the W corresponding to a chosen probability

dshapiro()
estimate the local density of W

This exercise also exposes the machinery hidden underneath a hypothesis test.

The p-value returned by:

shapiro.test(x)

is not a mysterious number produced by software. Conceptually, it answers a very concrete question:

If the observations really came from a normal population, how often would samples of this size produce a Shapiro-Wilk statistic at least this far into the lower tail?

Monte Carlo simulation lets us watch that probability emerge directly from repeated random experiments.

And that is one of the most useful bridges between probability theory and statistical inference:

probability distribution → random experiment → test statistic → sampling distribution → p-value
```

Sunday, November 8, 2026

Understanding the Shapiro-Wilk Test: Normality, the W Statistic, R Implementation, Confidence Intervals, and Tests for Other Distributions

Many familiar statistical procedures begin with an assumption that is easy to write down but surprisingly subtle to check:

X ~ N(μ, σ2)

In words, we assume that the observations, errors, or residuals come from a normal distribution.

The Shapiro-Wilk test is one of the most widely used formal tests of this assumption. It asks:

If these observations really came from a normal distribution, would their ordered values look approximately the way ordered observations from a normal distribution should look?

Behind that simple question sits an elegant statistic called W.

1. Why test for normality?

The normal distribution appears throughout classical statistics, including:

  • one-sample t-tests;
  • two-sample t-tests;
  • analysis of variance;
  • linear regression;
  • confidence intervals for means;
  • many parametric statistical models.

However, an important distinction is often missed. In regression and ANOVA, we generally do not require the raw response variable itself to be normally distributed. Instead, the assumption usually concerns the errors or residuals.

For example:

Yi = β0 + β1Xi + εi

with the assumption:

εi ~ N(0, σ2)

Therefore, applying shapiro.test() mechanically to every raw variable in a dataset is usually not good statistical practice.

2. A brief history of the Shapiro-Wilk test

The test was introduced by Samuel S. Shapiro and Martin B. Wilk in 1965 in their influential paper:

Shapiro SS, Wilk MB. An analysis of variance test for normality (complete samples). Biometrika. 1965;52(3-4):591-611.

The test became popular because it showed strong power against many forms of non-normality.

Later, Patrick Royston developed computational approximations that allowed the test to be applied efficiently to larger datasets. Modern statistical software, including R, uses algorithms derived from this work.

3. The hypotheses

The null hypothesis is:

H0: The sample is drawn from a normal distribution.

The alternative hypothesis is:

HA: The sample is not drawn from a normal distribution.

Notice that the test does not ask whether the mean is zero or whether the variance is one. It tests the shape of the distribution.

For example, all of the following are normal distributions:

N(0,1)
N(100,25)
N(-500,10000)

4. The Shapiro-Wilk statistic

Suppose we observe:

x1, x2, ..., xn

First arrange them in ascending order:

x(1) ≤ x(2) ≤ ... ≤ x(n)

The Shapiro-Wilk statistic is:

W = [( Σi=1n aix(i) )2] / [ Σi=1n (xi - x̄)2 ]

where:

  • x(i) is the i-th ordered observation;
  • x̄ is the sample mean;
  • ai are special coefficients derived from expected order statistics of a normal distribution.

5. What are the ai coefficients?

Imagine repeatedly drawing samples of size n from a standard normal distribution:

N(0,1)

For each sample, sort the observations. After many repetitions, we can determine the expected smallest value, expected second-smallest value, and so forth.

These are called expected normal order statistics.

The Shapiro-Wilk coefficients are constructed from these expected order statistics and their covariance structure.

Conceptually, the test compares:

the pattern of the ordered observed data

with:

the pattern expected if the data truly came from a normal distribution.

6. Understanding the numerator

The numerator is:

( Σ aix(i) )2

It measures how strongly the ordered observations agree with the ordering expected under normality.

Departures such as the following tend to reduce this agreement:

  • strong skewness;
  • heavy tails;
  • extreme outliers;
  • multimodality;
  • truncation.

7. Understanding the denominator

The denominator is:

Σ(xi - x̄)2

This is simply the total variability around the sample mean.

Recall:

s2 = Σ(xi - x̄)2 / (n - 1)

Therefore:

Σ(xi - x̄)2 = (n - 1)s2

8. How should W be interpreted?

Values of W close to 1 indicate that the ordering of the observations closely resembles what would be expected under a normal distribution.

W ≈ 1    →    data are highly compatible with normality

Smaller values indicate stronger deviations from normality.

However, there is no universal cutoff such as:

W < 0.95 means the data are non-normal.

The null distribution of W depends on sample size. This is why the p-value is used.

9. Running the Shapiro-Wilk test in R

# Make the simulation reproducible
set.seed(123)

# Generate 30 observations from a normal distribution
x <- rnorm(
  n = 30,
  mean = 50,
  sd = 10
)

# Perform the Shapiro-Wilk test
shapiro.test(x)

A typical output is:

Shapiro-Wilk normality test

data:  x
W = 0.97...
p-value = 0....

10. Interpreting the p-value

Suppose:

W = 0.976
p-value = 0.72

Using:

α = 0.05

we have:

p > 0.05

We therefore fail to reject the null hypothesis.

A suitable interpretation is:

There is insufficient evidence to conclude that the data depart from normality.

Avoid saying:

The data are normally distributed.

A non-significant test does not prove that the population is normal.

11. Example with clearly non-normal data

set.seed(123)

# Generate right-skewed exponential data
x_exp <- rexp(
  n = 50,
  rate = 1
)

# Test normality
shapiro.test(x_exp)

Because the exponential distribution is strongly right-skewed, the test will generally return a smaller W and a small p-value.

12. Always inspect a Q-Q plot

qqnorm(x)
qqline(x)

A normal Q-Q plot compares the observed sample quantiles with theoretical normal quantiles.

If the data are approximately normal, the points should lie close to a straight line.

13. Why sample size matters

Small samples

With a sample such as n = 8, even fairly substantial departures from normality may not be detected because the test has limited power.

Large samples

With a sample such as n = 2000, tiny departures from perfect normality can produce extremely small p-values.

Therefore:

Statistical evidence against exact normality does not automatically mean that a parametric statistical method is inappropriate.

14. Demonstrating sample-size effects in R

set.seed(100)

# Slightly skewed distribution
small_sample <- rgamma(
  20,
  shape = 20,
  rate = 1
)

large_sample <- rgamma(
  2000,
  shape = 20,
  rate = 1
)

shapiro.test(small_sample)

shapiro.test(large_sample)

Both samples come from the same non-normal population, but the larger sample has much greater power to detect the deviation.

15. Understanding the d, p, q and r functions in R

Most probability distributions in R have four related functions:

Prefix Meaning Normal example
d Density or probability mass dnorm()
p Cumulative probability pnorm()
q Quantile qnorm()
r Random generation rnorm()

The Shapiro-Wilk test itself does not have standard Base R functions named:

dshapiro()
pshapiro()
qshapiro()
rshapiro()

Instead, shapiro.test() internally calculates W and its p-value.

16. dnorm(): the normal density

The normal probability density function is:

f(x) = [1 / (σ√(2π))] × exp[-(x - μ)2 / (2σ2)]

In R:

dnorm(
  0,
  mean = 0,
  sd = 1
)

This gives approximately:

0.3989423

This value is a density, not the probability that X equals zero.

For a continuous distribution:

P(X = 0) = 0

17. Writing our own dnorm()

my_dnorm <- function(x, mean = 0, sd = 1) {

  # Standard deviation must be positive
  if (sd <= 0)
    stop("sd must be greater than zero")

  # Standardise x
  z <- (x - mean) / sd

  # Normal probability density
  density <-
    (1 / (sd * sqrt(2 * pi))) *
    exp(-0.5 * z^2)

  return(density)
}

Compare with Base R:

my_dnorm(0)
dnorm(0)

my_dnorm(
  10,
  mean = 5,
  sd = 2
)

dnorm(
  10,
  mean = 5,
  sd = 2
)

18. pnorm(): cumulative probability

The cumulative distribution function is:

F(x) = P(X ≤ x)

For example:

pnorm(1.96)

returns approximately:

0.975

Therefore:

P(Z ≤ 1.96) ≈ 0.975

Similarly:

pnorm(-1.96)

is approximately:

0.025

Hence:

P(-1.96 < Z < 1.96) ≈ 0.95

In R:

pnorm(1.96) - pnorm(-1.96)

19. Writing our own pnorm()

The normal cumulative distribution function does not have a simple elementary antiderivative, but it can be calculated numerically.

my_pnorm_one <- function(q, mean = 0, sd = 1) {

  if (sd <= 0)
    stop("sd must be greater than zero")

  answer <- integrate(
    f = function(x) {
      my_dnorm(
        x,
        mean = mean,
        sd = sd
      )
    },
    lower = -Inf,
    upper = q
  )

  return(answer$value)
}

Test it:

my_pnorm_one(1.96)
pnorm(1.96)

A vectorised version:

my_pnorm <- function(q, mean = 0, sd = 1) {

  sapply(
    q,
    my_pnorm_one,
    mean = mean,
    sd = sd
  )
}

20. qnorm(): the quantile function

The quantile function performs the reverse operation of the CDF.

For example:

qnorm(0.975)

returns approximately:

1.96

In mathematical terms:

F-1(0.975) ≈ 1.96

21. Writing our own qnorm()

my_qnorm_one <- function(
  p,
  mean = 0,
  sd = 1
) {

  if (p <= 0 || p >= 1)
    stop("p must lie strictly between 0 and 1")

  if (sd <= 0)
    stop("sd must be greater than zero")

  objective <- function(x) {

    my_pnorm_one(
      x,
      mean = mean,
      sd = sd
    ) - p
  }

  lower <- mean - 10 * sd
  upper <- mean + 10 * sd

  root <- uniroot(
    objective,
    interval = c(lower, upper)
  )

  return(root$root)
}

Compare:

my_qnorm_one(0.975)
qnorm(0.975)

22. rnorm(): generating normal random variables

Base R generates random normal observations using:

rnorm(10)

or:

rnorm(
  n = 100,
  mean = 50,
  sd = 10
)

A classical way to generate normally distributed values is the Box-Muller transformation.

Suppose U1 and U2 are independent Uniform(0,1) random variables.

Then:

Z1 = √[-2 ln(U1)] cos(2πU2)
Z2 = √[-2 ln(U1)] sin(2πU2)

Both Z1 and Z2 follow the standard normal distribution.

23. Writing our own rnorm() using Box-Muller

my_rnorm <- function(
  n,
  mean = 0,
  sd = 1
) {

  if (n < 1)
    return(numeric(0))

  if (sd < 0)
    stop("sd must be non-negative")

  # Box-Muller generates values in pairs
  m <- ceiling(n / 2)

  # Generate independent uniforms
  u1 <- runif(m)
  u2 <- runif(m)

  # Protect against log(0)
  u1[u1 == 0] <-
    .Machine$double.xmin

  # Box-Muller transformation
  z1 <-
    sqrt(-2 * log(u1)) *
    cos(2 * pi * u2)

  z2 <-
    sqrt(-2 * log(u1)) *
    sin(2 * pi * u2)

  # Combine
  z <- c(z1, z2)

  # Keep requested number
  z <- z[seq_len(n)]

  # Convert to N(mean, sd^2)
  x <- mean + sd * z

  return(x)
}

Test it:

set.seed(42)

x <- my_rnorm(
  n = 10000,
  mean = 50,
  sd = 10
)

mean(x)
sd(x)

24. The d-p-q-r pattern across R distributions

Distribution d p q r
Normal dnorm pnorm qnorm rnorm
Binomial dbinom pbinom qbinom rbinom
Poisson dpois ppois qpois rpois
Exponential dexp pexp qexp rexp
Gamma dgamma pgamma qgamma rgamma
Beta dbeta pbeta qbeta rbeta
Uniform dunif punif qunif runif
Weibull dweibull pweibull qweibull rweibull

25. Does the Shapiro-Wilk test have a confidence interval?

Normally, no.

shapiro.test() returns:

  • the W statistic;
  • a p-value;
  • the test name;
  • the data name.

It does not return a conventional confidence interval because W is a goodness-of-fit statistic rather than a simple biological parameter such as a mean or mean difference.

26. Confidence interval for the mean

If normality is reasonably plausible, a confidence interval for the population mean can be calculated using the t distribution.

x̄ ± t0.975,n-1 (s / √n)

In R:

set.seed(10)

x <- rnorm(
  30,
  mean = 100,
  sd = 15
)

n <- length(x)
xbar <- mean(x)
s <- sd(x)

alpha <- 0.05

critical_t <- qt(
  1 - alpha / 2,
  df = n - 1
)

margin <-
  critical_t *
  s / sqrt(n)

lower <- xbar - margin
upper <- xbar + margin

c(
  mean = xbar,
  lower_95 = lower,
  upper_95 = upper
)

Compare with:

t.test(x)

27. Confidence interval for the variance

For normally distributed data:

[(n - 1)S2] / σ2 ~ χ2n-1

The confidence interval for the variance is:

Lower = (n - 1)s2 / χ20.975,n-1
Upper = (n - 1)s2 / χ20.025,n-1
variance_ci <- function(
  x,
  conf.level = 0.95
) {

  x <- x[!is.na(x)]

  n <- length(x)

  if (n < 2)
    stop(
      "At least two observations are required"
    )

  s2 <- var(x)

  alpha <- 1 - conf.level
  df <- n - 1

  lower <-
    df * s2 /
    qchisq(
      1 - alpha / 2,
      df = df
    )

  upper <-
    df * s2 /
    qchisq(
      alpha / 2,
      df = df
    )

  return(
    c(
      variance = s2,
      lower = lower,
      upper = upper
    )
  )
}

28. Simulating the null distribution of W

A useful teaching exercise is to simulate what values of W occur when the null hypothesis is actually true.

simulate_W_null <- function(
  n,
  B = 5000
) {

  W <- numeric(B)

  for (b in seq_len(B)) {

    # Generate a sample under H0
    x <- rnorm(n)

    # Calculate W
    W[b] <-
      unname(
        shapiro.test(x)$statistic
      )
  }

  return(W)
}

Run:

set.seed(123)

W_null <- simulate_W_null(
  n = 30,
  B = 5000
)

hist(
  W_null,
  breaks = 40,
  main = "Null distribution of Shapiro-Wilk W",
  xlab = "W"
)

This demonstrates why the same W value cannot be interpreted identically for every sample size.

29. Empirical critical value

quantile(
  W_null,
  probs = 0.05
)

This gives an approximate 5% lower-tail critical value for that particular sample size.

30. Empirical p-value

W_obs <-
  unname(
    shapiro.test(x)$statistic
  )

p_empirical <-
  (sum(W_null <= W_obs) + 1) /
  (length(W_null) + 1)

p_empirical

31. Comparable tests for normality

Shapiro-Francia test

The Shapiro-Francia test is closely related to the Shapiro-Wilk test and compares observed order statistics with expected normal order statistics.

Anderson-Darling test

The Anderson-Darling test compares an empirical distribution with a theoretical distribution and gives relatively greater weight to the tails.

Conceptually:

A2 = -n - (1/n) Σ (2i - 1) [ ln F(x(i)) + ln(1 - F(x(n+1-i))) ]

It can be adapted to normal, exponential, Weibull and other distributions.

Kolmogorov-Smirnov test

The K-S statistic is:

D = sup |Fn(x) - F0(x)|

It measures the largest vertical difference between the empirical CDF and the theoretical CDF.

Example:

x <- rnorm(50)

ks.test(
  x,
  "pnorm",
  mean = 0,
  sd = 1
)

A crucial warning: the classical K-S test assumes that the theoretical distribution and its parameters were specified independently of the data.

Cramér-von Mises test

The Cramér-von Mises approach considers the overall squared discrepancy between the empirical and theoretical cumulative distributions.

W2 = n ∫ [Fn(x) - F0(x)]2 dF0(x)

Jarque-Bera test

The Jarque-Bera test focuses on skewness and kurtosis.

JB = (n / 6) [ S2 + (K - 3)2 / 4 ]

For a normal distribution:

Skewness = 0
Kurtosis = 3

32. Testing whether data follow an exponential distribution

For:

X ~ Exponential(λ)

R provides:

dexp()
pexp()
qexp()
rexp()

Example:

set.seed(123)

x <- rexp(
  100,
  rate = 0.5
)

ks.test(
  x,
  "pexp",
  rate = 0.5
)

If the rate parameter is estimated from the same data, the ordinary K-S p-value should not be interpreted directly.

33. Parametric bootstrap for exponential goodness-of-fit

exponential_gof <- function(
  x,
  B = 5000
) {

  x <- x[!is.na(x)]

  n <- length(x)

  if (any(x < 0))
    stop(
      "Exponential observations must be non-negative"
    )

  # Maximum-likelihood estimate
  lambda_hat <- 1 / mean(x)

  # Observed KS statistic
  D_obs <-
    unname(
      ks.test(
        x,
        "pexp",
        rate = lambda_hat
      )$statistic
    )

  D_sim <- numeric(B)

  for (b in seq_len(B)) {

    # Generate under fitted null
    xb <- rexp(
      n,
      rate = lambda_hat
    )

    # Re-estimate rate
    lambda_b <- 1 / mean(xb)

    # Calculate simulated statistic
    D_sim[b] <-
      unname(
        ks.test(
          xb,
          "pexp",
          rate = lambda_b
        )$statistic
      )
  }

  p_value <-
    (sum(D_sim >= D_obs) + 1) /
    (B + 1)

  return(
    list(
      rate_estimate = lambda_hat,
      statistic = D_obs,
      p.value = p_value
    )
  )
}

34. Testing a uniform distribution

set.seed(10)

x <- runif(
  50,
  min = 0,
  max = 1
)

ks.test(
  x,
  "punif",
  min = 0,
  max = 1
)

35. Testing lognormality

A useful identity is:

X is lognormal ⇔ log(X) is normal

Therefore:

shapiro.test(
  log(x)
)

can provide a simple diagnostic for lognormality.

36. Testing Poisson data

Poisson data are discrete, so the Shapiro-Wilk test is inappropriate.

For:

X ~ Poisson(λ)

R provides:

dpois()
ppois()
qpois()
rpois()

Example:

set.seed(10)

x <- rpois(
  200,
  lambda = 3
)

lambda_hat <- mean(x)

observed <- table(x)

observed

Observed and expected frequency distributions can then be compared using chi-square or simulation-based goodness-of-fit procedures.

37. Testing binomial data

For:

X ~ Binomial(m,p)

R provides:

dbinom()
pbinom()
qbinom()
rbinom()

Observed frequencies for 0, 1, ..., m successes can be compared against the corresponding binomial probabilities.

38. Testing a Weibull distribution

The Weibull distribution is widely used in survival analysis and reliability modelling.

R provides:

dweibull()
pweibull()
qweibull()
rweibull()

The Anderson-Darling test is often particularly useful for Weibull models because tail behaviour can be scientifically important.

39. Which goodness-of-fit test should be used?

Question Useful approach
Are continuous data normal? Shapiro-Wilk + Q-Q plot
Is normal tail fit especially important? Anderson-Darling
Does an empirical CDF match a fully specified distribution? Kolmogorov-Smirnov
Want sensitivity across the whole CDF? Cramér-von Mises
Interested primarily in skewness and kurtosis? Jarque-Bera
Normal parameters estimated from the sample? Shapiro-Wilk or Lilliefors
Lognormality? Shapiro-Wilk on log(x)
Exponentiality? Anderson-Darling or bootstrap GOF
Weibull fit? Anderson-Darling or bootstrap GOF
Poisson or binomial distribution? Chi-square or simulation-based GOF
Arbitrary fitted distribution? Parametric bootstrap

40. Why histograms alone are not enough

set.seed(10)

x <- rnorm(25)

hist(x)

With small samples, changing the number of histogram bins can make the same data appear bell-shaped, skewed, bimodal or irregular.

For evaluating normality, a Q-Q plot is generally more informative.

41. Why Shapiro-Wilk alone is not enough

x <- c(
  rnorm(99),
  10
)

shapiro.test(x)

This sample will probably fail the normality test because of one extreme observation.

However, the scientifically important question may be whether that value represents:

  • a measurement error;
  • a data-entry error;
  • a genuine biological observation;
  • a different population;
  • or another source of heterogeneity.

A normality test cannot distinguish these possibilities.

42. Normality is often less important than students are taught

A common but oversimplified workflow is:

Shapiro-Wilk significant
↓
data non-normal
↓
t-test forbidden

This is not generally correct.

The t-test can be reasonably robust to moderate departures from normality, particularly when:

  • sample sizes are reasonably large;
  • group sizes are balanced;
  • there are no extreme outliers.

Conversely, obtaining p > 0.05 from a Shapiro-Wilk test with n = 6 provides very little evidence that the underlying population is actually normal.

43. The key conceptual idea

The Shapiro-Wilk test is not merely asking:

Does the histogram look bell-shaped?

Its deeper question is:

Do the ordered observations behave the way order statistics from a normal distribution should behave?

That is why the statistic is built around:

x(1), x(2), ..., x(n)

and coefficients derived from the expected order statistics of a normal distribution.

44. Final perspective

The Shapiro-Wilk statistic has the compact form:

W = [( Σ aix(i) )2] / [ Σ(xi - x̄)2 ]

But behind this formula lies a sophisticated idea: compare the geometry of the ordered observations with the geometry expected from normal order statistics.

A small W indicates disagreement. The p-value tells us how surprising that disagreement would be if normality were true.

Neither replaces looking at the data.

The strongest workflow is:

scientific context → plot the data → Q-Q plot → formal test → evaluate practical importance

The same general idea extends beyond normality. Exponential, Weibull, lognormal, Poisson, binomial and many other probability models can be evaluated by asking:

What should the observations look like under the proposed model, and how different are the observed data from that expectation?

References

  1. Shapiro SS, Wilk MB. An analysis of variance test for normality (complete samples). Biometrika. 1965;52(3-4):591-611. DOI: 10.1093/biomet/52.3-4.591.
  2. Royston JP. An extension of Shapiro and Wilk's W test for normality to large samples. Applied Statistics. 1982;31(2):115-124.
  3. Royston P. Remark AS R94: A remark on Algorithm AS 181: The W-test for normality. Applied Statistics. 1995;44(4):547-551.
  4. Stephens MA. EDF statistics for goodness of fit and some comparisons. Journal of the American Statistical Association. 1974;69:730-737.