<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The DO Loop</title>
	<atom:link href="https://blogs.sas.com/content/iml/feed" rel="self" type="application/rss+xml" />
	<link>https://blogs.sas.com/content/iml/</link>
	<description>Statistical programming in SAS with an emphasis on SAS/IML programs</description>
	<lastBuildDate>Mon, 23 Nov 2026 14:53:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6</generator>
	<item>
		<title>Call a PROC IML function from the DATA step in SAS</title>
		<link>https://blogs.sas.com/content/iml/2026/11/23/call-iml-from-fcmp.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/11/23/call-iml-from-fcmp.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 23 Nov 2026 10:21:12 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[SAS Programming]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60635</guid>

					<description><![CDATA[<p>The SAS DATA step is a flexible computational tool. The DATA step supports hundreds of built-in functions that enable you to implement many algorithms in computational statistics. In addition, the FCMP procedure enables you to create new functions and store them in a library. You can use PROC FCMP to [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/23/call-iml-from-fcmp.html">Call a PROC IML function from the DATA step in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>

The SAS DATA step is a flexible computational tool. The DATA step supports hundreds of built-in functions that enable you 
to implement many algorithms in computational statistics. In addition, <a href="https://blogs.sas.com/content/iml/2012/04/18/extending-sas-how-to-define-new-functions-in-proc-fcmp-and-sasiml-software.html">the FCMP procedure</a> 
enables you to create new functions and store them in a library. You can use PROC FCMP to extend the built-in capabilities of the SAS DATA step.
These user-defined functions
can also be called in <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/proc/n0pio2crltpr35n1ny010zrfbvc9.htm">CMP-enabled statistical procedures such as PROC NLIN, PROC NLMIXED, and PROC MCMC</a>.
</p><p>
However, the DATA step processes one observation at a time, so some computations are easier to compute by using procedures.
These include matrix computations, root-finding algorithms, integrals and derivatives, differential equations, 
optimization, and other techniques in numerical analysis.
For those computations, SAS provides PROC IML, which is a high-level programming language for advanced computations.
A PROC IML program can call hundreds of built-in routines (as well as the functions in Base SAS), and you can define and store 
user-defined functions that implement advanced algorithms.
</p>
<p>
This article shows a powerful way to combine these tools.
It shows how to call PROC IML from within a PROC FCMP function. This means that PROC IML computations
can be made available to the DATA step and to CMP-enabled statistical procedures.  In fact, more is true: you can 
follow the steps in this article to call ANY SAS procedure from within a PROC FCMP function!
</p>

<h3>Motivation: Call PROC IML from a function defined in PROC FCMP</h3>
<p>
This article is motivated by a question from a SAS programmer.
After reading my recent article about <a href="https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html">how to 
implement the PDF of the generalized inverse Gaussian distribution (GIG) in PROC IML</a>,
the programmer asked whether it is possible to implement the log-likelihood function in PROC FCMP so that he could call it from CMP-enabled procedures.
I initially replied "no," because the GIG distribution requires 
<a href="https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html">computing a Bessel function</a>.
The Bessel function requires performing a 
numerical integration, so the computation must be performed by using PROC IML.
</p>
<p>
However, as I show in the subsequent sections, you can wrap the IML computation in a macro and then use <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/proc/n19ylmyrvhp7y6n1889zmwsv9nuh.htm">the RUN_MACRO function in PROC FCMP</a> to call the macro. 
This macro has to adhere to certain conventions, and the resulting computation is not very efficient, but
the RUN_MACRO function does enable you to call PROC IML to compute any result, then pass that result back to an FCMP function.
Since an FCMP function can be called by the DATA step or by any CMP-enabled statistical procedure, this makes the power of PROC IML
available these procedures.
</p>


<h3>How can you call PROC IML from the DATA step?</h3>
<p>
A previous article shows how to 
<a href="https://blogs.sas.com/content/iml/2012/04/18/extending-sas-how-to-define-new-functions-in-proc-fcmp-and-sasiml-software.html">create user-defined 
functions in the FCMP procedure and in PROC IML</a>.
The example in that article is the 'SafeLog' function: A function that returns the logarithm of a number if the number is positive and returns
a missing value otherwise.  I showed how to implement the function in PROC FCMP and in PROC IML.
</p>
<p>
Although there is no need to call the IML version of SafeLog function from the DATA step, we can use this simple example 
to illustrate the main steps. The steps are:
</p>
<ol>
<li>Create a macro "function" that wraps a PROC IML computation. The macro must not have any arguments.
It must use macro variables that are in the GLOBAL symbol table as the input arguments for the computation.
The macro must write the result of a computation to another global macro variable.
</li>
<li>
Use PROC FCMP to define a function. The input values are local variables that 
must have exactly the same names as the macro variables used in the macro.
Inside the function, use the RUN_MACRO function to call the macro "function" that invokes PROC IML. 
List the input variables and the output variable on the argument list for the RUN_MACRO function.
When the RUN_MACRO function is called, SAS will copy the values of all arguments to macro variables that have the same name.
Those will be the input arguments. After the macro executes, SAS will copy the macro values into the FCMP variables.
That is how you can get the output value(s).
</li>
<li>
Call the FCMP function from the DATA step or from a CMP-enabled procedure.
</li>
</ol>

<h3>A simple example of calling PROC IML from the DATA step</h3>
<p>
Let's implement these three steps for the 'SafeLog' function. The previous article showed how to implement the function in PROC IML.
The first step is to 
put the definition inside a macro (which I call 'SafeLog_IML') and call the IML function for the input arguments. Then, 
<a href="https://blogs.sas.com/content/iml/2011/10/17/does-symput-work-in-iml.html">use CALL SYMPUTX to write the output value to a macro variable</a>,
as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* 1. Define a macro that takes a scalar value and returns SafeLog(Y) in a macro variable.
   The input macro variable is &amp;safeLog_Y.
   The output macro variable is &amp;safeLog_result */</span>
<span style="color: #0000ff;">%macro</span> SafeLog_IML;   <span style="color: #006400; font-style: italic;">/* do not use arg list; read and write global macro variables */</span>
<span style="color: #0000ff;">%global</span> safeLog_Y;       <span style="color: #006400; font-style: italic;">/* INPUT variable is named 'safeLog_Y' */</span>
<span style="color: #0000ff;">%global</span> safeLog_result;  <span style="color: #006400; font-style: italic;">/* OUTPUT variable is named 'safeLog_result' */</span>
&nbsp;
<span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* Define a function for a scalar argument, Y.
   If Y&gt;0, return the natural log of Y, otherwise return a missing value  */</span>
start SafeLog<span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> Y&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">log</span><span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> . <span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* call the function on the input argument */</span>
Y = <span style="color: #0000ff; font-weight: bold;">&amp;safeLog_Y</span>;       <span style="color: #006400; font-style: italic;">/* assign INPUT value */</span>
LogY = SafeLog<span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> symputx<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'safeLog_result'</span>, LogY, <span style="color: #a020f0;">'G'</span><span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* assign OUTPUT value */</span>
<span style="color: #000080; font-weight: bold;">QUIT</span>;
<span style="color: #0000ff;">%mend</span>  SafeLog_IML;</pre></td></tr></table></div>




<p>
You can test whether the macro works by calling it in SAS. Use the %LET statement to define the input variable and use the %PUT statement 
to examine the value of the output variable:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #0000ff;">%let</span> safeLog_Y = <span style="color: #2e8b57; font-weight: bold;">100</span>;
%SafeLog_IML;
<span style="color: #0000ff;">%put</span> &amp;=safeLog_result;</pre></td></tr></table></div>





<div class="wp_syntax"><table><tr><td class="code"><pre class="text" style="font-family:monospace;">SAFELOG_RESULT=4.605170186</pre></td></tr></table></div>




<p>
The output value is log(100) = 4.6051..., so the macro is correctly calling the PROC IML function.
Notice, however, that the macro variable (which is displayed to full precision because it is a text string) 
appears to have 10 digits of precision. That is because <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/mcrolref/p09y28i2d1kn8qn1p1icxchz37p3.htm">the CALL SYMPUTX subroutine 
converts a numeric variable to a string by using the BEST12. format</a>.
This might cause a loss of precision for some numerical applications. Accordingly, the documentation suggests using the PUTN function to 
format the numeric variable to a higher precision. If you go back and modify the macro to use
<br />
&nbsp;&nbsp;&nbsp;&nbsp;
call symputx('safeLog_result', <strong>putn(LogY,'BEST32.')</strong>, 'G');  /* assign OUTPUT value at higher precision */
<br />
then the output macro variable will be sure to contain the full precision of the numeric variable.
</p>

<p>
The second step is to define a PROC FCMP function that calls the SafeLog_IML macro. This is done by using the following program:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc fcmp</span> outlib=work.funcs.MathFuncs;
<span style="color: #006400; font-style: italic;">/* Define the function by calling a macro that calls PROC IML.
   The input and output variables are passed via macro variables.
   The names of the input and output variables MUST match the names of macro variables
   used in the macro call!  */</span>
function SafeLog_IML<span style="color: #66cc66;">&#40;</span>y<span style="color: #66cc66;">&#41;</span>;
   safeLog_Y = y;        <span style="color: #006400; font-style: italic;">/* copy to INPUT name */</span>
   rc = run_macro<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;SafeLog_IML&quot;</span>, safeLog_Y, safeLog_result<span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* safeLog_result is OUTPUT */</span>
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> ifn<span style="color: #66cc66;">&#40;</span>rc=<span style="color: #2e8b57; font-weight: bold;">0</span>, safelog_result, .<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
endsub;
<span style="color: #000080; font-weight: bold;">run</span>;
<span style="color: #000080; font-weight: bold;">quit</span>;</pre></td></tr></table></div>




<p>
Notice an important detail: The FCMP function has two local variables (safeLog_Y and safeLog_result) that are part of the RUN_MACRO call.
Every time that the SafeLog_IML function is called, SAS copies the values of the arguments into global macro variables that 
have the same names. Then SAS calls the macro. Finally, SAS copies the macro values back to the local variables in FCMP.
The return value of the RUN_MACRO function is a flag that indicates whether the macro ran successfully.
</p><p>
The third step is to call the new SafeLog_IML function from the DATA step. Be sure to use the CMPLIB= option to tell the DATA step where to look for user-defined functions,
as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #0000ff;">options</span> cmplib=work.funcs;  <span style="color: #006400; font-style: italic;">/* define location of FCMP function */</span>
<span style="color: #006400; font-style: italic;">/* call the new CMP function */</span>
<span style="color: #000080; font-weight: bold;">data</span> A;
<span style="color: #0000ff;">input</span> <span style="color: #0000ff;">x</span> @@;
y_Correct = ifn<span style="color: #66cc66;">&#40;</span>x&gt;<span style="color: #2e8b57; font-weight: bold;">0</span>, <span style="color: #0000ff;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, .<span style="color: #66cc66;">&#41;</span>;
y_IML     = SafeLog_IML<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>; 
datalines;
-<span style="color: #2e8b57; font-weight: bold;">3</span> <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #2e8b57; font-weight: bold;">2</span> . <span style="color: #2e8b57; font-weight: bold;">5</span> <span style="color: #2e8b57; font-weight: bold;">10</span> <span style="color: #2e8b57; font-weight: bold;">100</span> 
;
&nbsp;
<span style="color: #000080; font-weight: bold;">proc print</span> <span style="color: #000080; font-weight: bold;">data</span>=A; 
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<img decoding="async" src="https://blogs.sas.com/content/iml/files/2026/11/FCMPCallIML1.png" alt="" width="205" height="228" class="alignnone size-full wp-image-60643" />

<p>
The output shows the result of calling the macro (which, in turn, calls an IML function) for multiple input values. The 
variable y_Correct is the in-line DATA step computation. The variable y_IML shows the result of calling the IML function.
</p>


<h3>A more complicated example: Call IML to compute a Bessel function</h3>
<p>
Of course, it is completely unnecessary to call IML to evaluate a logarithm, so let's return to the problem that motivated this article:
<a href="https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html">call a function in IML to compute the modified Bessel function of the second kind</a>. 
</p>
<p>
<strong>Step 1:</strong> Define a macro function (with no arguments) that calls a PROC IML program. The program should evaluate the 
Bessel function at the values of the input arguments, then store the output value in a macro variable.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Macro for computing the Bessel function by using PROC IML. See
   https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html
   The answer is returned via the macro variable BesselK_result.
   You can use the PUTN function to ensure that you do not lose precision. */</span>
<span style="color: #0000ff;">%macro</span> BesselK;
<span style="color: #0000ff;">%global</span> BesselK_nu;      <span style="color: #006400; font-style: italic;">/* First INPUT variable */</span>
<span style="color: #0000ff;">%global</span> BesselK_x;       <span style="color: #006400; font-style: italic;">/* Second INPUT variable */</span>
<span style="color: #0000ff;">%global</span> BesselK_result;  <span style="color: #006400; font-style: italic;">/* OUTPUT variable */</span>
&nbsp;
<span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* Define the integrand function for the unscaled modified 
   Bessel function of the second kind, K_{nu}(x)
 */</span>
start BesselK_integ<span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_BessK_nu, g_BessK_x<span style="color: #66cc66;">&#41;</span>;
   nu = g_BessK_nu; <span style="color: #0000ff;">x</span> = g_BessK_x;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> t<span style="color: #006400; font-style: italic;">**(-nu - 1) * exp(   -t - (x**2)/(4*t)) );</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Define the wrapper function to compute a scalar result */</span>
start BesselK_func<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_BessK_nu, g_BessK_x<span style="color: #66cc66;">&#41;</span>;
   g_BessK_nu = nu;
   funcName = <span style="color: #a020f0;">&quot;BesselK_integ&quot;</span>;
   K = .;     <span style="color: #006400; font-style: italic;">/* Use missing value for domain error such as x &lt;= 0 */</span>
   tau = nu+<span style="color: #2e8b57; font-weight: bold;">1</span>;
   <span style="color: #0000ff;">if</span> <span style="color: #0000ff;">x</span> &gt; <span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">do</span>;
      g_BessK_x = <span style="color: #0000ff;">x</span>;
      <span style="color: #006400; font-style: italic;">/* Calculate the exact peak of the integrand */</span>
      pk = <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span>tau<span style="color: #006400; font-style: italic;">**2 + x**2) - tau) / 2;</span>
      <span style="color: #0000ff;">call</span> QUAD<span style="color: #66cc66;">&#40;</span>y, funcName, <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">0</span> .I<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span> PEAK=pk;
      K = <span style="color: #2e8b57; font-weight: bold;">0.5</span> <span style="color: #006400; font-style: italic;">* (x / 2)##nu # y;</span>
   <span style="color: #0000ff;">end</span>;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span>K<span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* get the global macro variable values */</span>
nu = <span style="color: #0000ff; font-weight: bold;">&amp;BesselK_nu</span>;
<span style="color: #0000ff;">x</span>  = <span style="color: #0000ff; font-weight: bold;">&amp;BesselK_x</span>;
K = BesselK_func<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> symputx<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'BesselK_result'</span>, <span style="color: #0000ff;">putn</span><span style="color: #66cc66;">&#40;</span>K,<span style="color: #a020f0;">'BEST32.'</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #a020f0;">'G'</span><span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* store the result in full precision in a macro variable */</span>
<span style="color: #000080; font-weight: bold;">QUIT</span>;
<span style="color: #0000ff;">%mend</span> BesselK;</pre></td></tr></table></div>




<p>
<strong>Step 2:</strong> Define an FCMP function, which uses the RUN_MACRO function to call the macro:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc fcmp</span> outlib=work.funcs.MathFuncs;
<span style="color: #006400; font-style: italic;">/* Surface the BesselK function by calling a macro that calls PROC IML.
   The names of the input and output variables must match the names of macro variables
   used in the macro call.  */</span>
function BesselK<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   BesselK_nu = nu;
   BesselK_x  = <span style="color: #0000ff;">x</span>;
   rc = run_macro<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;BesselK&quot;</span>, BesselK_nu, BesselK_x, BesselK_result<span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* BesselK_result is OUTPUT */</span>
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> ifn<span style="color: #66cc66;">&#40;</span>rc=<span style="color: #2e8b57; font-weight: bold;">0</span>, BesselK_result, .<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
endsub;
<span style="color: #000080; font-weight: bold;">run</span>;
<span style="color: #000080; font-weight: bold;">quit</span>;</pre></td></tr></table></div>




<p>
<strong>Step 3:</strong> Call the FCMP function in the DATA step for a range of input parameters:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #0000ff;">options</span> cmplib=work.funcs;  <span style="color: #006400; font-style: italic;">/* define location of FCMP function */</span>
<span style="color: #000080; font-weight: bold;">data</span> Bessel2;
<span style="color: #0000ff;">do</span> nu = <span style="color: #2e8b57; font-weight: bold;">0</span> to <span style="color: #2e8b57; font-weight: bold;">2</span>;
   <span style="color: #0000ff;">do</span> <span style="color: #0000ff;">x</span> = <span style="color: #2e8b57; font-weight: bold;">0</span> to <span style="color: #2e8b57; font-weight: bold;">2.5</span> <span style="color: #0000ff;">by</span> <span style="color: #2e8b57; font-weight: bold;">0.05</span>;
      K = BesselK<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">output</span>;
    <span style="color: #0000ff;">end</span>;
<span style="color: #0000ff;">end</span>;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<p>
To see whether the computation is correct, you can use PROC SGPLOT to visualize the Bessel function for several values of the parameters:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Modified Bessel Functions of the Second Kind&quot;</span>;
<span style="color: #000080; font-weight: bold;">proc sgplot</span> <span style="color: #000080; font-weight: bold;">data</span>=Bessel2;
   series <span style="color: #0000ff;">x</span>=<span style="color: #0000ff;">x</span> y=K / <span style="color: #0000ff;">group</span>=nu;
   xaxis grid;
   yaxis grid <span style="color: #0000ff;">label</span>=<span style="color: #a020f0;">&quot;BesselK(x; nu)&quot;</span> <span style="color: #0000ff;">max</span>=<span style="color: #2e8b57; font-weight: bold;">10</span>;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/11/FCMPCallIML2.png"><img fetchpriority="high" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/11/FCMPCallIML2.png" alt="SGPLOT curves of modified Bessel functions of the second kind for nu = 0, 1, 2" width="480" height="360" class="alignnone size-full wp-image-60644" srcset="https://blogs.sas.com/content/iml/files/2026/11/FCMPCallIML2.png 640w, https://blogs.sas.com/content/iml/files/2026/11/FCMPCallIML2-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
Success! The graph shows three Bessel functions for parameter values &nu; = 0, 1, and 2, and for x in the interval (0, 2.5].
Each point on a curve was computed by calling a function in PROC IML.
</p>


<h3>Drawbacks of RUN_MACRO</h3>
<p>
The RUN_MACRO function in PROC FCMP is not a panacea. It has a few shortcomings:
</p>
<ul>
<li>The macro that is called by RUN_MACRO cannot have an argument list. 
This means that you probably need to rewrite existing macros to eliminate the argument list and to access only GLOBAL macro variables.
</li>
<li>
All input values to the macro are provided through the GLOBAL macro symbol table.
The return value is also communicated by using a GLOBAL macro variable. To prevent naming conflicts, I suggest that you 
avoid macro names like x and y in favor of longer names whose prefix indicates the name of the macro. For example,
this article uses BesselK_nu, BesselK_x, and BesselK_result. </li>
<li>
The FCMP function will be slower than the IML function. In the example in this article,
the input and output values are scalar quantities, whereas PROC IML is most efficient when you vectorize the 
functions. In addition, every call to RUN_MACRO will start PROC IML, parse the program, define the function, call the function for one value,
and then exit the procedure. There is considerable overhead associated with each of these steps! 
Be smart: In applications such as computing 
with generalized inverse Gaussian distribution, the Bessel function is a constant that does not need to be evaluated for every observation, 
only once for each time you want to evaluate the PDF or the log-likelihood function.
</li>
</ul>


<h3>Summary</h3>
<p>
This article demonstrates a powerful computational method in SAS: You can define a function in PROC FCMP that calls a SAS procedure.
In particular, you can call any computation in PROC IML. The method is enabled by using the RUN_MACRO function in PROC FCMP, which enables you to 
call any SAS macro. The macro must use the global macro symbol table, but other than that you can call any SAS procedure or set of procedures.
Before the macro ends, it should write any results to macro variables. These values are then copied back into variables in the FCMP function,
which can perform additional computations (if necessary) and return one or more results. 
The FCMP function can be called by the DATA step or by any CMP-enabled procedure.
</p>


<h3>Further Reading</h3>
<ul>
<li>
Christian, S. and Rioux, J. (2010) <a href="http://support.sas.com/resources/papers/proceedings10/326-2010.pdf">"Adding Statistical Functionality to the DATA Step with PROC FCMP,"</a>
Proceedings of the SAS Global Forum 2010. 
</li>
<li>
SAS Technical Support (2010), <a href="https://support.sas.com/kb/40/592.html">"Calling a SAS procedure function from within another SAS procedure"</a>
</li>
</ul>

<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/23/call-iml-from-fcmp.html">Call a PROC IML function from the DATA step in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/11/23/call-iml-from-fcmp.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/11/FCMPCallIML2-150x150.png" />
	</item>
		<item>
		<title>Quantiles of the skew-normal distribution</title>
		<link>https://blogs.sas.com/content/iml/2026/11/16/quantiles-skew-normal.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/11/16/quantiles-skew-normal.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 10:29:00 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Numerical Analysis]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60616</guid>

					<description><![CDATA[<p>A previous article introduces the skew-normal distribution and shows how to use SAS to compute the skew-normal PDF, CDF, and random variates. The present article shows how to use the Cornish-Fisher expansion to quickly compute the quantiles of the skew-normal distribution. The method is very general: it can be used [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/16/quantiles-skew-normal.html">Quantiles of the skew-normal distribution</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
A previous article introduces <a href="https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html">the skew-normal distribution</a> 
and shows how to 
use SAS to compute the skew-normal PDF, CDF, and random variates.
The present article shows how to use the Cornish-Fisher expansion to quickly compute the quantiles of the skew-normal distribution.
The method is very general: it can be used to compute the quantiles for many continuous probability distributions for 
which you can compute the first four moments (mean, variance, skewness, and excess kurtosis).
</p>

<h3>Three types of computations for quantiles of distributions</h3>

<p>
For a continuous probability distribution, 
a quantile is the root of an integral equation. Specifically, for a probability, p, the quantile for p 
is the solution to the equation F(x) - p = 0, where F is the cumulative distribution function (CDF). In general, the CDF is defined as 
<br />
 F(<em>x</em>) = &int;<sup><em>x</em></sup> f(<em>t</em>) <em>dt</em>, where the lower limit of the integral is &ndash;&infin;.
</p>
<p>
In practice, <a href="https://blogs.sas.com/content/iml/2013/07/22/the-inverse-cdf-method.html">the best way to compute a quantile</a> 
depends on the complexity of the CDF. There are three cases:
</p>
<ol>
<li>The CDF is invertible. That means that you can write down an explicit formula for the inverse equation x = F<sup>-1</sup>(p). 
In this case, computing a quantile is trivial and efficient. An example is the exponential distribution.
The CDF is F(x) = 1 – exp(–x), which can be explicitly inverted (solved for x). The inverse CDF is x = –log(1–p).
</li>
<li>The CDF can be written explicitly as a formula, but it cannot be inverted analytically. 
In this case, it is fast to evaluate the CDF, but you need to use a root-finding method to find the quantile.
In SAS IML, <a href="https://blogs.sas.com/content/iml/2018/02/19/compute-quantiles-distribution.html">I use the FROOT function to solve for these types of quantiles</a>.
The FROOT function often converges super-linearly to a solution.
</li>
<li>
The CDF must be evaluated by computing an integral and cannot be inverted analytically.
In this case, it is expensive to evaluate the CDF, so you want to 
choose a root-finding algorithm that converges quickly.
The Newton-Raphson method converges quadratically if you can 
provide a good estimate of the root.
The skew-normal distribution falls into this class. The CDF requires computing an integral,
but we can use the Cornish-Fisher (C-F) expansion to obtain a good initial estimate of the quantile
so that Newton's method converges in few steps.
</li>
</ol>

<h3>Case Study: The quantiles of the skew-normal distribution</h3>
<p>
The skew-normal distribution is an example of Case 3. Thus, 
computing the quantiles of the skew-normal distribution requires three steps: 
</p>
<ol>
<li>
Write the functions that evaluate the C-F approximation of the quantiles.  The article,
<a href="https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html">"The Cornish-Fisher approximation to quantiles"</a> shows how to use SAS to implement the C-F approximation.
</li>
<li>
Write the functions to evaluate the PDF and CDF. The CDF might require performing a numerical integration. The article,
<a href="https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html">"Implement the skew-normal distribution in SAS"</a> shows how to compute the CDF of the skew-normal distribution. It uses Owen's T function, which is evaluated by using numerical integration.
</li>
<li>
Call the CDF and PDF functions as part of Newton's method, using the C-F approximation as the initial guess.
</li>
</ol>

<h3>Step 1: Use the C-F expansion to approximate the quantiles</h3>
<p>
The following functions return the Cornish-Fisher approximation of the skew-normal quantiles:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* Use the Cornish-Fisher expansion to estimate quantiles. See 
   https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html 
   Function that computes the mean, variance, skewness, and 
   excess kurtosis for the skew-normal distribution */</span>
start Moments_SN<span style="color: #66cc66;">&#40;</span>Name, param<span style="color: #66cc66;">&#41;</span>;
   alpha = param<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span>;
   delta = alpha / <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span> + alpha##<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;
   pi = constant<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'pi'</span><span style="color: #66cc66;">&#41;</span>;
   mu  = delta <span style="color: #006400; font-style: italic;">* sqrt(2/pi);</span>                     <span style="color: #006400; font-style: italic;">/* Mean */</span>
   <span style="color: #0000ff;">var</span> = <span style="color: #2e8b57; font-weight: bold;">1</span> - <span style="color: #2e8b57; font-weight: bold;">2</span>/pi <span style="color: #006400; font-style: italic;">*delta##2;</span>                     <span style="color: #006400; font-style: italic;">/* Variance */</span>
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">3</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;VAR&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">var</span> <span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;MEAN&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> mu <span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;SKEW&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">4</span> - pi<span style="color: #66cc66;">&#41;</span>/<span style="color: #2e8b57; font-weight: bold;">2</span> <span style="color: #006400; font-style: italic;">* mu##3 / var##1.5 );</span>   <span style="color: #006400; font-style: italic;">/* qamma_1 = skewness */</span>
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;KURT&quot;</span> |
      ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;EXKU&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #006400; font-style: italic;">*(pi - 3) * mu##4 / var##2 );</span>     <span style="color: #006400; font-style: italic;">/* gamma_2 = excess kurtosis */</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Cornish-Fisher expansion for the SN(shape) distribution
   p is a vector of probabilities in (0, 1).
   The function returns a vector q, such that 
   q[i] is an approximation to quantile(&quot;SN&quot;, p[i], shape) */</span>
start Cornish_Expand_SN<span style="color: #66cc66;">&#40;</span>p, shape<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #006400; font-style: italic;">/* get moments of distribution: mean, variance, skewness, Ex kurtosis  */</span>
  mu  = Moments_SN<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Mean&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">var</span> = Moments_SN<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Var&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
  g1 = Moments_SN<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Skew&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
  g2 = Moments_SN<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;ExKurt&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #006400; font-style: italic;">/* Use the 4-term Cornish-Fisher expansion to estimate q for a 
     standardized distribution with those moments */</span>
  z = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, p<span style="color: #66cc66;">&#41;</span>;    <span style="color: #006400; font-style: italic;">/* z is the standard normal quantile */</span>
  q_std = z + <span style="color: #66cc66;">&#40;</span>z##<span style="color: #2e8b57; font-weight: bold;">2</span> - <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>#g1/<span style="color: #2e8b57; font-weight: bold;">6</span> + z#<span style="color: #66cc66;">&#40;</span>z##<span style="color: #2e8b57; font-weight: bold;">2</span> - <span style="color: #2e8b57; font-weight: bold;">3</span><span style="color: #66cc66;">&#41;</span>#g2/<span style="color: #2e8b57; font-weight: bold;">24</span> - z#<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">2</span>#z##<span style="color: #2e8b57; font-weight: bold;">2</span> - <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>#g1##<span style="color: #2e8b57; font-weight: bold;">2</span>/<span style="color: #2e8b57; font-weight: bold;">36</span>;
  <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> mu + <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">var</span><span style="color: #66cc66;">&#41;</span> # q_std <span style="color: #66cc66;">&#41;</span>;
finish;</pre></td></tr></table></div>




<h3>Step 2: Implement the PDF and CDF functions</h3>
<p>
I did this step in a previous article.
I assume that these functions are stored and that the following statement loads them into the current PROC IML
step:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Be sure to STORE the modules from 
   https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html  */</span>
load module=<span style="color: #66cc66;">&#40;</span>PDF_SN CDF_SN OwenT_Integrand OwenT<span style="color: #66cc66;">&#41;</span>;</pre></td></tr></table></div>




<h3>Step 3: Implement Newton's method</h3>
<p>
With the helper functions defined, you can implement Newton's method. 
To solve for the root of an equation CDF(x) - p = 0, 
Newton's method requires evaluating the function and its derivative. 
The derivative of  a CDF is exactly the PDF. Therefore, the Newton-Raphson update step is simply
<br />
x_new = x - (CDF(x) - p) / PDF(x)
<br />
The following SAS IML program uses the Cornish-Fisher expansion to provide aan initial guess for x. 
It also includes <a href="https://blogs.sas.com/content/iml/2026/02/04/clip-values.html">a Clip function</a> to bound the updates, 
which ensures that the root-finding algorithm cannot exceed the theoretical limits of the skew-normal distribution.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* use the elementwise minimum (&gt;&lt;) and elementwise maximum (&lt;&gt;) operators to 
   truncate elements of a vector into an interval. 
   https://blogs.sas.com/content/iml/2026/02/04/clip-values.html
*/</span>
start Clip<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, ab<span style="color: #66cc66;">&#41;</span>;
   a = ab<span style="color: #66cc66;">&#91;</span>,<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span>; b = ab<span style="color: #66cc66;">&#91;</span>,<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#93;</span>;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> a &lt;&gt; <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span> &gt;&lt; b<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Quantile of the standardized skew-normal distribution for a single scalar value, p. */</span>
start Quantile1_SN<span style="color: #66cc66;">&#40;</span>p, alpha<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">x</span> = Cornish_Expand_SN<span style="color: #66cc66;">&#40;</span>p, alpha<span style="color: #66cc66;">&#41;</span>;        <span style="color: #006400; font-style: italic;">/* approximate quantile */</span>
&nbsp;
  <span style="color: #006400; font-style: italic;">/* From asymptotic theory, we know that q = F_{SN}^{-1}(p) in [q_min, q_max] */</span>
  q_max = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, <span style="color: #66cc66;">&#40;</span>p + <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>/<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* quantile of half-normal distrib */</span>
  q_min = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, p/<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;        <span style="color: #006400; font-style: italic;">/* quantile of negative half-normal distrib */</span>
&nbsp;
  <span style="color: #006400; font-style: italic;">/* Use Newton-Raphson to find root of CDF_SN(q,alpha) - p = 0.
     Since the derivative of the CDF is the PDF, it's easy to use Newton's method.  */</span>
  relerr = <span style="color: #2e8b57; font-weight: bold;">1</span>;
  <span style="color: #0000ff;">do</span> iter = <span style="color: #2e8b57; font-weight: bold;">1</span> to <span style="color: #2e8b57; font-weight: bold;">200</span> <span style="color: #0000ff;">while</span> <span style="color: #66cc66;">&#40;</span>relerr &gt; 1E-6<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #006400; font-style: italic;">/* Step size using standard PDF and CDF (loc=0, scale=1) */</span>
    x1 = <span style="color: #0000ff;">x</span> - <span style="color: #66cc66;">&#40;</span>CDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha<span style="color: #66cc66;">&#41;</span> - p<span style="color: #66cc66;">&#41;</span> / PDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha<span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* x - F(x) / F'(x) */</span>
    x1 = Clip<span style="color: #66cc66;">&#40;</span>x1, q_min||q_max<span style="color: #66cc66;">&#41;</span>;          <span style="color: #006400; font-style: italic;">/* prevent extreme steps */</span>
    relerr = <span style="color: #0000ff;">abs</span><span style="color: #66cc66;">&#40;</span>x1 - <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span> / <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span> + <span style="color: #0000ff;">abs</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; 
    <span style="color: #0000ff;">x</span> = x1;
  <span style="color: #0000ff;">end</span>;
  <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">x</span> <span style="color: #66cc66;">&#41;</span>;   <span style="color: #006400; font-style: italic;">/* standardized quantile: F(q) = p for the standardized CDF */</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Quantile function of the skew-normal distribution for column vector of values, p. 
   alpha is the shape parameter for the SN distribution. 
   loc and scale are optional location/scale  parameters for the SN distribution. */</span>
start Quantile_SN<span style="color: #66cc66;">&#40;</span>p, alpha, loc=<span style="color: #2e8b57; font-weight: bold;">0</span>, scale=<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
  q = j<span style="color: #66cc66;">&#40;</span>nrow<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span>, ncol<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span>, .<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">do</span> i = <span style="color: #2e8b57; font-weight: bold;">1</span> to nrow<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*ncol(p);</span>
    q<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = Quantile1_SN<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>, alpha<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">end</span>;
  <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> loc + scale # q <span style="color: #66cc66;">&#41;</span>;
finish;</pre></td></tr></table></div>




<p>
The Quantile1_SN function is the main computational routine. It uses Newton's method to converge 
quickly to the quantile of a standard skew-normal distribution, given the C-F approximation. The 
Quantile_SN function is a convenient wrapper, which enables you to compute multiple quantiles with a single call.
It also enables you to support location and scale parameters for the skew-normal distribution.
</p><p>
To demonstrate the usage, here is a call to the Quantile_SN function for &alpha;=2.
The input is a regular grid of probabilities on the interval (0, 1). The output is a vector
of skew-normal quantiles.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;">alpha = <span style="color: #2e8b57; font-weight: bold;">2</span>;
p = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0.01</span>, <span style="color: #2e8b57; font-weight: bold;">0.99</span>, <span style="color: #2e8b57; font-weight: bold;">0.01</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
q = Quantile_SN<span style="color: #66cc66;">&#40;</span>p, alpha<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;SN(2) Quantile Function&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span>p, q<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/11/skewnormal4.png"><img decoding="async" src="https://blogs.sas.com/content/iml/files/2026/11/skewnormal4.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60626" srcset="https://blogs.sas.com/content/iml/files/2026/11/skewnormal4.png 640w, https://blogs.sas.com/content/iml/files/2026/11/skewnormal4-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<h3>So what? I don't use the skew-normal distribution!</h3>
<p>
The method in this article is very general.
You might never use the skew-normal distribution, but the method (a C-F approximation, followed by Newton's method, which uses the CDF and PDF)
can be applied to many other distributions. 
Although software packages like SAS provide built-in functions for the quantiles of many common distributions,
the technique in this article is generally useful for less-common distributions.
</p>

<h3>Summary</h3>
<p>
This article demonstrates a general method for computing the quantiles of a continuous
probability distribution. The method is demonstrated by using 
the skew-normal distribution. The method requires three steps,
First, write functions that evaluate 
<a href="https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html">"the Cornish-Fisher approximation to quantiles"</a>.
Second, write the functions to evaluate the PDF and CDF. The CDF might require performing a numerical integration. 
Third, call the CDF and PDF functions as part of Newton's method, using the C-F approximation as the initial guess.
</p><p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/16/quantiles-skew-normal.html">Quantiles of the skew-normal distribution</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/11/16/quantiles-skew-normal.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/11/skewnormal4-150x150.png" />
	</item>
		<item>
		<title>Implement the skew-normal distribution in SAS</title>
		<link>https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 09 Nov 2026 10:21:26 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60414</guid>

					<description><![CDATA[<p>The normal distribution is symmetric, which means that it has zero skewness. In certain applications, it is useful to embed the normal distribution into a family that can model positively and negatively skewed data. Azzalini (1985) proposed a method to add a skewness parameter, &#945;, to any symmetric family. He [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html">Implement the skew-normal distribution in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
The normal distribution is symmetric, which means that it has zero skewness.
In certain applications, it is useful to embed the normal distribution into a family that 
can model positively and negatively skewed data.
Azzalini (1985) proposed a method to add a skewness parameter, &alpha;, to 
any symmetric family. He applied his method to the normal distribution to construct
the <a href="https://en.wikipedia.org/wiki/Skew_normal_distribution">skew-normal (SN) distribution</a>
</p><p>
The skew-normal distribution is negatively skewed when &alpha; &lt; 0. The distribution is positively 
skewed when &alpha; &gt; 0. The distribution equals the normal distribution when &alpha; = 0.
</p>
<p>
This article shows how to implement the PDF, CDF, and how to generate random variates 
for the skew-normal distribution in SAS.  Some of the techniques are similar to those
in <a href="https://support.sas.com/resources/papers/proceedings16/7660-2016.pdf">the SAS Global Forum paper by da Silva and da Silva (2016)</a>.
However, this blog post uses <a href="https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html">Owen's T function</a> 
to evaluate the CDF of the skew normal distribution. 
</p>
<p>
To prevent this article from being too long, 
the computation of the quantiles for the skew-normal distribution is
discussed in a separate blog post. 
</p>

<h3>The PDF of the skew-normal distribution</h3>
<p>
The skew-normal distribution is defined by its probability density function (PDF). 
For the standardized skew-normal distribution, the PDF is given by 
<br />
&nbsp;&nbsp;&nbsp;&nbsp;
f(x; &alpha;) = 2 &phi;(x) &Phi;(&alpha; x)
<br />
where  &phi;(x) is the PDF of the standard normal distribution and &Phi;(x) is the cumulative distribution
function (CDF) of the standard normal distribution.
</p>
<p>
If you need the log-PDF for likelihood-related computations, that's a straightforward computation:
<br />
&nbsp;&nbsp;&nbsp;&nbsp;
log(f(x; &alpha;)) = log(2) + log(&phi;(x)) + log(&Phi;(&alpha; x))
</p>

<p>
You can program these formulas in the SAS DATA step, PROC FCMP, or PROC IML.
Since the computation of the CDF requires integration, I will use PROC IML,
which provides a general-purpose integration subroutine.  Although this blog post only discusses 
standardized distributions, the following implementations include a location and scale parameter, 
in case you might find them useful in your own work.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Computation of the PDF, CDF, and random variates for the skew-normal distribution.
   Some computations follow da Silva and da Silva (2016).
   https://support.sas.com/resources/papers/proceedings16/7660-2016.pdf
*/</span>
<span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* PDF of skew-normal distribution */</span>
start PDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha, loc=<span style="color: #2e8b57; font-weight: bold;">0</span>, scale=<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
    z = <span style="color: #66cc66;">&#40;</span>x-loc<span style="color: #66cc66;">&#41;</span>/scale;
    phi = <span style="color: #0000ff;">pdf</span><span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, z<span style="color: #66cc66;">&#41;</span>;
    cdf_a = <span style="color: #0000ff;">cdf</span><span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, alpha#z<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #2e8b57; font-weight: bold;">2</span>/scale # phi # cdf_a <span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* for some applications, it is useful to compute the log-PDF function */</span>
start LogPDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha, loc=<span style="color: #2e8b57; font-weight: bold;">0</span>, scale=<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
    z = <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span> - loc<span style="color: #66cc66;">&#41;</span> / scale;
    log_phi = <span style="color: #0000ff;">logpdf</span><span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, z<span style="color: #66cc66;">&#41;</span>;
    log_cdf_a = logcdf<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, alpha#z<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">2</span>/scale<span style="color: #66cc66;">&#41;</span> + log_phi + log_cdf_a <span style="color: #66cc66;">&#41;</span>;
finish;
store module=<span style="color: #66cc66;">&#40;</span>PDF_SN LogPDF_SN<span style="color: #66cc66;">&#41;</span>;   <span style="color: #006400; font-style: italic;">/* store for using in another session */</span>
&nbsp;
<span style="color: #006400; font-style: italic;">/* visualize the standard skew-normal distribution for alpha=0, 1, 5 */</span>
<span style="color: #0000ff;">x</span> = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #2e8b57; font-weight: bold;">3</span>,<span style="color: #2e8b57; font-weight: bold;">3</span>,<span style="color: #2e8b57; font-weight: bold;">0.05</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
p0 = PDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
p1 = PDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
p5 = PDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000080; font-weight: bold;">run</span> WideToLong<span style="color: #66cc66;">&#40;</span>OutX, OutP, OutG, 
               p0||p1||p5, <span style="color: #0000ff;">x</span>, <span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">'alpha0'</span> <span style="color: #a020f0;">'alpha1'</span> <span style="color: #a020f0;">'alpha5'</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Skew-Normal Density&quot;</span>;
title2 <span style="color: #a020f0;">&quot;alpha = 0, 1, 5&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span>OutX, OutP<span style="color: #66cc66;">&#41;</span> <span style="color: #0000ff;">group</span>=OutG grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>





<a href="https://blogs.sas.com/content/iml/files/2026/11/skewnormal1.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/11/skewnormal1.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60604" srcset="https://blogs.sas.com/content/iml/files/2026/11/skewnormal1.png 640w, https://blogs.sas.com/content/iml/files/2026/11/skewnormal1-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
You can see that when &alpha; = 0 (the blue curve), the skew-normal distribution is symmetric and
equals the normal distribution. As &alpha; increases to 1 (the red curve), the skew-normal distribution
acquires positive skewness. For large values of &alpha; (the green curve), the distribution approaches <a href="https://blogs.sas.com/content/iml/2011/10/26/implement-the-folded-normal-distribution-in-sas.html">the half-normal distribution</a>.
</p>
<p>
I did not visualize any distributions for negative &alpha; because the distribution obeys the symmetry
f(x; -&alpha;) = f(-x; &alpha;). Thus, you can flip these curves around the line x=0 to visualize the skew-symmetric distributions
for &alpha; = -1 and -5.
</p>


<h3>The CDF of the skew-normal distribution</h3>
<p>
You could integrate the PDF directly (like da Silva and da Silva (2016) did in their paper), 
but it is more efficient to use <a href="https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html">Owen's T function</a>,
which I have written about previously. Whereas the definition of the CDF requires integrating the PDF 
on the infinite domain (-&infin;, x), Owen's T function enables you to integrate 
a function on a finite domain [0, &alpha;]. 
</p><p>
In terms of Owen's T function, the CDF of the standard skew-normal distribution is 
<br />
&nbsp;&nbsp;&nbsp;&nbsp;
F(x; &alpha;) = &Phi;(x) - 2 T(x; &alpha;)
<br />
For your convenience, I copied the IML implementation of Owen's T function into the 
Appendix of this article. When you run the code in the Appendix, it stores the OwenT function
to a module library. You can then use the LOAD statement to load the function, as follows: 
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* FIRST, STORE the modules in 
   https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html
   Then use the LOAD statement to load the definitions.
*/</span>
load module=<span style="color: #66cc66;">&#40;</span>OwenT_Integrand OwenT<span style="color: #66cc66;">&#41;</span>;
start CDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha, loc=<span style="color: #2e8b57; font-weight: bold;">0</span>, scale=<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
    z = <span style="color: #66cc66;">&#40;</span>x-loc<span style="color: #66cc66;">&#41;</span>/scale;
    cdf_N = <span style="color: #0000ff;">cdf</span><span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, z<span style="color: #66cc66;">&#41;</span>;
    T = OwenT<span style="color: #66cc66;">&#40;</span>z, alpha<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> cdf_N - <span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #006400; font-style: italic;">*T );</span>
finish;
store module=<span style="color: #66cc66;">&#40;</span>CDF_SN<span style="color: #66cc66;">&#41;</span>;   <span style="color: #006400; font-style: italic;">/* store for using in another session */</span>
&nbsp;
<span style="color: #006400; font-style: italic;">/* visualize the skew-normal CDF for alpha=0, 1, 5 */</span>
<span style="color: #0000ff;">x</span> = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #2e8b57; font-weight: bold;">3</span>,<span style="color: #2e8b57; font-weight: bold;">3</span>,<span style="color: #2e8b57; font-weight: bold;">0.05</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
c0 = CDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
c1 = CDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
c5 = CDF_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000080; font-weight: bold;">run</span> WideToLong<span style="color: #66cc66;">&#40;</span>OutX, OutC, OutG, 
               c0||c1||c5, <span style="color: #0000ff;">x</span>, <span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">'alpha0'</span> <span style="color: #a020f0;">'alpha1'</span> <span style="color: #a020f0;">'alpha5'</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Skew-Normal CDF&quot;</span>;
title2 <span style="color: #a020f0;">&quot;alpha = 0, 1, 5&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span>OutX, OutC<span style="color: #66cc66;">&#41;</span> <span style="color: #0000ff;">group</span>=OutG grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/11/skewnormal2.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/11/skewnormal2.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60603" srcset="https://blogs.sas.com/content/iml/files/2026/11/skewnormal2.png 640w, https://blogs.sas.com/content/iml/files/2026/11/skewnormal2-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
As before, the blue curve corresponds to the skew-normal distribution with &alpha;=0, which is the standard normal CDF.
The red and green curves correspond to &alpha;=1 and &alpha;=5, respectively, and show the CDF of right-skewed skew-normal distributions.
</p>

 
<h3>Random variates of the skew-normal distribution</h3>
<p>
The families of distribution in Azzalini (1985) all have a simple method to generate random variates.
They are based on generating random variates from a correlated bivariate normal distribution.
Random variates for the skew-normal distribution (with parameter &alpha;) can be 
generated by using random variates from the bivariate normal distribution with correlation 
&delta; = &alpha; / sqrt(1 + &alpha;<sup>2</sup>).
This transformation is an S-shaped sigmoidal curve that is strictly increasing and bounded in the range (-1, 1).
The random number generation is simple: generate a bivariate normal variate (x,y),
and return sign(x)*y.
This is implemented in the following IML function:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Random variates from the SN distribution */</span>
start Rand_SN<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, alpha, loc=<span style="color: #2e8b57; font-weight: bold;">0</span>, scale=<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
    delta = alpha / <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span> + alpha##<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;
    R = <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span> || delta<span style="color: #66cc66;">&#41;</span> // <span style="color: #66cc66;">&#40;</span>delta || <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
    U = randnormal<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#125;</span>, R<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">X</span> = <span style="color: #0000ff;">sign</span><span style="color: #66cc66;">&#40;</span>U<span style="color: #66cc66;">&#91;</span>,<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> # U<span style="color: #66cc66;">&#91;</span>,<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#93;</span>;
    <span style="color: #0000ff;">if</span> loc=<span style="color: #2e8b57; font-weight: bold;">0</span> &amp; scale=<span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">then</span>
       <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">X</span> <span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">else</span> 
       <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> scale<span style="color: #006400; font-style: italic;">*X + loc );</span>
finish;
&nbsp;
<span style="color: #0000ff;">call</span> randseed<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1234</span><span style="color: #66cc66;">&#41;</span>;
rx = Rand_SN<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1000</span>, <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Random Variates from Skew-Normal Distribution&quot;</span>;
title2 <span style="color: #a020f0;">&quot;alpha = 1&quot;</span>;
<span style="color: #0000ff;">call</span> histogram<span style="color: #66cc66;">&#40;</span>rx<span style="color: #66cc66;">&#41;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/11/skewnormal3.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/11/skewnormal3.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60602" srcset="https://blogs.sas.com/content/iml/files/2026/11/skewnormal3.png 640w, https://blogs.sas.com/content/iml/files/2026/11/skewnormal3-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
The histogram shows 1,000 random variates for the SN distribution with &alpha; = 1.
It looks similar to the PDF function for the same parameter value.
</p>


<h3>Summary</h3>
<p>
This article discusses the skew-normal distribution (Azzalini (1985))
and uses the SAS IML language to implement the PDF, CDF, and random variate functions. 
For a slightly different implementation, see  da Silva and da Silva (2016).
The quantile function is a little tricky, so it will be covered in a separate blog post.
</p>

<h3>Appendix: The computation of Owen's T function</h3>
<p>
I have written about <a href="https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html">how to compute Owen's T function in SAS</a>.
One application of Owen's T function is computing the CDF of the skew-normal distribution.
For your convenience, here is the SAS IML code you need to store Owen's T function in an IML library.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;">&nbsp;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Define the Integrand for Owen's T function:
   The QUAD subroutine passes a scalar value, t, during the integration process.
   Use the GLOBAL statement to pass the parameter value, x (via 'g_Owenx').
*/</span>
start OwenT_Integrand<span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_Owenx<span style="color: #66cc66;">&#41;</span>;
   t2 = <span style="color: #2e8b57; font-weight: bold;">1</span> + t##<span style="color: #2e8b57; font-weight: bold;">2</span>;
   <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">exp</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #2e8b57; font-weight: bold;">0.5</span> <span style="color: #006400; font-style: italic;">* g_Owenx##2 * t2) / t2 );</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Define Owen's T Function by integrating OwenT_Integrand on [0, alpha].
   Loop over the elements of x to allow vector inputs. alpha is a scalar.
*/</span>
start OwenT<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_Owenx<span style="color: #66cc66;">&#41;</span>;
   pi = constant<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;pi&quot;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">n</span> = nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   y = j<span style="color: #66cc66;">&#40;</span>nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, .<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #006400; font-style: italic;">/* make sure limits of integration are increasing. If alpha &lt; 0, reverse sign of answer */</span>
   limits = <span style="color: #2e8b57; font-weight: bold;">0</span> || <span style="color: #0000ff;">abs</span><span style="color: #66cc66;">&#40;</span>alpha<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">do</span> i = <span style="color: #2e8b57; font-weight: bold;">1</span> to <span style="color: #0000ff;">n</span>;
      g_Owenx = <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;   <span style="color: #006400; font-style: italic;">/* set parameter, 'x' */</span>
      <span style="color: #0000ff;">call</span> quad<span style="color: #66cc66;">&#40;</span>val, <span style="color: #a020f0;">&quot;OwenT_Integrand&quot;</span>, limits<span style="color: #66cc66;">&#41;</span>;
      y<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = val;
   <span style="color: #0000ff;">end</span>;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">sign</span><span style="color: #66cc66;">&#40;</span>alpha<span style="color: #66cc66;">&#41;</span> <span style="color: #006400; font-style: italic;">* y/(2*pi) );</span> <span style="color: #006400; font-style: italic;">/* negate answer if alpha &lt; 0 */</span>
finish;
store module=<span style="color: #66cc66;">&#40;</span>OwenT_Integrand OwenT<span style="color: #66cc66;">&#41;</span>;
<span style="color: #000080; font-weight: bold;">QUIT</span>;</pre></td></tr></table></div>





<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html">Implement the skew-normal distribution in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/11/09/skew-normal-sas.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/11/skewnormal1-150x150.png" />
	</item>
		<item>
		<title>The Cornish-Fisher approximation to quantiles</title>
		<link>https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html#comments</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Tue, 03 Nov 2026 11:21:58 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60566</guid>

					<description><![CDATA[<p>The Cornish-Fisher (C-F) expansion approximates the quantiles of an arbitrary continuous univariate distribution by using only the mean, variance, skewness, and excess kurtosis of the distribution. Intuitively, you can model the shape of many common probability distributions by using these four moment-based quantities. This article shows how to use SAS [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html">The Cornish-Fisher approximation to quantiles</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
The <a href="https://en.wikipedia.org/wiki/Cornish%E2%80%93Fisher_expansion">Cornish-Fisher (C-F)
expansion</a> approximates the quantiles of an arbitrary continuous univariate 
distribution by using only the mean, variance, skewness, and excess kurtosis 
of the distribution. Intuitively, you can model the shape of many common 
probability distributions by using these four moment-based quantities. 
</p>
<p>
This article shows how to use SAS to implement the Cornish-Fisher 
approximation to a quantile.
</p>

<h3>The Cornish-Fisher expansion</h3>
<p>
Let F be a continuous cumulative probability distribution. 
If p in (0,1) is any probability, then the quantile for p is the value, 
q<sub>p</sub>, such that p = F(q<sub>p</sub>). This is often denoted as q<sub>p</sub> = F<sup>-1</sup>(p). 
For a wide range of distributions, the C-F expansion enables you to 
approximate the quantile for any probability, p. The approximation is 
best when p is not too close to 0 or 1.
</p>
<p>
The C-F expansion is based on a transformation of a normal distribution. 
The full Cornish-Fisher expansion is an infinite series, but most 
practitioners truncate the series after four terms. Thus, in the 
remainder of this article, "the C-F expansion" always means "the four-term C-F expansion."
</p>
<p>
Let z = &Phi;<sup>-1</sup>(p) be the quantile of p for the standard normal 
distribution. The four-term C-F expansion is the cubic polynomial 
<br />
q = z + (&gamma;<sub>1</sub> / 6)(z<sup>2</sup> &minus; 1) + 
        (&gamma;<sub>2</sub> / 24)(z<sup>3</sup> &minus; 3z) &minus; 
        (&gamma;<sub>1</sub><sup>2</sup> / 36)(2z<sup>3</sup> &minus; 5z)
<br />
where &gamma;<sub>1</sub> is the skewness of the distribution, and 
&gamma;<sub>2</sub> is the excess kurtosis. This function maps the 
standard normal quantile into a quantile for a standardized 
distribution whose skewness and excess kurtosis are close to 
&gamma;<sub>1</sub> and &gamma;<sub>2</sub>, respectively. 
Notice that the normal distribution has &gamma;<sub>1</sub> = &gamma;<sub>2</sub> = 0, 
so the C-F expansion reduces to the identity transformation for 
the normal distribution itself.
</p>
<p>
A standardized distribution has zero mean and unit variance. 
You can use the linear transformation 
<br />
q &rarr; &mu; + &sigma; q
<br />
to adjust the quantile for non-standardized distributions 
that have mean &mu; and standard deviation &sigma;.
</p>

<h3>Implement the Cornish-Fisher expansion in SAS</h3>

<a href="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand1.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand1.png" alt="" width="320" height="240" class="alignright size-full wp-image-60581" srcset="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand1.png 640w, https://blogs.sas.com/content/iml/files/2026/10/CornishExpand1-300x225.png 300w" sizes="(max-width: 320px) 100vw, 320px" /></a>

<p>
To demonstrate the C-F expansion, let's use the 
<a href="https://en.wikipedia.org/wiki/Gamma_distribution">Gamma distribution</a> 
with shape parameter equal to 2 and unit scale. The PDF of this distribution is 
shown to the right. You can see that it does not look very much like a normal 
distribution. The Wikipedia article about the Gamma distribution contains formulas 
for the four moments in terms of the shape parameter, &alpha;. The mean and 
variance are both equal to &alpha;. The kurtosis is 2/sqrt(&alpha;); 
the excess kurtosis is 6 / &alpha;. Thus, when &alpha; = 2, the skewness 
is sqrt(2) &asymp; 1.41, and the excess kurtosis is 3.
</p>
<p>
The following SAS IML program defines a helper function that returns 
the mean, variance, skewness, and excess kurtosis of the Gamma(&alpha;) 
distribution in terms of the shape parameter. The program then 
defines a function that evaluates the four-term Cornish-Fisher 
approximation to the quantiles of the Gamma(&alpha;) distribution. The 
function implements the cubic polynomial formula in the previous section. 
You can call the function for a vector of probabilities in (0,1) 
and compare the approximate C-F values with the true values by 
using the built-in QUANTILE function in Base SAS, as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* function that computes the mean, variance, skewness, and 
   excess kurtosis for the Gamma distribution */</span>
start Moments_Gamma<span style="color: #66cc66;">&#40;</span>Name, param<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">3</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;VAR&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> param <span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;MEAN&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> param <span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;SKEW&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #2e8b57; font-weight: bold;">2</span> / <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span>param<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;KURT&quot;</span> |
      ksubstr<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">upcase</span><span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">4</span><span style="color: #66cc66;">&#41;</span>=<span style="color: #a020f0;">&quot;EXKU&quot;</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #2e8b57; font-weight: bold;">6</span> / param <span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Cornish-Fisher expansion for the Gamma(shape) distribution
   p is a vector of probabilities in (0, 1).
   The function returns a vector q, such that 
   q[i] is an approximation to quantile(&quot;Gamma&quot;, p[i], shape) */</span>
start Cornish_Expand_Gamma<span style="color: #66cc66;">&#40;</span>p, shape<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #006400; font-style: italic;">/* get moments of the distribution: mean, variance, skewness, Ex kurtosis  */</span>
  mu  = Moments_Gamma<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Mean&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">var</span> = Moments_Gamma<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Var&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
  g1 = Moments_Gamma<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Skew&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
  g2 = Moments_Gamma<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;ExKurt&quot;</span>, shape<span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #006400; font-style: italic;">/* Use the 4-term Cornish-Fisher expansion to estimate q for a 
     standardized distribution with those moments */</span>
  z = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, p<span style="color: #66cc66;">&#41;</span>;    <span style="color: #006400; font-style: italic;">/* z is the standard normal quantile */</span>
  q_std = z + <span style="color: #66cc66;">&#40;</span>z##<span style="color: #2e8b57; font-weight: bold;">2</span> - <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>#g1/<span style="color: #2e8b57; font-weight: bold;">6</span> + z#<span style="color: #66cc66;">&#40;</span>z##<span style="color: #2e8b57; font-weight: bold;">2</span> - <span style="color: #2e8b57; font-weight: bold;">3</span><span style="color: #66cc66;">&#41;</span>#g2/<span style="color: #2e8b57; font-weight: bold;">24</span> - z#<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">2</span>#z##<span style="color: #2e8b57; font-weight: bold;">2</span> - <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>#g1##<span style="color: #2e8b57; font-weight: bold;">2</span>/<span style="color: #2e8b57; font-weight: bold;">36</span>;
  <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> mu + <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">var</span><span style="color: #66cc66;">&#41;</span> # q_std <span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* incorporate the center and scale */</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Compare exact quantiles and C-F expansion for the Gamma(2) distribution */</span>
shape = <span style="color: #2e8b57; font-weight: bold;">2</span>;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Calculate approximate and exact quantiles */</span>
p = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0.01</span>, <span style="color: #2e8b57; font-weight: bold;">0.99</span>, <span style="color: #2e8b57; font-weight: bold;">0.01</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
Approx_Q = Cornish_Expand_Gamma<span style="color: #66cc66;">&#40;</span>p, shape<span style="color: #66cc66;">&#41;</span>;
Exact_Q = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Gamma&quot;</span>, p, shape<span style="color: #66cc66;">&#41;</span>;</pre></td></tr></table></div>




<p>
The following statements overlay 
the C-F approximation and the true quantile function on a single graph:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Prepare data for plotting */</span>
<span style="color: #000080; font-weight: bold;">run</span> WideToLong<span style="color: #66cc66;">&#40;</span>Probability, Quantile, Method, 
               Approx_Q || Exact_Q, p, <span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">&quot;CF_Approx&quot;</span> <span style="color: #a020f0;">&quot;Exact_Gamma&quot;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Cornish-Fisher Approximation vs Exact Gamma Quantiles&quot;</span>;
title2 <span style="color: #a020f0;">&quot;Gamma Distribution (Shape=2)&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span>Probability, Quantile<span style="color: #66cc66;">&#41;</span> <span style="color: #0000ff;">group</span>=Method grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>





<a href="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand2.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand2.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60578" srcset="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand2.png 640w, https://blogs.sas.com/content/iml/files/2026/10/CornishExpand2-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
Wow! That's a good approximation!
The C-F expansion is excellent approximation for all but 
very extreme values of the probability, p.
</p><p>
If you subtract the two curves, you can visualize the absolute 
difference between the true value and the C-F approximation. 
The difference is shown in the following graph. The difference 
is largest for extreme values of the probability, but the 
overall agreement is remarkably good.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* plot the difference */</span>
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Difference Between Exact Quantiles and C-F Approximation&quot;</span>;
title2 <span style="color: #a020f0;">&quot;Gamma Distribution (Shape=2)&quot;</span>;
Difference = Exact_Q - Approx_Q;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span>p, Difference<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span> <span style="color: #0000ff;">label</span>=<span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">&quot;Probability&quot;</span> <span style="color: #a020f0;">&quot;Difference (Exact-Approx)&quot;</span><span style="color: #66cc66;">&#125;</span>
                           other=<span style="color: #a020f0;">&quot;refline 0 / axis=y;&quot;</span>;</pre></td></tr></table></div>





<a href="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand3.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand3.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60575" srcset="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand3.png 640w, https://blogs.sas.com/content/iml/files/2026/10/CornishExpand3-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>


<h3>How good is the approximation for other parameter values?</h3>
<p>
You can change the value of the 'alpha' parameter and rerun 
the program to determine how the approximation varies with 
the shape parameter. Try these other values:
</p>
<ul>
<li>alpha = 1: For this parameter, the Gamma(1) distribution 
is equal to the exponential distribution. The exponential 
distribution is far from being normally distributed. 
Nevertheless, the cubic transformation of the normal 
quantiles is close to the actual exponential quantiles 
except for extreme probabilities. For p = 0.01, the C-F 
approximation is within 0.24 units of the true quantile. 
</li>
<li>alpha = 4: As alpha increases, the Gamma(alpha) distribution 
looks more and more normal. For alpha = 4, the C-F approximation 
is within 0.05 units of the true quantile on the interval (0.01, 0.99). 
</li>
</ul>

<h3>Why is the C-F expansion useful?</h3>
<p>
Since we can use the QUANTILE function to compute the exact 
value of the quantiles of the Gamma distribution, why 
do we need the C-F approximation?
</p>
<p>
For any function that is supported by the QUANTILE function 
in SAS, you do not need to use an approximation. However, 
you might need to compute the quantiles for a distribution 
that is not natively supported by the QUANTILE function. 
For most distributions, the CDF function cannot be explicitly 
inverted. Thus, to find a quantile, you must solve for the 
root of a nonlinear equation of the form CDF(q) - p = 0. 
This requires some sort of root-finding algorithm. 
</p>
<p>
In the past, I have used the FROOT function in IML to solve 
for the root. The FROOT function requires that you specify 
an interval that contains the root. This might be a challenge. 
An alternative is to use Newton's method to find the root. 
Newton's method requires an approximate guess for the location 
of a root, which can also be challenging. Fortunately, the 
Cornish-Fisher approximation provides the required guess. 
In many cases, the C-F approximation is close enough that 
Newton's Method converges in 1-3 iterations. This rapid 
convergence is important when the CDF is expensive to compute, 
such as when the CDF must be computed by integrating the PDF function.
</p>

<h3>How to use the C-F expansion for a different distribution</h3>
<p>
It is straightforward to compute the C-F expansion for a 
different distribution. You first write a new helper function 
that returns the mean, variance, skewness, and excess kurtosis 
for the distribution. (Check Wikipedia or a textbook.) You then 
modify the Cornish_Expand_Gamma function to call the new function. 
I will demonstrate this in a subsequent article.
</p>

<h3>Summary</h3>
<p>
This article shows how to use the four-term Cornish-Fisher
expansion to obtain an approximation for a quantile of a large 
variety of continuous probability distributions. The C-F formula 
uses the first four moments of the distribution (mean, variance, 
skewness, and excess kurtosis) to transform a standard normal quantile. 
While in theory, this method is limited to distributions that are not 
"too far from normal," in practice the 4-term CF expansion is very accurate,
even for a distribution that is not close to being normal.
</p>
<p>
The C-F approximation is useful when there is not an explicit formula 
for the quantile function. In those cases, the C-F approximation 
provides an initial guess for a root-finding algorithm that solves 
for the quantile of the distribution. In a subsequent article, I
show <a href="https://blogs.sas.com/content/iml/2026/11/16/quantiles-skew-normal.html">how to use the Cornish-Fisher transformation to compute the quantiles of the skew-normal distribution</a>.
</p>
<p>
The limitations of the C-F approximation are discussed in the Appendix.
</p>


<h3>Appendix</h3>
<p>
An early effort of Fisher and his colleagues was to describe all distribution in terms of their moments. 
This effort can be summarized in <a href="https://blogs.sas.com/content/iml/2020/01/15/moment-ratio-diagram.html">the moment-ratio (MR) diagram</a>,
which organizes many common standardized distributions according to their skewness and kurtosis. 
</p><p>
The Cornish-Fisher expansion is not valid if a distribution has an extreme value of skewness and kurtosis. 
In "A User’s Guide to the Cornish Fisher Expansion" (2014, 2018), Didier Maillard derives the algebraic boundaries where the expansion is valid. 
If you overlay that region on a moment-ratio diagram, you can visualize the distributions that are not "too far from normal" as measured by the C-F expansion.
And, of course, the method assumes that the first four moments exist, which excludes heavy-tailed distributions such as the Cauchy distribution.  
</p><p>
In addition, the C-F expansion might not respect the natural boundaries of a distribution. 
For example, it might predict a negative quantile for a strictly positive distribution when p is very small.
</p><p>
The idea of using power transformations of a normal variable has been used by 
Fleishman (1978) and Headrick (2002, 2010) to develop <a href="https://blogs.sas.com/content/iml/2024/02/26/fit-flexible-distribution.html">flexible families of distributions</a>. Fleishman used cubic transformations whereas Headrick used higher-order polynomials.
Both the Fleishman and Headrick systems have limitations in the sense that they cannot model distributions that have extreme skewness and kurtosis.
</p><p>
The "solution" to this problem was found by Johnson (1949) who used non-polynomial transformations of normal variables to
construct a flexible system of distributions that covers the entire moment-ratio diagram. The so-called <a href="https://blogs.sas.com/content/iml/2020/01/27/johnson-su-distribution.html">Johnson system of distributions</a>
is a marvelous tool. It is supported in SAS by using PROC SIMSYSTEM.  
</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html">The Cornish-Fisher approximation to quantiles</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/11/03/cornish-approx-quantiles.html/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/10/CornishExpand2-150x150.png" />
	</item>
		<item>
		<title>Compute the generalized inverse Gaussian distribution in SAS</title>
		<link>https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 19 Oct 2026 09:28:16 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Numerical Analysis]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60417</guid>

					<description><![CDATA[<p>A SAS programmer asked how to implement the generalized inverse Gaussian (GIG) distribution in SAS. The GIG distribution is used as a conjugate prior for the variance of a normal distribution, so it appears in some Bayesian models. As its name implies, the generalized inverse Gaussian distribution includes the inverse [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html">Compute the generalized inverse Gaussian distribution in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
A SAS programmer asked how to implement the generalized inverse Gaussian (GIG) distribution in SAS.
The GIG distribution is 
used as a conjugate prior for the variance of a normal distribution, so it appears in some Bayesian models.
As its name implies, the generalized inverse Gaussian distribution includes <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/procstat/procstat_univariate_details39.htm#procstat.univariate.fitted_igauss">the inverse Gaussian (Wald) distribution</a> for  
special values of its parameters. The gamma and inverse gamma distributions are asymptotically related distributions.
</p>
<p>
<a href="https://en.wikipedia.org/wiki/Generalized_inverse_Gaussian_distribution">The Wikipedia article about the GIG distribution</a> provides a formula for the probability density function of the GIG 
distribution.
This article shows how to implement that formula in SAS. In addition, this article
shows how to implement the log-PDF function, which is used in log-likelihood computations.
</p>

<h3>The PDF of the generalized inverse Gaussian distribution</h3>
<p>
The generalized inverse Gaussian distribution, GIG(<em>x; a, b, p</em>), 
specifies the density of a positive random variable, X. The distribution has three parameters: <em>a</em>  &gt; 0,  <em>b</em> &gt; 0, and a real value <em>p</em>. The formula for the PDF is 
<br />
<span class='MathJax_Preview'>\(
f(y; a, b, p) = \frac{(a/b)^{p/2}}{2 K_p(\sqrt{ab})} y^{p-1} \exp\left( -\frac{1}{2}\left(ay + \frac{b}{y}\right) \right)
\)</span><script type='math/tex'>
f(y; a, b, p) = \frac{(a/b)^{p/2}}{2 K_p(\sqrt{ab})} y^{p-1} \exp\left( -\frac{1}{2}\left(ay + \frac{b}{y}\right) \right)
</script>
<br />
where K<sub>p</sub> is <a href="https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html">the modified Bessel function of the second kind</a>. The roles of the three parameters are as follows:
</p>
<ul>
<li>
<em>a</em> &gt; 0 is a rate parameter. It controls the rate of decay for the right tail of the distribution as x &rarr; &infin;.
</li>
<li>
<em>b</em> &gt; 0 is a parameter that controls the rate of decay for the left tail of the distribution near x=0.
</li>
<li>
<em>p</em> is a real index parameter. It is the "generalization" parameter that 
links the GIG to other distributions. Most notably, if <em>p</em> = -1/2, the GIG becomes the ordinary inverse Gaussian distribution.
If <em>p</em> &gt; 0, then in the limit as <em>b</em> &rarr; 0, the GIG approaches the gamma distribution.
If <em>p</em> &lt; 0, then as <em>a</em>  &rarr; 0, the GIG approaches the inverse gamma distribution.
</li>
</ul>
<p>
It is sometimes useful to compute the log-PDF, which is 
<br />
log f(y; a, b, p) = (p/2) log(a/b) - log(2) - log(K<sub>p</sub>(sqrt(a*b))) + (p-1) log(y) - (1/2)(a*y + b/y)
<br />
where log indicates the natural logarithm.
The log-PDF is useful if you want to compute the log-likelihood. The log-likelihood function is simply the sum of the log-PDF for each point in a data sample: 
LL = &Sigma;<sub>i</sub> log( f(y<sub>i</sub>; a, b, p) ),
where {y<sub>1</sub>, y<sub>2</sub>, ..., y<sub>n</sub>} is a sample of data.
</p>
<p>
Not only does the modified Bessel function, K<sub>p</sub>, appear in the definition of the PDF, but the Bessel function also
is used in formulas for the mean and variance of the distribution. See Wikipedia for the formulas.
</p>

<h3>Implement the PDF of the GIG distribution in SAS</h3>
<p>
The GIG PDF requires evaluating the modified Bessel function of the second kind, which is not natively supported in SAS.
However, a previous article shows <a href="https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html">how to evaluate the modified Bessel function in SAS IML software</a> by numerically evaluating an integral.
The following program assumes that you have defined and stored the BesselK function from the previous blog post. 
You can then implement the log-PDF. For the full PDF, exponentiate the log-PDF, as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Before running this program, STORE the BesselK function and helper functions from
   https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html
*/</span>
<span style="color: #000080; font-weight: bold;">proc iml</span>;
load module=<span style="color: #0000ff;">_all_</span>; <span style="color: #006400; font-style: italic;">/* load BesselK function */</span>
&nbsp;
<span style="color: #006400; font-style: italic;">/* Log-PDF for the generalized inverse Gaussian distribution 
   evaluated at a column vector of values x, x[i] &gt; 0 for all i */</span>
start logPDF_GIG<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, a, b, p<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">n</span> = nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">logPDF</span> = j<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">n</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, .<span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #006400; font-style: italic;">/* calculate log(BesselK): https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html */</span>
   sqrt_ab = <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span>a <span style="color: #006400; font-style: italic;">* b);</span>
   exp_K = BesselK<span style="color: #66cc66;">&#40;</span>p, sqrt_ab, <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* returns exp(y)*K_p(y) for y=sqrt(a*b) */</span>
   log_K = <span style="color: #0000ff;">log</span><span style="color: #66cc66;">&#40;</span>exp_K<span style="color: #66cc66;">&#41;</span> - sqrt_ab;
   C = <span style="color: #66cc66;">&#40;</span>p/<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*log(a/b) - log(2) - log_K;</span>   <span style="color: #006400; font-style: italic;">/* normalizing constant */</span>
&nbsp;
   i = loc<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span> &gt; <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>i<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">logPDF</span><span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = C + <span style="color: #66cc66;">&#40;</span>p-<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*log(x[i]) - 0.5*(a*x[i] + b/x[i]);</span>
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">logPDF</span><span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* PDF for the generalized inverse Gaussian distribution 
   evaluated at a column vector of values x, x[i] &gt; 0 for all i */</span>
start PDF_GIG<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, a, b, p<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">logPDF</span> = logPDF_GIG<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, a, b, p<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">exp</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">logPDF</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* test the functions. Visualize the PDF */</span>
a = <span style="color: #2e8b57; font-weight: bold;">1.4</span>; 
b = <span style="color: #2e8b57; font-weight: bold;">2.7</span>;
p = -<span style="color: #2e8b57; font-weight: bold;">0.5</span>;
<span style="color: #0000ff;">x</span> = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span>, <span style="color: #2e8b57; font-weight: bold;">3</span>, <span style="color: #2e8b57; font-weight: bold;">0.01</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
f = PDF_GIG<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, a, b, p<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;PDF of Generalized Inverse Gaussian Distribution&quot;</span>;
title2 <span style="color: #a020f0;">&quot;(a,b,p) = (1.4, 2.7, -0.5)&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, f<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/10/GIGdist1.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/GIGdist1.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60522" srcset="https://blogs.sas.com/content/iml/files/2026/10/GIGdist1.png 640w, https://blogs.sas.com/content/iml/files/2026/10/GIGdist1-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
As mentioned previously, when p = -1/2, the generalized inverse Gaussian distribution reduces to the ordinary inverse Gaussian, so this curve shape might look familiar to some readers. You can vary the values of the <em>p</em> parameter to see how the curve changes for <em>p</em> = 0, 1, and 2. As mentioned earlier, the <em>a</em> parameter controls the rate of decay of the right tail; the <em>b</em> parameter controls the decay of the left side of the PDF.
</p>

<h3>Summary</h3>
<p>
This short article shows how to use SAS IML to evaluate the PDF and log-PDF 
of the generalized inverse Gaussian (GIG) distribution. The distribution is defined in terms of the 
modified Bessel function of the second kind.  
I have not used the GIG distribution myself, but various internet sources claim that 
it is a flexible distribution that is used to model strictly positive data and to model variance parameters 
in Bayesian models.
</p> <p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html">Compute the generalized inverse Gaussian distribution in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/10/GIGdist1-150x150.png" />
	</item>
		<item>
		<title>The modified Bessel function of the second kind in SAS</title>
		<link>https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html#comments</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 12 Oct 2026 09:23:02 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Numerical Analysis]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=58936</guid>

					<description><![CDATA[<p>Bessel functions appear in surprising places. Although originally studied in physics as the solution to differential equations that describe waves and heat diffusion, Bessel functions also have applications in probability, statistics, and signal processing. SAS software provides the JBESSEL function, which is a Bessel function of the first kind, and [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html">The modified Bessel function of the second kind in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
<a href="https://en.wikipedia.org/wiki/Bessel_function">Bessel functions</a> appear in surprising places. 
Although originally studied in physics as the solution to differential equations that describe waves and heat diffusion,
Bessel functions also have applications in probability, statistics, and signal processing.
SAS software provides <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/lefunctionsref/p13zbsyioy421cn1ipphn1edwis1.htm">the JBESSEL function</a>, which is a Bessel function of the first kind,
and <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/lefunctionsref/n123ec4afwk7ben1ilrz6uor45ut.htm">the IBESSEL function</a>, which is a modified Bessel function of the first kind. <a href="https://blogs.sas.com/content/iml/2015/05/20/nuclear-bessels.html">I have previously written about these functions.</a>
</p>
<p>
A SAS customer recently asked me about how to implement the <em>modified Bessel function of the second kind</em> in SAS.
This Bessel function, which is often denoted by  <em>K</em><sub>&nu;</sub>(x), appears in the 
formulas for the generalized inverse Gaussian (GIG) distribution. The modified Bessel function of the second kind
is also used in survival analysis, spatial statistics, financial modeling, 
and to model variance parameters in Bayesian models.
Although SAS does not have a built-in "KBESSEL" function, you can define the <em>K</em><sub>&nu;</sub>(x) function 
in SAS IML. 
</p>

<h3>The definition of the modified Bessel function of the second kind</h3>
<p>
For the purpose of this article, the modified Bessel function of the second kind,
<em>K</em><sub>&nu;</sub>(x), where the parameter &nu; is a real number and the domain of the function is <em>x</em> &gt; 0.
A good way to compute the function is to use the integral definition from <a href="https://dlmf.nist.gov/10.32#E10">Equation 10.32.10</a> of the 
<em>NIST Digital Library of Mathematical Functions</em>:
<br />
<span class='MathJax_Preview'>\(
K_\nu(x) = \frac{1}{2} \left( \frac{x}{2} \right)^\nu \int_0^\infty t^{-\nu-1} \exp\left( -t - \frac{x^2}{4t} \right) \, dt
\)</span><script type='math/tex'>
K_\nu(x) = \frac{1}{2} \left( \frac{x}{2} \right)^\nu \int_0^\infty t^{-\nu-1} \exp\left( -t - \frac{x^2}{4t} \right) \, dt
</script>
</p>
<p>
In this formula, <em>x</em> and &nu; are parameters to the integrand. The dummy variable, <em>t</em>, is integrated from 0 to infinity.
The integrand has a peak that can be computed analytically by using calculus. The peak occurs at 
<br />
<span class='MathJax_Preview'>\(
t_{peak} = \frac{\sqrt{(\nu + 1)^2 + x^2} - (\nu + 1)}{2}
\)</span><script type='math/tex'>
t_{peak} = \frac{\sqrt{(\nu + 1)^2 + x^2} - (\nu + 1)}{2}
</script>

</p><p>
In the SAS IML Language, the QUAD subroutine is used to compute integrals.
Knowing the location of the peak is helpful because <a href="https://blogs.sas.com/content/iml/2014/08/13/peak-option-in-quad.html">the QUAD subroutine in IML contains a PEAK= option</a> that you can specify to assist the numerical integration routine. (Alternatively, you can perform a change of variables <em>u = t / t</em><sub>peak</sub> so that the peak is always at <em>u</em>=1. I leave that as an exercise.)
</p>


<h3>The optional exponential scaling factor</h3>
<p>
The documentation for the 
<a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/lefunctionsref/n123ec4afwk7ben1ilrz6uor45ut.htm">the IBESSEL function</a>, which is the modified Bessel function of the first kind, contains an optional binary argument. By default, the call
<tt>IBESSEL(nu, x)</tt> computes the function I<sub>&nu;</sub>(x). However, the function decays rapidly to zero as x increases, which makes the numerical computation difficult when x is moderately large (like x &ge; 50). Accordingly, a numerical trick is to compute the expression exp(x)*I<sub>&nu;</sub>(x), which you can do by using the syntax <tt>IBESSEL(nu, x, 1)</tt>. 
</p><p>
A similar situation occurs for the Bessel function of the second kind, K<sub>&nu;</sub>(x), which also decays quickly to zero for moderately large x.
(<a href="https://dlmf.nist.gov/10.40#E2">Equation 10.40.2</a> in the NIST Digital Library shows that the function decays asymptotically like exp(-x)/sqrt(x).)
When x is moderately large, it becomes numerically challenging to evaluate the function by using a standard numerical quadrature routine like CALL QUAD. The integration routine can prematurely terminate because the value of the integral is less than the algorithm's absolute error tolerance. 
</p>
<p>
Accordingly, it is common in numerical software for the syntax to support an optional binary flag that causes the function to return a "scaled value," which is exp(x)*K<sub>&nu;</sub>(x). The exponential scaling factor is evaluated as part of the integrand. This keeps the peak of the integrand near 1 and permits the quadrature routine to evaluate the integral accurately.
</p>
<p>
Not only does this trick enable you to compute the scaled value exp(x)*K<sub>&nu;</sub>(x) to high precision,
but it also enables you to find the value of  log(K<sub>&nu;</sub>(x)) accurately. Taking the natural log of the scaled value gives
log(exp(x)*K<sub>&nu;</sub>(x)) = x + log(K<sub>&nu;</sub>(x)), which you can solve for 
log(K<sub>&nu;</sub>(x)). This computation is shown in the next section.
The log of the Bessel function is used in applications such as loglikelihood computations.
</p>

<h3>Implement modified Bessel function of the second kind in SAS</h3>
<p>
Because SAS already supports the JBESSEL and IBESSEL functions, I will reserve the name KBESSEL for a 
future built-in SAS implementation. Instead, I will define a SAS IML function named BesselK, which takes three parameters: 
the parameter &nu;, the variable x, and an optional binary flag. If the binary flag is 0 (the default), the function will return
K<sub>&nu;</sub>(x), otherwise the function returns the scaled value exp(x)*K<sub>&nu;</sub>(x).
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* Define the integrand function for the unscaled modified 
   Bessel function of the second kind, K_{nu}(x)
 */</span>
start BesselK_integ<span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_BessK_nu, g_BessK_x<span style="color: #66cc66;">&#41;</span>;
   nu = g_BessK_nu; <span style="color: #0000ff;">x</span> = g_BessK_x;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> t<span style="color: #006400; font-style: italic;">**(-nu - 1) * exp(   -t - (x**2)/(4*t)) );</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Define the integrand function that includes the EXP term:
   exp(x)*K_{nu}(x). Use this scaled function when x is moderately large or you want log(K_{nu}(x)).
*/</span>
start BesselK_Scale_integ<span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_BessK_nu, g_BessK_x<span style="color: #66cc66;">&#41;</span>;
   nu = g_BessK_nu; <span style="color: #0000ff;">x</span> = g_BessK_x;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> t<span style="color: #006400; font-style: italic;">**(-nu - 1) * exp(x -t - (x**2)/(4*t)) );</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Define the wrapper function */</span>
start BesselK<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span>, scale=<span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_BessK_nu, g_BessK_x<span style="color: #66cc66;">&#41;</span>;
   g_BessK_nu = nu;
   <span style="color: #0000ff;">if</span> scale = <span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      funcName = <span style="color: #a020f0;">&quot;BesselK_integ&quot;</span>;
   <span style="color: #0000ff;">else</span> 
      funcName = <span style="color: #a020f0;">&quot;BesselK_Scale_integ&quot;</span>;
   <span style="color: #0000ff;">n</span> = nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   K = j<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">n</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, .<span style="color: #66cc66;">&#41;</span>; <span style="color: #006400; font-style: italic;">/* the result vector K_nu(x). Use missing for domain error such as x &lt;= 0 */</span>
   tau = nu+<span style="color: #2e8b57; font-weight: bold;">1</span>;
   <span style="color: #0000ff;">do</span> i = <span style="color: #2e8b57; font-weight: bold;">1</span> to <span style="color: #0000ff;">n</span>;
      <span style="color: #0000ff;">if</span> <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> &gt; <span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">do</span>;
         g_BessK_x = <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;
         <span style="color: #006400; font-style: italic;">/* Calculate the exact peak of the integrand */</span>
         pk = <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span>tau<span style="color: #006400; font-style: italic;">**2 + x[i]**2) - tau) / 2;</span>
         <span style="color: #0000ff;">call</span> QUAD<span style="color: #66cc66;">&#40;</span>integral_at_x, funcName, <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">0</span> .I<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span> PEAK=pk;
         K<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = integral_at_x;
      <span style="color: #0000ff;">end</span>;
   <span style="color: #0000ff;">end</span>;
   <span style="color: #006400; font-style: italic;">/* Multiply the integral by the leading constants */</span>
   K = <span style="color: #2e8b57; font-weight: bold;">0.5</span> <span style="color: #006400; font-style: italic;">* (x / 2)##nu # K;</span>
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span>K<span style="color: #66cc66;">&#41;</span>;
finish;
store module=<span style="color: #66cc66;">&#40;</span>BesselK_integ BesselK_Scale_integ BesselK<span style="color: #66cc66;">&#41;</span>;
<span style="color: #000080; font-weight: bold;">QUIT</span>;</pre></td></tr></table></div>




<p>
Let's test the function. First, let's visualize the function 
K<sub>&nu;</sub>(x) for &nu;=1 and <em>x</em> in (0, 3].
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
load module=<span style="color: #0000ff;">_all_</span>;
&nbsp;
<span style="color: #0000ff;">x</span> = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span>,<span style="color: #2e8b57; font-weight: bold;">3</span>,<span style="color: #2e8b57; font-weight: bold;">0.05</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
nu = <span style="color: #2e8b57; font-weight: bold;">1</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Modified Bessel Function of the Second Kind (nu=1)&quot;</span>;
K = BesselK<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, K<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/10/BesselK1.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/BesselK1.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60450" srcset="https://blogs.sas.com/content/iml/files/2026/10/BesselK1.png 640w, https://blogs.sas.com/content/iml/files/2026/10/BesselK1-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
The graph shows that the K<sub>&nu;</sub>(x) decays to 0 rapidly. 
Let's turn on the binary flag and visualize the function 
exp(x)*K<sub>&nu;</sub>(x) on the same domain:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Scaled Modified Bessel Function exp(x)*K(x) (nu=1)&quot;</span>;
expx_K = BesselK<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, expx_K<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/10/BesselK2.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/BesselK2.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60447" srcset="https://blogs.sas.com/content/iml/files/2026/10/BesselK2.png 640w, https://blogs.sas.com/content/iml/files/2026/10/BesselK2-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>


<p>
The graph shows that the exponentially scaled function still decays, but not as rapidly. 
For example, whereas K<sub>1</sub>(30) ~ 2.5E-14, the scaled function at x=30 is much larger: 
exp(30)*K<sub>1</sub>(30) ~ 0.23.
</p>

<p>
By using the scaled version, you can compute 
log(K<sub>&nu;</sub>(x)), which is useful for various applications:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* What good is the exp scaling? 
   1. Computations are more accurate for large values of x. 
   2. You can easily compute log(K_{nu}(x)) */</span>
<span style="color: #0000ff;">x</span> = <span style="color: #2e8b57; font-weight: bold;">50</span>;
expx_K = BesselK<span style="color: #66cc66;">&#40;</span>nu, <span style="color: #0000ff;">x</span>, <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
logK = <span style="color: #0000ff;">log</span><span style="color: #66cc66;">&#40;</span>expx_K<span style="color: #66cc66;">&#41;</span> - <span style="color: #0000ff;">x</span>;
print <span style="color: #0000ff;">x</span> expx_K logK;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/10/BesselK3.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/10/BesselK3.png" alt="" width="176" height="64" class="alignnone size-full wp-image-60453" /></a>

<p>
If you plan to compute log(K<sub>&nu;</sub>(x)) regularly, you could encapsulate this logic into 
a self-contained module.
</p>

<h3>Summary</h3>
<p>
This article shows how to implement the modified Bessel function of the second kind, K<sub>&nu;</sub>(x), in SAS.
The method involves integrating a complicated expression over an infinite domain. 
In addition, the article shows how you can compute the exponentially scaled expression exp(x)*K<sub>&nu;</sub>(x),
which enables you to evaluate log(K<sub>&nu;</sub>(x)).
</p><p>
In a subsequent article, I will show <a href="https://blogs.sas.com/content/iml/2026/10/19/generalize-inverse-gaussian-sas.html">how to use the K<sub>&nu;</sub> Bessel function to evaluate the PDF and log-PDF of the generalized inverse Gaussian distribution in SAS</a>.
</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html">The modified Bessel function of the second kind in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/10/12/besselk-function-sas.html/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/10/BesselK1-150x150.png" />
	</item>
		<item>
		<title>What is convolution and why is it important in statistics?</title>
		<link>https://blogs.sas.com/content/iml/2026/10/05/intro-convolution.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/10/05/intro-convolution.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 05 Oct 2026 09:27:37 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Data Analysis]]></category>
		<category><![CDATA[Numerical Analysis]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60255</guid>

					<description><![CDATA[<p>A convolution is a mathematical operation on two discrete sequences (or continuous functions) that produces a new sequence (or function). In probability and statistics, a convolution is closely associated with the concept of a "moving window," which time series analysts often call a "filter." If you have ever smoothed a [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/10/05/intro-convolution.html">What is convolution and why is it important in statistics?</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
A convolution is a mathematical operation on two discrete sequences (or continuous functions) that produces a new sequence (or function). In probability and statistics, a convolution is closely associated with the concept of a "moving window," which time series analysts often call a "filter."
If you have ever smoothed a time series, created a kernel density estimate, or calculated the distribution of the sum of two independent random variables, you have used a convolution, whether you realized it or not. 
</p>

<p>This article provides the mathematical background for a discrete convolution operation.
It discusses a SAS IML function, DFCONV, that you can use to compute a discrete convolution.
The convolution operation is illustrated by using two classical statistical applications.
The first is the sum of two independent discrete random variables. The second is the 
computation of a moving average for a time series.
</p>

<h3>The formula for a discrete convolution</h3>
<p>
The convolution operation comes in two forms: a continuous convolution that operates on functions, and a discrete convolution that operates on sequences. This article discusses only the discrete convolution operator. The discrete convolution operator is a binary operation on two sequences, u and v. It produces a new sequence, denoted u*v, by using multiplication and addition of the terms in the original sequences. 
Each element of u*v is a dot product for a subsequence of elements in u and v.
</p>
<p>
In math, the two sequences are usually indexed starting at 0. That is, u = {u<sub>0</sub>, u<sub>1</sub>, ..., u<sub>M-1</sub>} and v = {v<sub>0</sub>, v<sub>1</sub>, ..., v<sub>N-1</sub>}. The sequence u has M elements; the sequence v has N elements. The full convolution u*v is a new sequence that has M+N-1 elements (indexed from 0 to M+N-2). The k-th element of u*v, denoted as (u*v)(k), is defined as:
<br />
<span class='MathJax_Preview'>\( (u*v)(k) = \sum_{j=\max(0, k-N+1)}^{\min(k, M-1)} u(j)v(k-j) \)</span><script type='math/tex'> (u*v)(k) = \sum_{j=\max(0, k-N+1)}^{\min(k, M-1)} u(j)v(k-j) </script>
</p>

<p>
If you adopt the convention that the sequences are infinite and that the unspecified terms of the sequences are zero, 
this formula can be written more simply:
<br />
<span class='MathJax_Preview'>\( (u*v)(k) = \sum_{j=-\infty}^{\infty} u(j)v(k-j) \)</span><script type='math/tex'> (u*v)(k) = \sum_{j=-\infty}^{\infty} u(j)v(k-j) </script>
<br />
This version makes it look more like the continuous convolution operator, which replaces the summation with an integral.
The convolution is commutative, so you can also use u(k-j)v(j) in the formula.  I use this fact in the section about time-series smoothing. 
</p>


<h3>Computing a convolution: The DFCONV function in SAS IML</h3>
<p>
In Appendix A, I show how to "manually" compute a discrete convolution between two vectors in the 
SAS IML language. (The SAS IML language uses one-based indexing, so the indices in the implementation are slightly different than in the formula that I showed in the previous section.)
But, you don't need to write any code to use a convolution. The SAS IML language provides a built-in function, 
<a href="https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/imlug/imlug_langref_sect112.htm">the DFCONV function</a>, 
which automatically computes the convolution and a few useful variations. The documentation shows the formula for vectors that use one-based indexing.
The 'DF'
prefix stands for 'Digital Filter', which is the name that electrical engineers use 
for operations that process digital signals.
</p>
<p>
Let's look at a simple numeric example. Suppose that 
u = {1,2,3} and v = {4,5,6,7,8} are vectors of length M=3 and N=5, respectively.
You can use the DFCONV function to compute the convolution y = u*v, as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
u = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">2</span>,<span style="color: #2e8b57; font-weight: bold;">3</span><span style="color: #66cc66;">&#125;</span>;
v = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">4</span>,<span style="color: #2e8b57; font-weight: bold;">5</span>,<span style="color: #2e8b57; font-weight: bold;">6</span>,<span style="color: #2e8b57; font-weight: bold;">7</span>,<span style="color: #2e8b57; font-weight: bold;">8</span><span style="color: #66cc66;">&#125;</span>;
y = dfconv<span style="color: #66cc66;">&#40;</span>u,v<span style="color: #66cc66;">&#41;</span>;
print y;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/dfconv1.png" alt="" width="37" height="231" class="alignnone size-full wp-image-60387" />

<p>Appendix A provides the step-by-step manual computations that verify that the output is correct. 
Notice that the output length is N + M - 1 = 3 + 5 - 1 = 7.
</p>


<h3>Example 1: The sum of two independent random variables</h3>
<p>
An example of a discrete convolution in probability theory is the distribution of the sum of two independent rolls of dice.
When you sum two independent random variables, the distribution of the sum is the convolution of their individual probability distributions.
</p>
<p>A classic example is two fair six-sided dice. Let <i>X</i> and <i>Y</i> be the outcomes of the two dice. Both follow a discrete uniform distribution. The probability mass function (PMF) for a single die can be represented as a vector of probabilities for the outcomes 1 through 6. Thus,
u = {1/6, 1/6, 1/6, 1/6, 1/6, 1/6} and v = {1/6, 1/6, 1/6, 1/6, 1/6, 1/6} are the PMFs.
</p>
<p>
Let Z = X + Y be the sum of the dice faces. The random variable Z takes on values in the range 2, 3, 4, ..., 12.
The probability that Z=2 is relatively small because there is only one way ("snake eyes") for that sum to occur.
In contrast, there are six equally likely ways for the sum to be 7: 1+6, 2+5, 3+4, 4+3, 5+2, and 6+1. 
In general, if the sum of the two dice is <em>s</em>, and if <em>X=k</em>, then we know that second die has the value <em>s-k</em>.
Thus, to find the probability that <em>Z=s</em>, we must sum the probabilities that <em>X=k</em> and <em>Y=s-k</em> for <em>k</em>=1..6.
</p>
<p>
Because X and Y are independent, the probability that <em>X=k</em> and <em>Y=s-k</em> is the product
P(<em>X=k</em>)*P(<em>Y=s-k</em>). To find the complete probability that Z=s, we sum over all the ways that 
the sum <em>s</em> can occur. This leads to the formula 
<br />
<span class='MathJax_Preview'>\( P(Z = s) = \sum_{k} P(X = k) P(Y = s - k) \)</span><script type='math/tex'> P(Z = s) = \sum_{k} P(X = k) P(Y = s - k) </script>
<br />
The right side of the formula is the k_th element of a convolution.
Thus, to find the probability distribution of the sum of two dice, you can convolve 
the PMFs for each die.
</p>
<p>
You can use the DFCONV function in IML to find the distribution of the sum of two six-sided dice, as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Example: Discrete convoution of rolling two fair six-sided dice */</span>
<span style="color: #000080; font-weight: bold;">proc iml</span>;
prob_d6 = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#125;</span> / <span style="color: #2e8b57; font-weight: bold;">6</span>;            <span style="color: #006400; font-style: italic;">/* PMF of six-side fair die */</span>
prob_2dice = dfconv<span style="color: #66cc66;">&#40;</span>prob_d6, prob_d6<span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* PMF of sum of two dice */</span>
print prob_2dice<span style="color: #66cc66;">&#91;</span>r=<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">2</span>:<span style="color: #2e8b57; font-weight: bold;">12</span><span style="color: #66cc66;">&#41;</span> F=FRACT12.<span style="color: #66cc66;">&#93;</span>;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/dfconv2.png" alt="" width="93" height="336" class="alignnone size-full wp-image-60384" srcset="https://blogs.sas.com/content/iml/files/2026/09/dfconv2.png 93w, https://blogs.sas.com/content/iml/files/2026/09/dfconv2-83x300.png 83w" sizes="(max-width: 93px) 100vw, 93px" />

<p>
The PMF for each die has six elements. Thus, 
the convolution is a vector of length <i>6 + 6 - 1 = 11</i>, which corresponds to the sums 2-12.
The PMF of the sum is the familiar triangular distribution, which peak at the sum of 7 with a probability of 6/36 or 1/6.
</p>
<p>
If you want the sum of three dice, you can convolve the distribution of the sum with the distribution of another fair die,
as follows:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Want three dice? Convolve the probability distribution for a six-sided 
   die with the distribution for two independent dice. */</span>
prob_3dice = dfconv<span style="color: #66cc66;">&#40;</span>prob_d6, prob_2dice<span style="color: #66cc66;">&#41;</span>;
print prob_3dice<span style="color: #66cc66;">&#91;</span>r=<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">3</span>:<span style="color: #2e8b57; font-weight: bold;">18</span><span style="color: #66cc66;">&#41;</span> F=FRACT12.<span style="color: #66cc66;">&#93;</span>;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/dfconv3.png" alt="" width="91" height="472" class="alignnone size-full wp-image-60381" srcset="https://blogs.sas.com/content/iml/files/2026/09/dfconv3.png 91w, https://blogs.sas.com/content/iml/files/2026/09/dfconv3-58x300.png 58w" sizes="(max-width: 91px) 100vw, 91px" />

<p>
You can continue this process as many times as you like. 
You can compare the result to <a href="https://blogs.sas.com/content/iml/2024/08/26/formula-sum-of-dice.html">the classical formula for rolling n six-sided dice</a>.
If the dice are not fair, you can replace the vectors u and v with other vectors that specify the probability for each face.
</p>


<h3>Example 2: Moving averages in time series</h3>
<p>
A second application of convolution is smoothing a sequence of data points by using a moving window analysis. 
When you apply a moving average, you convolve a short sequence (the filter or kernel) with a longer data sequence.
I have previously discussed <a href="https://blogs.sas.com/content/iml/2016/01/25/moving-average.html">how to compute a moving average</a> and 
<a href="https://blogs.sas.com/content/iml/2016/01/27/moving-average-in-sas.html">how to compute a moving average in SAS</a> by using PROC EXPAND or SAS IML functions. 
</p>
<p>
In the previous post, I use PROC EXPAND to find two different (backward) moving averages of the monthly price of IBM stock in the late 1990s and early 2000s. The following SAS statements smooth 120 prices and create a graph that overlays the scatter plot, a moving average, and a weighted moving average. See the previous article for an explanation and discussion.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Example from https://blogs.sas.com/content/iml/2016/01/27/moving-average-in-sas.html */</span>
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Monthly IBM Stock Price&quot;</span>;
<span style="color: #000080; font-weight: bold;">proc sort</span> <span style="color: #000080; font-weight: bold;">data</span>=sashelp.stocks<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">where</span>=<span style="color: #66cc66;">&#40;</span>STOCK=<span style="color: #a020f0;">'IBM'</span><span style="color: #66cc66;">&#41;</span> <span style="color: #0000ff;">rename</span>=<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">Date</span>=t <span style="color: #0000ff;">Close</span>=y<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> 
          out=Series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">keep</span>=t y<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">where</span> <span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'01JAN1996'</span>d &lt;= t &lt;= <span style="color: #a020f0;">'31DEC2005'</span>d<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">by</span> t;
<span style="color: #000080; font-weight: bold;">run</span>;
&nbsp;
<span style="color: #006400; font-style: italic;">/* create three moving average curves. Use the TRIM option to remove 
   edge effects and compute only the &quot;middle&quot; of the smoother. */</span>
<span style="color: #000080; font-weight: bold;">proc expand</span> <span style="color: #000080; font-weight: bold;">data</span>=Series out=out method=none;
   id t;
   convert y = MA   / transout=<span style="color: #66cc66;">&#40;</span>movave <span style="color: #2e8b57; font-weight: bold;">5</span> <span style="color: #0000ff;">trim</span> <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>;          <span style="color: #006400; font-style: italic;">/* backward MA(5) */</span>
   convert y = WMA  / transout=<span style="color: #66cc66;">&#40;</span>movave<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #2e8b57; font-weight: bold;">2</span> <span style="color: #2e8b57; font-weight: bold;">3</span> <span style="color: #2e8b57; font-weight: bold;">4</span> <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span> <span style="color: #0000ff;">trim</span> <span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #006400; font-style: italic;">/* backward WMA   */</span>
<span style="color: #000080; font-weight: bold;">run</span>;
&nbsp;
<span style="color: #000080; font-weight: bold;">proc sgplot</span> <span style="color: #000080; font-weight: bold;">data</span>=out cycleattrs;
   scatter <span style="color: #0000ff;">x</span>=t y=y;
   series <span style="color: #0000ff;">x</span>=t y=MA   / name=<span style="color: #a020f0;">'MA'</span>   legendlabel=<span style="color: #a020f0;">&quot;MA(5)&quot;</span>;
   series <span style="color: #0000ff;">x</span>=t y=WMA  / name=<span style="color: #a020f0;">'WMA'</span>  legendlabel=<span style="color: #a020f0;">&quot;WMA(1,2,3,4,5)&quot;</span>;
   keylegend <span style="color: #a020f0;">'MA'</span> <span style="color: #a020f0;">'WMA'</span>;
   xaxis <span style="color: #0000ff;">display</span>=<span style="color: #66cc66;">&#40;</span>nolabel<span style="color: #66cc66;">&#41;</span> grid;
   yaxis <span style="color: #0000ff;">label</span>=<span style="color: #a020f0;">&quot;Closing Price&quot;</span> grid;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>





<a href="https://blogs.sas.com/content/iml/files/2026/09/dfconv4.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/dfconv4.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60390" srcset="https://blogs.sas.com/content/iml/files/2026/09/dfconv4.png 640w, https://blogs.sas.com/content/iml/files/2026/09/dfconv4-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>


<p>PROC EXPAND has <a href="https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/etsug/etsug_expand_details19.htm">various options to deal with averages at the beginning and end of the sequence</a>, where there are not enough points to perform a full convolution. By default, it adjusts the width of the moving window. To avoid a discussion of edge effects, I used the TRIM option to output missing values for the first and last five averaged values. Thus, the graph shows smoothers that do not predict values for the first five and the last five observations. 
I will do the same after convolving the window and the data. In this way, I avoid a distracting discussion about why the default behavior of PROC EXPAND deviates from the mathematical definition of a convolution.
</p>
<p>
Let's perform the moving average computation in SAS IML by using a convolution. We want the filter elements to sum to unity,
A simple backward moving average with a window width of 5 corresponds to a filter with values u={1,1,1,1,1}/5.
The backward weighted moving average corresponds to u={5,4,3,2,1}/15.
Notice that the order of the elements in the weighted kernel are reversed from the PROC EXPAND order.
Why? Well, the mathematical definition of a convolution flips the kernel shape (that is, it uses u(k-j) to compute the k_th smoothed point). 
We therefore need to manually reverse the elements in u before calling the DFCONV function so that the output agrees with the
backward moving average from PROC EXPAND.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* perform a similar computation by using convolution */</span>
<span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* read the data into v */</span>
use Series;  read all <span style="color: #0000ff;">var</span> <span style="color: #a020f0;">&quot;y&quot;</span> <span style="color: #0000ff;">into</span> v;  <span style="color: #0000ff;">close</span>;
&nbsp;
u = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#125;</span> / <span style="color: #2e8b57; font-weight: bold;">5</span>;   <span style="color: #006400; font-style: italic;">/* MA(5) */</span>
MA = dfconv<span style="color: #66cc66;">&#40;</span>u, v<span style="color: #66cc66;">&#41;</span>;
<span style="color: #006400; font-style: italic;">/* reverse the filter elements to match the PROC EXPAND output for a backward MA */</span>   
u = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">5</span>,<span style="color: #2e8b57; font-weight: bold;">4</span>,<span style="color: #2e8b57; font-weight: bold;">3</span>,<span style="color: #2e8b57; font-weight: bold;">2</span>,<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#125;</span> / <span style="color: #2e8b57; font-weight: bold;">15</span>;  <span style="color: #006400; font-style: italic;">/* WMA(1,2,3,4,5) */</span>
WMA = dfconv<span style="color: #66cc66;">&#40;</span>u, v<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #006400; font-style: italic;">/* We want to compare with PROC EXPAND. The PROC
   1) outputs N elements.
   2) has special handling for the first and last N obs.
*/</span>
M = nrow<span style="color: #66cc66;">&#40;</span>u<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">N</span> = nrow<span style="color: #66cc66;">&#40;</span>v<span style="color: #66cc66;">&#41;</span>;
MA  = MA<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span>:<span style="color: #0000ff;">N</span><span style="color: #66cc66;">&#93;</span>;    <span style="color: #006400; font-style: italic;">/* keep only N elements */</span>
WMA = WMA<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span>:<span style="color: #0000ff;">N</span><span style="color: #66cc66;">&#93;</span>;
&nbsp;
firstObs = <span style="color: #2e8b57; font-weight: bold;">1</span>:M;
lastObs  = <span style="color: #66cc66;">&#40;</span>N-M+<span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0000ff;">N</span>; 
MA <span style="color: #66cc66;">&#91;</span>firstObs||lastObs<span style="color: #66cc66;">&#93;</span> = .;  <span style="color: #006400; font-style: italic;">/* set the first/last obs to missing */</span>
WMA<span style="color: #66cc66;">&#91;</span>firstObs||lastObs<span style="color: #66cc66;">&#93;</span> = .;
&nbsp;
<span style="color: #0000ff;">create</span> IML_MA <span style="color: #0000ff;">var</span> <span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">'MA'</span> <span style="color: #a020f0;">'WMA'</span><span style="color: #66cc66;">&#125;</span>;  append;  <span style="color: #0000ff;">close</span>;
<span style="color: #000080; font-weight: bold;">QUIT</span>;
&nbsp;
<span style="color: #000080; font-weight: bold;">proc compare</span> base=out<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">keep</span>=MA WMA<span style="color: #66cc66;">&#41;</span> compare=IML_MA 
             method=absolute criterion=1E-12;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>





<div class="wp_syntax"><table><tr><td class="code"><pre class="text" style="font-family:monospace;">                                       Observation Summary                                        
&nbsp;
                                  Observation      Base  Compare                                  
&nbsp;
                                  First Obs           1        1                                  
                                  Last  Obs         120      120                                  
&nbsp;
                 Number of Observations in Common: 120.                                           
                 Total Number of Observations Read from WORK.OUT: 120.                            
                 Total Number of Observations Read from WORK.IML_MA: 120.                         
&nbsp;
                 Number of Observations with Some Compared Variables Unequal: 0.                  
                 Number of Observations with All Compared Variables Equal: 120.</pre></td></tr></table></div>




<p>
The IML values (computed by using a convolution) agree with the PROC EXPAND values to within 1E-12. (In fact, the largest difference
for this example is 5.68E-14.) If we had not used the TRIM option in PROC EXPAND, then there would be differences in the first few observations because PROC EXPAND uses a varying-width kernel near the beginning and end of the data series.
</p>

<h3>Summary</h3>
<p>
This article discusses the mathematical definition of a discrete convolution operator. 
In SAS, you can use the DFCONV function in SAS IML to convolve two vectors of arbitrary lengths. 
The result is a new longer vector. The convolution operator is illustrated by using two examples: 
the distribution of the sum of two six-sided dice, and the smoothing of a time series by using a moving average.
</p>



<h3>Appendix A: Manual computation of a discrete convolution</h3>
<p>
This appendix shows a simple manual computation of discrete convolution for two vectors. 
It is presented so that you can compare the output of the DFCONV function with a function 
that directly implements the convolution formula.
</p><p>
Suppose you define a vector, u={1,2,3}, which has M=3 elements, 
and a vector, v={4,5,6,7,8}, which has N=5 elements.
If you want to compute their convolution, y=u*v, you can use the following manual computations.
These computations assume zero-based indexing. For this problem, the convolution has M+N-1 = 7 elements:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="text" style="font-family:monospace;">y[0] = u[0]v[0] = 1*4 = 4
y[1] = u[0]v[1] + u[1]v[0] = (1*5) + (2*4) = 13
y[2] = u[0]v[2] + u[1]v[1] + u[2]v[0] = (1*6) + (2*5) + (3*4) = 28
y[3] = u[0]v[3] + u[1]v[2] + u[2]v[1] = (1*7) + (2*6) + (3*5) = 34
y[4] = u[0]v[4] + u[1]v[3] + u[2]v[2] = (1*8) + (2*7) + (3*6) = 40
y[5] = u[1]v[4] + u[2]v[3] = (2*8) + (3*7) = 37
y[6] = u[2]v[4] = 3*8 = 24</pre></td></tr></table></div>



<p>
Thus, the convolution y=u*v is a new vector, 
y = {4,13,28,34,40,37,24}.
</p>
<p>
There are two issues when turning this into a computation. First, the IML language 
uses one-based indexing, not zero-based. Second, a naive implementation would use
a pair of nested loops and perform scalar multiplication and addition, which is 
inefficient in a vectorized language. A better implementation is to use 
a dot product to perform the sums of the products of subsequences. 
After the first few elements of the vector v, the dot products will always 
use subsequences of length M, which is the length of u.
</p><p>
The following computation implements the definition of the 
discrete convolution formula. 
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* y = conv(u,v) convolves column vectors u and v. 
   Algebraically, convolution is the same operation as 
   multiplying the polynomials whose coefficients are the 
   elements of u and v. 
*/</span>
start conv_manual<span style="color: #66cc66;">&#40;</span>u,v<span style="color: #66cc66;">&#41;</span>;
   m = nrow<span style="color: #66cc66;">&#40;</span>u<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">n</span> = nrow<span style="color: #66cc66;">&#40;</span>v<span style="color: #66cc66;">&#41;</span>;
   ny = m + <span style="color: #0000ff;">n</span> - <span style="color: #2e8b57; font-weight: bold;">1</span>;
   y = j<span style="color: #66cc66;">&#40;</span>ny, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #0000ff;">do</span> k = <span style="color: #2e8b57; font-weight: bold;">1</span> to ny;
      idx = <span style="color: #0000ff;">max</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>, k+<span style="color: #2e8b57; font-weight: bold;">1</span>-<span style="color: #0000ff;">n</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0000ff;">min</span><span style="color: #66cc66;">&#40;</span>k,m<span style="color: #66cc66;">&#41;</span>; 
      y<span style="color: #66cc66;">&#91;</span>k<span style="color: #66cc66;">&#93;</span> = u<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span>` <span style="color: #006400; font-style: italic;">* v[k + 1 - idx];</span>
   <span style="color: #0000ff;">end</span>;
   <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span>y<span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* test the computation */</span>
u = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">1</span>,<span style="color: #2e8b57; font-weight: bold;">2</span>,<span style="color: #2e8b57; font-weight: bold;">3</span><span style="color: #66cc66;">&#125;</span>;
v = <span style="color: #66cc66;">&#123;</span><span style="color: #2e8b57; font-weight: bold;">4</span>,<span style="color: #2e8b57; font-weight: bold;">5</span>,<span style="color: #2e8b57; font-weight: bold;">6</span>,<span style="color: #2e8b57; font-weight: bold;">7</span>,<span style="color: #2e8b57; font-weight: bold;">8</span><span style="color: #66cc66;">&#125;</span>;
y1 = conv_manual<span style="color: #66cc66;">&#40;</span>u,v<span style="color: #66cc66;">&#41;</span>;
<span style="color: #006400; font-style: italic;">/* compare to the built-in IML function */</span>
y2 = dfconv<span style="color: #66cc66;">&#40;</span>u,v<span style="color: #66cc66;">&#41;</span>;
print y1 y2;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/dfconv5.png" alt="" width="73" height="234" class="alignnone size-full wp-image-60378" />

<p>
Notice the statement, <tt>idx = max(1, k+1-n):min(k,m)</tt>, which selects the indices to use for the dot product.
This statement corresponds to the summation limits in the mathematical formula earlier.
In the formula, the lower limit of summation is max(0, k-N+1) and the upper limit  is min(k, M-1). 
The IML statement adjusts these limits to account for 1-based indexing. 
</p>

<h3>Appendix B: Convolution as matrix-vector multiplication</h3>
<p>
</p><p>
Incidentally, the first time I saw a convolution operator was in a course in Linear Algebra where it was presented as an
example of a bilinear operator between two vector spaces. Accordingly, you can represent a convolution as a matrix-vector
multiplication where the matrix T=T(v) is a Toeplitz-type
matrix of the appropriate dimension and padded with zeros. 
In honor of my now-deceased Cornell math professor, Keith Dennis, I'll show how to construct the matrix 
and use it to compute a convolution in IML:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="text" style="font-family:monospace;">ny = nrow(v) + nrow(u) - 1;
Tv = j(ny, nrow(u), 0);
do i = 1 to nrow(u);
   Tv[i:(i+nrow(v)-1),i] = v;    /* create a Toeplitz-type matrix by copying v into columns */
end;
y3 = Tv*u;                       /* matrix-vector multiplication */
print Tv, y3;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/dfconv6.png" alt="" width="70" height="466" class="alignnone size-full wp-image-60375" srcset="https://blogs.sas.com/content/iml/files/2026/09/dfconv6.png 70w, https://blogs.sas.com/content/iml/files/2026/09/dfconv6-45x300.png 45w" sizes="(max-width: 70px) 100vw, 70px" />

<p>
In practice, there is no advantage to construct a large matrix and perform matrix-vector multiplication.
You can save RAM memory
and compute a series of dot products instead.
Nevertheless, it's a cool result!
</p><p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/10/05/intro-convolution.html">What is convolution and why is it important in statistics?</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/10/05/intro-convolution.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/09/dfconv4-150x150.png" />
	</item>
		<item>
		<title>What is Owen&#039;s T function?</title>
		<link>https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 28 Sep 2026 09:21:17 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Numerical Analysis]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60261</guid>

					<description><![CDATA[<p>While researching a topic in probability, I encountered a special mathematical function that I had not previously known about. The function is called Owen's T function (Owen, 1956, Ann. Math. Stat.). It is useful for computing multivariate probabilities, for defining the skew-normal distribution, and for computing probabilities associated with certain [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html">What is Owen&#039;s T function?</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
While researching a topic in probability, I encountered a special mathematical function that I had not previously known about. The function is called Owen's T function (<a href="https://www.jstor.org/stable/2237196">Owen, 1956, Ann. Math. Stat.</a>).
It is useful for computing multivariate probabilities, for defining the skew-normal distribution, and for computing probabilities associated with certain hypothesis tests.
This article shows how to compute and visualize Owen's T function in SAS. I will show applications of Owen's T function in a subsequent article.
</p>
<p>
Owen's T function is defined as a one-dimensional integral, so this article uses the QUAD subroutine in SAS IML to evaluate it. However, it is worth mentioning that 
<a href="https://ideas.repec.org/a/jss/jstsof/v005i05.html">Patefield, M. and Tandy, D. (2000, <em>JSS</em>)</a> provide a 
faster and more accurate algorithm. Their algorithm is more complex. It evaluates the function
by selecting from among six different numerical methods, depending on the specified values of (x, &alpha;).
</p>

<h3>The definition of Owen's T function</h3>
<p>
The definition of Owen's T function, T(x, &alpha;), uses &alpha; as the upper limit of an integral and <em>X</em> as a parameter to the integrand:
<br />
<span class='MathJax_Preview'>\(
T(x, \alpha) = \frac{1}{2\pi} \int_0^\alpha \frac{e^{-\frac{x^2}{2}(1+t^2)}}{1+t^2} dt
\)</span><script type='math/tex'>
T(x, \alpha) = \frac{1}{2\pi} \int_0^\alpha \frac{e^{-\frac{x^2}{2}(1+t^2)}}{1+t^2} dt
</script>
</p>
<p>
From this definition, it is clear that T is an even function in x and an odd function in &alpha;:
</p>
<ul>
<li>T is symmetric in x: T(-x, &alpha;) = T(x, &alpha;)</li>
<li>T is anti-symmetric in &alpha;: T(x, -&alpha;) = -T(x, &alpha;)</li>
</ul>
<p>
It is less obvious that Owen's T function simplifies if x=0 or &alpha;=1:
</p>
<ul>
<li> T(0,&alpha;) = 1/(2 &pi;) tan<sup>-1</sup>(&alpha;) </li>
<li> T(x,1) = 1/2 * &Phi;(x) (1 - &Phi;(x)), where &Phi;(x) is the standard univariate normal CDF.
</li>
</ul>
<p>
The derivative (with respect to x) of Owen's T function is the product of two familiar functions.
If you take the derivative, differentiate under the integral sign, and then simplify, you obtain 
</p>
<ul>
<li> T'(x,&alpha;) = -&phi;(x) [&Phi;(&alpha; x) - 1/2], where &phi;(x) is the PDF and &Phi;(x) is CDF of the standard univariate normal distribution.
</li>
</ul>


<h3>Define Owen's T function in SAS</h3>
<p>
<a href="https://blogs.sas.com/content/iml/2011/05/06/how-to-numerically-integrate-a-function-in-sas.html">The QUAD subroutine in SAS IML is a general-purpose integration routine</a>. 
The domain of integration in the formula is [0, &alpha;]. However, &alpha; can be negative, so
it might be necessary to <a href="https://blogs.sas.com/content/iml/2014/08/04/reversing-the-limits-of-integration.html">reverse the limits of integration</a>. 
To handle that possibility, 
I specify the domain of integration as [0, |&alpha;|] and negate the answer if &alpha; &lt; 0.
Here is one way to define Owen's T function:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* Define the Integrand for Owen's T function:
   The QUAD subroutine passes a scalar value, t, during the integration process.
   Use the GLOBAL statement to pass the parameter value, x (via 'g_x').
*/</span>
start OwenT_Integrand<span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_x<span style="color: #66cc66;">&#41;</span>;
   t2 = <span style="color: #2e8b57; font-weight: bold;">1</span> + t##<span style="color: #2e8b57; font-weight: bold;">2</span>;
   <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #0000ff;">exp</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #2e8b57; font-weight: bold;">0.5</span> <span style="color: #006400; font-style: italic;">* g_x##2 * t2) / t2 );</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Define Owen's T Function by integrating OwenT_Integrand on [0, alpha].
   Loop over the elements of x to allow vector inputs. alpha is a scalar.
*/</span>
start OwenT<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha<span style="color: #66cc66;">&#41;</span> global<span style="color: #66cc66;">&#40;</span>g_x<span style="color: #66cc66;">&#41;</span>;
   pi = constant<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;pi&quot;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">n</span> = nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   y = j<span style="color: #66cc66;">&#40;</span>nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, .<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #006400; font-style: italic;">/* make sure limits of integration are increasing. If alpha &lt; 0, reverse sign of answer */</span>
   limits = <span style="color: #2e8b57; font-weight: bold;">0</span> || <span style="color: #0000ff;">abs</span><span style="color: #66cc66;">&#40;</span>alpha<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">do</span> i = <span style="color: #2e8b57; font-weight: bold;">1</span> to <span style="color: #0000ff;">n</span>;
      g_x = <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;   <span style="color: #006400; font-style: italic;">/* set parameter, 'x' */</span>
      <span style="color: #0000ff;">call</span> quad<span style="color: #66cc66;">&#40;</span>val, <span style="color: #a020f0;">&quot;OwenT_Integrand&quot;</span>, limits<span style="color: #66cc66;">&#41;</span>;
      y<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = val;
   <span style="color: #0000ff;">end</span>;
   <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> choose<span style="color: #66cc66;">&#40;</span>alpha&gt;=<span style="color: #2e8b57; font-weight: bold;">0</span>, y/<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #006400; font-style: italic;">*pi), -y/(2*pi)) );</span> <span style="color: #006400; font-style: italic;">/* negate answer if alpha &lt; 0 */</span>
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* test evaluating the function for x in [-3,3] */</span>
<span style="color: #0000ff;">x</span> = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #2e8b57; font-weight: bold;">3</span>, <span style="color: #2e8b57; font-weight: bold;">3</span>, <span style="color: #2e8b57; font-weight: bold;">6</span>/<span style="color: #2e8b57; font-weight: bold;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
alpha = <span style="color: #2e8b57; font-weight: bold;">1</span>;
T = OwenT<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, alpha<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Graph of Owen's T Function: alpha=1&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, T<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/09/OwenT1.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/OwenT1.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60303" srcset="https://blogs.sas.com/content/iml/files/2026/09/OwenT1.png 640w, https://blogs.sas.com/content/iml/files/2026/09/OwenT1-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
The plot shows the graph of Owen's T function when the parameter &alpha; is fixed at &alpha;=1 and 
the parameter x is in the interval [-3, 3].
You can see that the graph looks somewhat bell-shaped. 
</p>
<p>
The following panel of graphs shows the T(x, &alpha;) function for various values of &alpha;.
You can see that the shape of the function is similar for all &alpha; values, but the amplitude of the function depends on &alpha;. You can show analytically that the magnitude of the T function is greatest at x=0.
The height of the function at x=0 is 1/(2 &pi;) tan<sup>-1</sup>(&alpha;).
</p>

<a href="https://blogs.sas.com/content/iml/files/2026/09/OwenT2.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/OwenT2.png" alt="" width="360" height="480" class="alignnone size-full wp-image-60309" srcset="https://blogs.sas.com/content/iml/files/2026/09/OwenT2.png 480w, https://blogs.sas.com/content/iml/files/2026/09/OwenT2-225x300.png 225w" sizes="(max-width: 360px) 100vw, 360px" /></a>

<p>
If you like 3-D graphs, the Boost C++ library contains <a href="https://www.boost.org/doc/libs/latest/libs/math/doc/html/math_toolkit/owens_t.html">a graph of T(x, &alpha;)</a> over a rectangular domain.
</p>

<h3>Summary</h3>
<p>
Owen's T function is defined as a one-dimensional integral with two parameters. This article uses the QUAD subroutine in SAS IML to evaluate the integral for any parameter values. A subsequent article will discuss applications of Owen's T function in probability and statistics.
</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html">What is Owen&#039;s T function?</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/09/28/owen-t-function.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/09/OwenT1-150x150.png" />
	</item>
		<item>
		<title>How to compare two independent Monte Carlo estimates</title>
		<link>https://blogs.sas.com/content/iml/2026/09/21/diff-mc-estimates.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/09/21/diff-mc-estimates.html#respond</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 21 Sep 2026 09:30:23 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60192</guid>

					<description><![CDATA[<p>I write a lot of Monte Carlo simulations. This article discusses how to assess whether two independent Monte Carlo estimates are close to each other. This result can be used to test the correctness of a Monte Carlo simulation. It can also be used to compare different Monte Carlo algorithms [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/09/21/diff-mc-estimates.html">How to compare two independent Monte Carlo estimates</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
I write a lot of Monte Carlo simulations. This article discusses how to assess whether two independent Monte Carlo estimates are close to each other. This result can be used to test the correctness of a Monte Carlo simulation. It can also be used to <a href="https://blogs.sas.com/content/iml/2016/03/14/monte-carlo-estimates-of-pi.html">compare different Monte Carlo algorithms that compute the same quantity</a>.
</p>

<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/MCDiff1-1.png" alt="" width="397" height="200" class="alignright size-full wp-image-60234" srcset="https://blogs.sas.com/content/iml/files/2026/09/MCDiff1-1.png 397w, https://blogs.sas.com/content/iml/files/2026/09/MCDiff1-1-300x151.png 300w, https://blogs.sas.com/content/iml/files/2026/09/MCDiff1-1-164x82.png 164w" sizes="(max-width: 397px) 100vw, 397px" />

<p>
A Monte Carlo (MC) simulation provides both a statistical estimate for a parameter and a confidence interval for the parameter. (The confidence interval assumes that the estimate follows a normal distribution.)
If you run two independent MC simulations to estimate the same parameter, how close will the two estimates be? This is illustrated by the diagram to the right. There are two MC estimates (<em>q<sub>1</sub></em> and <em>q<sub>2</sub></em>) and two confidence intervals for an unknown parameter, &mu;. 
How close are the estimates to each other? Intuitively, you might expect to bound the distance between the estimates by the width of the larger confidence interval, but is there a better way to compare the distance between two estimates? 
</p><p>
Yes, there is a better way. You can compute the variance of the difference between the two estimates
and construct a 95% confidence interval for that difference.
This article shows how to perform the computation in SAS by using the SAS IML language.
We will also verify the empirical 95% coverage for an example.
</p>


<h3>Generate independent Monte Carlo estimates</h3>
<p>
To make the ideas concrete, let's look at a specific problem.
Suppose you want to estimate 
the expected value of the Exponential distribution with scale parameter 10.
Call that quantity &mu;.
You can prove analytically that &mu; = 10 is the true expected value.  
</p><p>
The following SAS IML function performs a Monte Carlo simulation to estimate &mu;. 
The function generates <em>B</em> independent samples of size <em>N</em> from the Expo(10) distribution. 
It calculates the mean of each sample. The 
Monte Carlo estimate is the average of the estimates.
The Monte Carlo standard error is the standard deviation of the estimates divided by sqrt(B).
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* use Monte Carlo simulation to estimate the mean of the
   Expo(lambda) distribution. The simulation uses B independent
   samples of size N. Each sample is independently drawn from Expo(lambda) */</span>
start MC_Est_Expo<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, B, lambda<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">x</span> = j<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, B, .<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">call</span> randgen<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #a020f0;">&quot;Expo&quot;</span>, lambda<span style="color: #66cc66;">&#41;</span>;
    sample_means = <span style="color: #0000ff;">mean</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;                <span style="color: #006400; font-style: italic;">/* mean of each column */</span>
    MC_est = <span style="color: #0000ff;">mean</span><span style="color: #66cc66;">&#40;</span>sample_means`<span style="color: #66cc66;">&#41;</span>;          <span style="color: #006400; font-style: italic;">/* MC estimate of statistic */</span>
    SE_est = <span style="color: #0000ff;">std</span><span style="color: #66cc66;">&#40;</span>sample_means`<span style="color: #66cc66;">&#41;</span> / <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span>B<span style="color: #66cc66;">&#41;</span>; <span style="color: #006400; font-style: italic;">/* MC standard error */</span>
    <span style="color: #0000ff;">return</span><span style="color: #66cc66;">&#40;</span> MC_est || SE_est <span style="color: #66cc66;">&#41;</span>;
finish;
&nbsp;
<span style="color: #0000ff;">N</span> = <span style="color: #2e8b57; font-weight: bold;">100</span>;
B = <span style="color: #2e8b57; font-weight: bold;">5000</span>;
lambda = <span style="color: #2e8b57; font-weight: bold;">10</span>;
<span style="color: #0000ff;">call</span> randseed<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">79</span><span style="color: #66cc66;">&#41;</span>;
est1 = MC_Est_Expo<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, B, Lambda<span style="color: #66cc66;">&#41;</span>;
est2 = MC_Est_Expo<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, B, Lambda<span style="color: #66cc66;">&#41;</span>;
print est1<span style="color: #66cc66;">&#91;</span>c=<span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">'MCest1'</span> <span style="color: #a020f0;">'SE1'</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#93;</span>, est2<span style="color: #66cc66;">&#91;</span>c=<span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">'MCest2'</span> <span style="color: #a020f0;">'SE2'</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#93;</span>;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/MCDiff2.png" alt="" width="154" height="189" class="alignnone size-full wp-image-60204" />

<p>
Because the algorithm relies on random number simulation, every call results in a slightly different point estimate and standard error. Here, the estimate from the first simulation is larger than the true parameter (10); the other estimate is smaller. The standard errors are very similar: approximately 0.142.
</p>

<h3>The variance of the difference</h3>
<p>
Let <em>q<sub>1</sub></em> and <em>q<sub>2</sub></em> be two independent MC estimates, with standard errors <em>SE<sub>1</sub></em> and <em>SE<sub>2</sub></em>. Since both estimates are computed by the same method, the expected value of their difference is zero: E[<em>q<sub>1</sub></em> - <em>q<sub>2</sub></em>] = 0. (If we used different methods, and those methods are biased by different amounts, the expected value will not be zero.)
</p>
<p>
How much variance should we expect for the difference? Because <em>q<sub>1</sub></em> and <em>q<sub>2</sub></em> are independent, the variance of their difference is the sum of the individual variances:
<br />
Var(<em>q<sub>1</sub></em> - <em>q<sub>2</sub></em>) = <em>SE<sub>1</sub></em><sup>2</sup> + <em>SE<sub>2</sub></em><sup>2</sup>
</p>
<p>
Let <em>SE<sub>diff</sub></em> be the square root of this sum. For this example,
both estimates are normally distributed, so the difference also follows a normal distribution: <em>q<sub>1</sub></em> - <em>q<sub>2</sub></em> &sim; N(0, <em>SE<sub>diff</sub></em>). 
You can use this distribution to construct a 95% interval for the difference. 
Let's do that, then check whether the distance between these estimates 
|<em>q<sub>1</sub></em> - <em>q<sub>2</sub></em>| is less than the width of the interval.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* given (q1, SE1) and (q2, SE2), what is a confidence interval for the 
   difference q1-q2? The expected value E[q1-q2] = 0, but what is the variance? */</span>
q1 = est1<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span>;  q2 = est2<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span>; 
SE1 = est1<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#93;</span>; SE2 = est2<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#93;</span>;
<span style="color: #006400; font-style: italic;">/* Standard deviation of the DIFFERENCE between two independent estimates */</span>
SE_diff = <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span>SE1<span style="color: #006400; font-style: italic;">**2 + SE2**2);</span>
print SE1 SE2 SE_diff;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Can we bound |q1 - q2| with high probability? 
   Use a prediction interval based on the fact that 
   q1-q2 ~ N(0, SE_diff) */</span>
w95 = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, <span style="color: #2e8b57; font-weight: bold;">0.975</span><span style="color: #66cc66;">&#41;</span> <span style="color: #006400; font-style: italic;">* SE_diff;</span>
<span style="color: #0000ff;">if</span> <span style="color: #0000ff;">abs</span><span style="color: #66cc66;">&#40;</span>q1 - q2<span style="color: #66cc66;">&#41;</span> &lt; w95 <span style="color: #0000ff;">then</span> 
    print <span style="color: #a020f0;">&quot;The difference |q1 - q2| is inside a 95% confidence interval&quot;</span>;
<span style="color: #0000ff;">else</span>
    print <span style="color: #a020f0;">&quot;The difference |q1 - q2| is NOT inside a 95% confidence interval&quot;</span>;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/MCDiff3.png" alt="" width="356" height="108" class="alignnone size-full wp-image-60213" srcset="https://blogs.sas.com/content/iml/files/2026/09/MCDiff3.png 356w, https://blogs.sas.com/content/iml/files/2026/09/MCDiff3-300x91.png 300w" sizes="(max-width: 356px) 100vw, 356px" />

<p>
For these estimates, the difference is, indeed, less than the width of a 95% confidence interval.
Of course, we might have gotten lucky. 
The next section investigates what happens if we repeat this experiment many times.
</p>

<h3>Verify the empirical coverage</h3>
<p>
According to probability theory, the difference between the two estimates should fall inside the calculated interval 95% of the time. However, I always like to verify statistical theory by running a simulation in SAS.
</p>
<p>
The following program repeats the experiment 1,000 times. For each iteration, the program generates two independent Monte Carlo estimates, computes the 95% confidence interval for their difference, and 
saves a 0/1 binary value that indicates if the difference falls inside the CI. 
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* If we repeat this computation many times, about 95% of the differences
   should be in the 95% CI */</span>
C = <span style="color: #2e8b57; font-weight: bold;">1000</span>;
crit_val = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Normal&quot;</span>, <span style="color: #2e8b57; font-weight: bold;">0.975</span><span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* ~ 1.96 */</span>
inCI95 = j<span style="color: #66cc66;">&#40;</span>C, <span style="color: #2e8b57; font-weight: bold;">1</span>, <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">do</span> i=<span style="color: #2e8b57; font-weight: bold;">1</span> to C;
    est1 = MC_Est_Expo<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, B, Lambda<span style="color: #66cc66;">&#41;</span>;
    est2 = MC_Est_Expo<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, B, Lambda<span style="color: #66cc66;">&#41;</span>;
    q1 = est1<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span>;  q2 = est2<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#93;</span>; 
    SE1 = est1<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#93;</span>; SE2 = est2<span style="color: #66cc66;">&#91;</span><span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#93;</span>;
    SE_diff = <span style="color: #0000ff;">sqrt</span><span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#40;</span>SE1<span style="color: #006400; font-style: italic;">**2 + SE2**2) );</span>
    w95 = crit_val <span style="color: #006400; font-style: italic;">* SE_diff;</span>
    inCI95<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">abs</span><span style="color: #66cc66;">&#40;</span>q1 - q2<span style="color: #66cc66;">&#41;</span> &lt; w95<span style="color: #66cc66;">&#41;</span>; 
<span style="color: #0000ff;">end</span>; 
&nbsp;
propInCI = <span style="color: #0000ff;">mean</span><span style="color: #66cc66;">&#40;</span>inCI95<span style="color: #66cc66;">&#41;</span>;
print propInCI<span style="color: #66cc66;">&#91;</span>c=<span style="color: #66cc66;">&#123;</span><span style="color: #a020f0;">'Empirical 95% Cov'</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#93;</span>;</pre></td></tr></table></div>




<img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/MCDiff4.png" alt="" width="111" height="105" class="alignnone size-full wp-image-60216" />

<p>
Ah, success! 
The empirical coverage for this random number seed is close to the theoretical coverage of 0.95. This confirms that adding the individual variances provides a statistical interval for comparing the distance between two 
Monte Carlo estimates of the same quantity. 
</p>


<h3>Modifying this technique</h3>
<p>
You can change the critical value if you want to test the difference with more confidence. For example, you can use three standard errors to obtain a 99.7% confidence interval, which is known as the "three-sigma rule."
</p><p>
You can also compare the distance between two estimates that come from different (unbiased) estimates. For example, if one estimate is computed by using B<sub>1</sub>=5,000 random samples and the other is computed by using B<sub>2</sub>=3,000 random samples, the standard error for the second estimate will be larger, but you can still compute the standard error of the difference.
</p><p>
If you are testing a routine that produces a random or quasi-random result, you can use this technique to compare the routine's result to a MC validation procedure that you wrote yourself. Suppose the routine returns the value <em>q<sub>1</sub></em>. Your validation procedure gives the value <em>q<sub>2</sub></em>.
95% of the time,  <em>q<sub>1</sub></em> will be close to  <em>q<sub>2</sub></em>.
But there is a 5% chance that they are not sufficiently close. 
Does that indicate that the estimates are wrong? No, most likely you got unlucky.
One option is to rerun the routine and your verification procedure again. This gives new estimates
<em>q<sub>3</sub></em> and <em>q<sub>4</sub></em>. These new results also have a 5% chance of failure, but the probability that BOTH tests fail sequentially is a very small 0.25%.
If that probability is not small enough for you, you can use 99.7% CIs instead of 95% CIs.
</p>


<h3>Summary</h3>
<p>
This article shows a technique for comparing the difference between two Monte Carlo estimates of the same 
quantity. You can compute the variance of the difference as the sum of the two individual variances.
In many cases, the expected value of the difference is zero, and the difference is normally distributed. (You should check this assumption.) Therefore, you can derive a formula for the magnitude of the difference.
You can use this formula to verify the consistency of a single Monte Carlo simulation, or you can use it to verify that two different MC algorithms provide consistent estimates of the same quantity.
</p>
  <p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/09/21/diff-mc-estimates.html">How to compare two independent Monte Carlo estimates</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/09/21/diff-mc-estimates.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/09/MCDiff1-150x150.png" />
	</item>
		<item>
		<title>Implement a zero-inflated distribution in SAS</title>
		<link>https://blogs.sas.com/content/iml/2026/09/14/zero-inflated-beta-sas.html</link>
					<comments>https://blogs.sas.com/content/iml/2026/09/14/zero-inflated-beta-sas.html#comments</comments>
		
		<dc:creator><![CDATA[Rick Wicklin]]></dc:creator>
		<pubDate>Mon, 14 Sep 2026 09:22:32 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Statistical Programming]]></category>
		<guid isPermaLink="false">https://blogs.sas.com/content/iml/?p=60144</guid>

					<description><![CDATA[<p>SAS has more than 25 common probability distributions that are supported in the PDF, CDF, QUANTILE, and RAND functions. If you want to work with a less common distribution, you can implement these functions yourself. For example, I previously showed how to use PROC FCMP in Base SAS to implement [...]</p>
<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/09/14/zero-inflated-beta-sas.html">Implement a zero-inflated distribution in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>
SAS has more than 25 common probability distributions that are supported in the PDF, CDF, QUANTILE, and RAND functions. If you want 
to work with a less common distribution, you can implement these functions yourself. For example, I previously showed how to use PROC FCMP in Base SAS to implement <a href="https://blogs.sas.com/content/iml/2026/01/20/burr-sas.html">the Burr (Type XII) distribution</a> and <a href="https://blogs.sas.com/content/iml/2025/08/25/gev-sas.html">the generalized extreme value distribution</a>.
</p>

<a href="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta1.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta1.png" alt="" width="480" height="360" class="alignright size-full wp-image-60168" srcset="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta1.png 640w, https://blogs.sas.com/content/iml/files/2026/09/ZIBeta1-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
A SAS programmer recently asked me questions about a zero-inflated (ZI) probability distribution. 
Some readers might be familiar with distributions that are related to zero-inflated <em>counts</em>.
These distributions are used in some linear regression models.
A zero-inflated model is a mixture of two distributions: a discrete probability mass situated at X=0, and a second probability distribution, 
which describes the probability that a random variable is not zero.
In regression, two common zero-inflated distributions are the ZI Poisson (ZIP) and the ZI negative binomial (ZINB) distributions. 
</p><p>
However, the SAS programmer wanted to implement a mixture distribution that is the mixture of a 
discrete point-mass distribution and a continuous distribution. The discrete distribution gives the probability that X=0. The continuous distribution gives the probability that X &gt; 0.
</p><p>
This article shows how to use SAS to create functions for the zero-inflated Beta distribution. The image to the right shows the PDF for a ZI Beta distribution.
The techniques in this article can be generalized to other mixture distributions, such as a ZI gamma distribution.
This article implements the functions in PROC FCMP and calls them from the DATA step. 
</p>

<h3>What is the zero-inflated Beta distribution?</h3>

<p>
<a href="https://en.wikipedia.org/wiki/Beta_distribution">The Beta distribution is a two-parameter distribution on the interval (0,1)</a>. The two positive shape parameters 
are often called "alpha" and "beta." To reduce confusion, I capitalize the name of the distribution and lowercase the name of the parameter.
Depending on the relative magnitudes of the shape parameters, the probability density function can be U-shaped, J-shaped, L-shaped, or mound-shaped (sometimes called "inverted-U shaped"). 
</p>
<p>
The equation for the probability density function (PDF) of a random variable that follows a zero-inflated distribution is 
<br />
&nbsp;&nbsp;&nbsp;&nbsp; 
f(x) = &pi; &delta;(x) + (1-&pi;) f<sub>2</sub>(x; &alpha;, &beta;) I(x &gt; 0)
<br />
where &delta;(x) is the Dirac delta function, &pi; is the mixing probability, f<sub>2</sub> is the probability density function of the second distribution, and I is the indicator function (also called the Heaviside function). For this article, f<sub>2</sub> is the PDF of a Beta distribution.
</p><p>
This article uses the values &alpha; = 2 and &beta; = 3 for the shape parameters.
For the probability of mixing, this article uses &pi; = 0.2. In programs, I use the variable p0 instead of &pi; for the mixing probability so that the parameter will not be confused with the mathematical constant 3.14159....
</p>


<h3>Define the zero-inflated functions in PROC FCMP</h3>
<p>
This article defines the four main functions that statistical programmers need: The PDF, CDF, quantile, and random functions
for the ZI Beta distribution.
They are defined in a PROC FCMP library and can be called from the SAS DATA step.
To simplify the article, I've put the PROC FCMP code in the Appendix. 
To reproduce the images in this article, you must run the PROC FCMP code <em>before</em> running the examples! 
I have stored the definitions in the WORK libref, but you replace WORK with a libref to a permanent location if you want to 
persist the definitions. If you do, be sure to specify the CMPLIB= option in each new session of SAS. The CMPLIB= option tells SAS where 
you stored the functions.
</p>

<h3>Parameter values for the examples</h3>
<p>
To keep this article short, all examples use the same parameter values for the Beta distribution. 
The %DefineParms macro defines three parameter values. It sets the mixing probability (p0) to 0.2.
It sets the Beta parameters to &alpha; = 2 and &beta; = 3.  You can modify the macro to explore other ZI Beta shapes.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #0000ff;">%macro</span> DefineParms;
   p0    = <span style="color: #2e8b57; font-weight: bold;">0.2</span>;
   alpha = <span style="color: #2e8b57; font-weight: bold;">2</span>;
   beta  = <span style="color: #2e8b57; font-weight: bold;">3</span>;
   <span style="color: #0000ff;">length</span> Params $40;
   Params = cats<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;alpha=&quot;</span>,<span style="color: #0000ff;">put</span><span style="color: #66cc66;">&#40;</span>alpha,BEST3.<span style="color: #66cc66;">&#41;</span>, <span style="color: #a020f0;">&quot;, beta=&quot;</span>, <span style="color: #0000ff;">put</span><span style="color: #66cc66;">&#40;</span>beta,BEST3.<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">%mend</span>;</pre></td></tr></table></div>





<h3>The ZI Beta PDF</h3>
<p>
When I study a new distribution, I start by visualizing the probability density function (PDF). 
The following DATA step calls the PDF_ZIBeta function, then uses PROC SGPLOT to visualize the PDF curves.
Remember to run the code in the Appendix first!
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">data</span> PDF_Test;
%DefineParms;
dx = <span style="color: #2e8b57; font-weight: bold;">0.01</span>;
<span style="color: #0000ff;">do</span> <span style="color: #0000ff;">x</span> = 1E-6, dx/<span style="color: #2e8b57; font-weight: bold;">2</span>, dx to <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">by</span> dx;
   <span style="color: #0000ff;">PDF</span> = PDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">output</span>;
<span style="color: #0000ff;">end</span>;
t = <span style="color: #2e8b57; font-weight: bold;">0</span>; <span style="color: #0000ff;">output</span>;
<span style="color: #0000ff;">keep</span> p0 <span style="color: #0000ff;">x</span> <span style="color: #0000ff;">PDF</span> Params t;
<span style="color: #000080; font-weight: bold;">run</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;PDF of Zero-Inflated Beta&quot;</span>;
<span style="color: #000080; font-weight: bold;">proc sgplot</span> <span style="color: #000080; font-weight: bold;">data</span>=PDF_Test;
   series <span style="color: #0000ff;">x</span>=<span style="color: #0000ff;">x</span> y=<span style="color: #0000ff;">PDF</span> / <span style="color: #0000ff;">group</span>=Params lineattrs=<span style="color: #66cc66;">&#40;</span>thickness=<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;
   dropline <span style="color: #0000ff;">x</span>=t y=p0 / dropto=<span style="color: #0000ff;">x</span> lineattrs=GraphData1<span style="color: #66cc66;">&#40;</span>thickness=<span style="color: #2e8b57; font-weight: bold;">5</span><span style="color: #66cc66;">&#41;</span>;
   yaxis grid <span style="color: #0000ff;">min</span>=<span style="color: #2e8b57; font-weight: bold;">0</span> offsetmin=<span style="color: #2e8b57; font-weight: bold;">0</span>;
   xaxis grid;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<p>
The graph is shown at the top of this article.
I used a DROPLINE statement to display a vertical bar, which indicates the discrete probability mass at x=0.
The Beta curve defines the probability density for x &gt; 0.
</p>

<h3>The ZI Beta CDF</h3>
<p>
The cumulative distribution function (CDF) is the integral of the PDF. 
Given a value, x, the CDF at x tells you the probability that a random observation drawn from the ZI Beta distribution will be less than or equal to x. 
Because of the point-mass at 0, the CDF for the ZI Beta distribution has the value p0 (here, 0.2) at x=0 and increases monotonically as x increases.
The following DATA step calls the CDF_ZIBeta function,
then uses PROC SGPLOT to visualize the CDF curves:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">data</span> CDF_Test;
%DefineParms;
dx = <span style="color: #2e8b57; font-weight: bold;">0.01</span>;
<span style="color: #0000ff;">do</span> <span style="color: #0000ff;">x</span> = 1E-6, dx/<span style="color: #2e8b57; font-weight: bold;">2</span>, dx to <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">by</span> dx;
   <span style="color: #0000ff;">CDF</span> = CDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">output</span>;
<span style="color: #0000ff;">end</span>;
t = <span style="color: #2e8b57; font-weight: bold;">0</span>; <span style="color: #0000ff;">output</span>;
<span style="color: #0000ff;">keep</span> p0 <span style="color: #0000ff;">x</span> <span style="color: #0000ff;">CDF</span> Params t;
<span style="color: #000080; font-weight: bold;">run</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;CDF of Zero-Inflated Beta&quot;</span>;
<span style="color: #000080; font-weight: bold;">proc sgplot</span> <span style="color: #000080; font-weight: bold;">data</span>=CDF_Test;
   series <span style="color: #0000ff;">x</span>=<span style="color: #0000ff;">x</span> y=<span style="color: #0000ff;">CDF</span> / <span style="color: #0000ff;">group</span>=Params lineattrs=<span style="color: #66cc66;">&#40;</span>thickness=<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;
   dropline <span style="color: #0000ff;">x</span>=t y=p0 / dropto=<span style="color: #0000ff;">x</span> lineattrs=GraphData1<span style="color: #66cc66;">&#40;</span>thickness=<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;
   yaxis grid <span style="color: #0000ff;">min</span>=<span style="color: #2e8b57; font-weight: bold;">0</span> offsetmin=<span style="color: #2e8b57; font-weight: bold;">0</span>;
   xaxis grid;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta2.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta2.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60165" srcset="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta2.png 640w, https://blogs.sas.com/content/iml/files/2026/09/ZIBeta2-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
For any value of x along the horizontal axis, the graph shows the probability (on the vertical axis) 
that a random observation is less than or equal to  x.
For example, the function at x=0.4 shows that there is approximately a 63% chance that a random variate from that 
distribution will have a value less than or equal to 0.4. Notice that there is a 20% probability that a random observation is 0.
</p>


<h3>The ZI Beta quantile function</h3>
<p>
The quantile function is the inverse of the CDF function.  
Given a probability, <em>p</em> in (0,1), the quantile function at <em>p</em> is the <em>x</em> value such that a random observation drawn 
from the ZI Beta distribution will be less than or equal to <em>x</em> with probability <em>p</em>. 
For a ZI distribution, you can use the quantile function of the continuous distribution,
but you need to rescale the probability to account for the point-mass at 0.
The following DATA step calls the quantile_ZIBeta function,
then uses PROC SGPLOT to visualize the quantile curves.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">data</span> Quantile_Test;
%DefineParms;
dp = <span style="color: #2e8b57; font-weight: bold;">0.01</span>;
<span style="color: #0000ff;">do</span> p = <span style="color: #2e8b57; font-weight: bold;">0</span> to <span style="color: #2e8b57; font-weight: bold;">1</span>-dp <span style="color: #0000ff;">by</span> dp, <span style="color: #2e8b57; font-weight: bold;">0.999</span>, <span style="color: #2e8b57; font-weight: bold;">0.9999</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>;
   <span style="color: #0000ff;">x</span> = quantile_ZIBeta<span style="color: #66cc66;">&#40;</span>p, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">output</span>;
<span style="color: #0000ff;">end</span>;
<span style="color: #0000ff;">keep</span> p0 p <span style="color: #0000ff;">x</span> Params;
<span style="color: #000080; font-weight: bold;">run</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Quantile Function of Zero-Inflated Beta&quot;</span>;
<span style="color: #000080; font-weight: bold;">proc sgplot</span> <span style="color: #000080; font-weight: bold;">data</span>=Quantile_Test;
   series <span style="color: #0000ff;">x</span>=p y=<span style="color: #0000ff;">x</span> / <span style="color: #0000ff;">group</span>=Params lineattrs=<span style="color: #66cc66;">&#40;</span>thickness=<span style="color: #2e8b57; font-weight: bold;">2</span><span style="color: #66cc66;">&#41;</span>;
   yaxis grid <span style="color: #0000ff;">min</span>=<span style="color: #2e8b57; font-weight: bold;">0</span> offsetmin=<span style="color: #2e8b57; font-weight: bold;">0</span>;
   xaxis grid;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta3.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta3.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60162" srcset="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta3.png 640w, https://blogs.sas.com/content/iml/files/2026/09/ZIBeta3-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
Notice that the graph of the quantile function is the "flipped image" of the CDF graph. 
Notice also that the derivative of the quantile becomes infinite as x &rarr; 1. 
This is because the slope of the CDF function approaches 0 as x &rarr; 1. 
</p>

<h3>Random variates from the ZI Beta distribution</h3>
<p>
For any mixture distribution, generating random variates requires two steps. The first step is to generate a binary
random variate. (In SAS, this is done by using the "Bernoulli" distribution.) With probability &pi;, you return a random variate from the first distribution; with probability 1-&pi;, you return a random variate from the second distribution. For the ZI Beta distribution, this means that 
you return 0 with probability &pi;, and a random variate from the Beta distribution with probability 1-&pi;. 
If you draw a histogram of the resulting random variates, the bin that includes 0 will display the counts of the random variates
near 0 from both distributions. 
</p><p>
The following DATA step calls the rand_ZIBeta function 1000 times. Approximately 20% of the random variates are from the point-mass at 0.
The remaining variates are from the Beta distribution. 
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">data</span> Rand_Test;
%DefineParms;
<span style="color: #0000ff;">call</span> streaminit<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1234</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">N</span> = <span style="color: #2e8b57; font-weight: bold;">1000</span>;
<span style="color: #0000ff;">do</span> j  = <span style="color: #2e8b57; font-weight: bold;">1</span> to <span style="color: #0000ff;">N</span>;
   <span style="color: #0000ff;">x</span> = rand_ZIBeta<span style="color: #66cc66;">&#40;</span>p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">output</span>;
<span style="color: #0000ff;">end</span>;
<span style="color: #0000ff;">keep</span> <span style="color: #0000ff;">x</span> Params;
<span style="color: #000080; font-weight: bold;">run</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Random Variates for the Zero-Inflated Beta&quot;</span>;
<span style="color: #000080; font-weight: bold;">proc sgplot</span> <span style="color: #000080; font-weight: bold;">data</span>=Rand_Test;
   histogram <span style="color: #0000ff;">x</span>;
   yaxis grid;
   xaxis grid;
<span style="color: #000080; font-weight: bold;">run</span>;</pre></td></tr></table></div>




<a href="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta4.png"><img loading="lazy" decoding="async" src="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta4.png" alt="" width="480" height="360" class="alignnone size-full wp-image-60159" srcset="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta4.png 640w, https://blogs.sas.com/content/iml/files/2026/09/ZIBeta4-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a>

<p>
Because the program generates 1,000 random variates, the shape of the histogram is similar to the shape of the PDF curve. Specifically, note that bar that includes x=0 is slightly more than 20% for this random sample.
</p>

<h3>Define the functions for the ZI Beta distribution in SAS IML</h3>
<p>
Some programmers prefer to use the SAS IML language, especially when conducting a simulation study. Appendix 2 presents SAS IML module definitions. You can store the definition, then call them from a SAS IML program.
</p>

<h3>Summary</h3>
<p>
This article demonstrates how to implement a zero-inflated distribution in SAS. This article implements the
zero-inflated Beta distribution, but you can use the same techniques for other zero-inflated distributions. 
Appendix A of this article defines four related functions in PROC FCMP in Base SAS: the PDF, CDF, quantile, and random variate functions. SAS IML versions of the functions are defined in Appendix B.
</p>



<h3>Appendix A: FCMP functions for the zero-inflated Beta distribution</h3>
<p>
This appendix shows <a href="https://blogs.sas.com/content/iml/2012/04/18/extending-sas-how-to-define-new-functions-in-proc-fcmp-and-sasiml-software.html">how to use PROC FCMP in SAS to add new DATA step functions</a>. It follows the same technique as <a href="https://blogs.sas.com/content/iml/2025/08/25/gev-sas.html">a previous article about the generalized extreme-value (GEV) distribution</a>.
Run this PROC FCMP step before trying to call the functions in the DATA step.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #006400; font-style: italic;">/* Define the PDF, CDF, QUANTILE, and RAND functions for the 
   ZI Beta distribution in PROC FCMP.  
&nbsp;
   The support for the ZI Beta distribution is X in [0,1).
   alpha : Shape1 &gt; 0
   beta  : Shape2 &gt; 0
&nbsp;
   For simplicity, the function assume alpha &gt; 0 and beta &gt; 0.
   The PDF is undefined if x=1 and beta &lt; 1. It is well-defined
   for other parameter values. For simplicity, we always 
   return a missing value with x=1. Thus, the variates for
   the distribution are defined on [0,1). */</span>
<span style="color: #000080; font-weight: bold;">proc fcmp</span> outlib=work.funcs.ProbDist;
   function PDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">if</span> <span style="color: #0000ff;">x</span> &lt; <span style="color: #2e8b57; font-weight: bold;">0</span> | <span style="color: #0000ff;">x</span> &gt;= <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span>.<span style="color: #66cc66;">&#41;</span>;
      f = ifn<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>=<span style="color: #2e8b57; font-weight: bold;">0</span>, p0, <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*pdf('Beta', x, alpha, beta));</span>
      <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span>f<span style="color: #66cc66;">&#41;</span>;
   endsub;
&nbsp;
   function CDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">if</span> <span style="color: #0000ff;">x</span> &lt; <span style="color: #2e8b57; font-weight: bold;">0</span> | <span style="color: #0000ff;">x</span> &gt;= <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span>.<span style="color: #66cc66;">&#41;</span>;
      F = ifn<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>=<span style="color: #2e8b57; font-weight: bold;">0</span>, p0, p0+<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*cdf('Beta', x, alpha, beta));</span>
      <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span>F<span style="color: #66cc66;">&#41;</span>;
   endsub;
&nbsp;
   function quantile_ZIBeta<span style="color: #66cc66;">&#40;</span>p, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">if</span> p &lt; <span style="color: #2e8b57; font-weight: bold;">0</span> | p &gt; <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span>.<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">if</span> p &lt;= p0 <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">if</span> p = <span style="color: #2e8b57; font-weight: bold;">1</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
      z = <span style="color: #66cc66;">&#40;</span>p-p0<span style="color: #66cc66;">&#41;</span>/<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* rescale the probability on [p0,1] */</span>
      <span style="color: #0000ff;">x</span> = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'Beta'</span>, z, alpha, beta<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   endsub;
&nbsp;
   function rand_ZIBeta<span style="color: #66cc66;">&#40;</span>p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
      b = rand<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">&quot;Bernoulli&quot;</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">if</span> b=<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">x</span> = rand<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'Beta'</span>, alpha, beta<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
   endsub;
<span style="color: #000080; font-weight: bold;">quit</span>;
<span style="color: #0000ff;">options</span> cmplib=work.funcs;  <span style="color: #006400; font-style: italic;">/* define location of functions so the DATA step can find them */</span></pre></td></tr></table></div>





<h3>Appendix B: SAS IML functions for the zero-inflated Beta distribution</h3>
<p>
This appendix shows how to define the PDF, CDF, QUANTILE, and RAND functions for the ZI Beta distribution in the SAS IML language.
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="sas" style="font-family:monospace;"><span style="color: #000080; font-weight: bold;">proc iml</span>;
<span style="color: #006400; font-style: italic;">/* PDF of Zero Inflated Beta Distribution
   x can be a vector; p0, alpha, and beta are scalars. */</span>
start PDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   f = j<span style="color: #66cc66;">&#40;</span>nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, ncol<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, .<span style="color: #66cc66;">&#41;</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span> = <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      f<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = p0;
   idx = loc<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span> &lt; <span style="color: #0000ff;">x</span> &amp; <span style="color: #0000ff;">x</span> &lt; <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      f<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*PDF('beta', x[idx], alpha, beta);</span>
   <span style="color: #0000ff;">return</span> f;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* CDF of Zero Inflated Beta Distribution
   x can be a vector; p0, alpha, and beta are scalars. */</span>
start CDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   F = j<span style="color: #66cc66;">&#40;</span>nrow<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, ncol<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>, .<span style="color: #66cc66;">&#41;</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span> = <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      F<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = p0;
   idx = loc<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span> = <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      F<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = <span style="color: #2e8b57; font-weight: bold;">1</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span> &lt; <span style="color: #0000ff;">x</span> &amp; <span style="color: #0000ff;">x</span> &lt; <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      F<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = p0 + <span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span><span style="color: #006400; font-style: italic;">*CDF('beta', x[idx], alpha, beta);</span>
   <span style="color: #0000ff;">return</span> F;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Quantile function of Zero Inflated Beta Distribution
   p can be a vector in (0,1); p0, alpha, and beta are scalars. */</span>
start Quantile_ZIBeta<span style="color: #66cc66;">&#40;</span>p, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">x</span> = j<span style="color: #66cc66;">&#40;</span>nrow<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span>, ncol<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span>, .<span style="color: #66cc66;">&#41;</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span> &lt;= p &amp; p &lt;= p0<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = <span style="color: #2e8b57; font-weight: bold;">0</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span>p = <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = <span style="color: #2e8b57; font-weight: bold;">1</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span>p0 &lt; p &amp; p &lt; <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> <span style="color: #0000ff;">do</span>;
      z = <span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span>-p0<span style="color: #66cc66;">&#41;</span>/<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span>;  <span style="color: #006400; font-style: italic;">/* rescale the probability on [p0,1] */</span>
      <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = quantile<span style="color: #66cc66;">&#40;</span><span style="color: #a020f0;">'Beta'</span>, z, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">end</span>;
   <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">x</span>;
finish;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Random variate function of Zero Inflated Beta Distribution
   N is the number or random variates; p0, alpha, and beta are scalars. */</span>
start Rand_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">x</span> = j<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, .<span style="color: #66cc66;">&#41;</span>;
   b = randfun<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">N</span>, <span style="color: #a020f0;">'Bernoulli'</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>-p0<span style="color: #66cc66;">&#41;</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span>b = <span style="color: #2e8b57; font-weight: bold;">0</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span> 
      <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = <span style="color: #2e8b57; font-weight: bold;">0</span>;
   idx = loc<span style="color: #66cc66;">&#40;</span>b = <span style="color: #2e8b57; font-weight: bold;">1</span><span style="color: #66cc66;">&#41;</span>;
   nBeta = ncol<span style="color: #66cc66;">&#40;</span>idx<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">if</span> nBeta&gt;<span style="color: #2e8b57; font-weight: bold;">0</span> <span style="color: #0000ff;">then</span>
      <span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#91;</span>idx<span style="color: #66cc66;">&#93;</span> = randfun<span style="color: #66cc66;">&#40;</span>nBeta, <span style="color: #a020f0;">'Beta'</span>, alpha, beta<span style="color: #66cc66;">&#41;</span>;
   <span style="color: #0000ff;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span>;
finish;
store module=<span style="color: #66cc66;">&#40;</span>PDF_ZIBeta CDF_ZIBeta quantile_ZIBeta Rand_ZIBeta<span style="color: #66cc66;">&#41;</span>;
<span style="color: #000080; font-weight: bold;">QUIT</span>;
&nbsp;
<span style="color: #006400; font-style: italic;">/* Test the functions for the ZI Beta distribution */</span>
<span style="color: #000080; font-weight: bold;">proc iml</span>;
load module=<span style="color: #66cc66;">&#40;</span>PDF_ZIBeta CDF_ZIBeta quantile_ZIBeta Rand_ZIBeta<span style="color: #66cc66;">&#41;</span>;
&nbsp;
p0    = <span style="color: #2e8b57; font-weight: bold;">0.2</span>;
alpha = <span style="color: #2e8b57; font-weight: bold;">2</span>;
beta  = <span style="color: #2e8b57; font-weight: bold;">3</span>;
&nbsp;
dx = <span style="color: #2e8b57; font-weight: bold;">0.01</span>;
<span style="color: #0000ff;">x</span> = <span style="color: #2e8b57; font-weight: bold;">0</span> // 1E-6 // T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span>dx, <span style="color: #2e8b57; font-weight: bold;">1</span>, dx<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">PDF</span> = PDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;PDF of Zero-Inflated Beta&quot;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #0000ff;">PDF</span><span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;CDF of Zero-Inflated Beta&quot;</span>;
<span style="color: #0000ff;">CDF</span> = CDF_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span>, <span style="color: #0000ff;">CDF</span><span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span> other=<span style="color: #a020f0;">&quot;refline 0.2/axis=y; yaxis grid values=(0 to 1 by 0.1);&quot;</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Quantile Function of Zero-Inflated Beta&quot;</span>;
dp = <span style="color: #2e8b57; font-weight: bold;">0.01</span>;
p = T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">0</span>, p0, dp<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> // T<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">do</span><span style="color: #66cc66;">&#40;</span>p0+dp/<span style="color: #2e8b57; font-weight: bold;">10</span>, <span style="color: #2e8b57; font-weight: bold;">1</span>, dp<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
q = quantile_ZIBeta<span style="color: #66cc66;">&#40;</span>p, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> series<span style="color: #66cc66;">&#40;</span>p, q<span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span><span style="color: #0000ff;">x</span> y<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #0000ff;">title</span> <span style="color: #a020f0;">&quot;Random Variates for the Zero-Inflated Beta&quot;</span>;
<span style="color: #0000ff;">x</span> = Rand_ZIBeta<span style="color: #66cc66;">&#40;</span><span style="color: #2e8b57; font-weight: bold;">1000</span>, p0, alpha, beta<span style="color: #66cc66;">&#41;</span>;
<span style="color: #0000ff;">call</span> histogram<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">x</span><span style="color: #66cc66;">&#41;</span> grid=<span style="color: #66cc66;">&#123;</span>y<span style="color: #66cc66;">&#125;</span>;
<span style="color: #000080; font-weight: bold;">QUIT</span>;</pre></td></tr></table></div>



<p>The post <a rel="nofollow" href="https://blogs.sas.com/content/iml/2026/09/14/zero-inflated-beta-sas.html">Implement a zero-inflated distribution in SAS</a> appeared first on <a rel="nofollow" href="https://blogs.sas.com/content/iml">The DO Loop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.sas.com/content/iml/2026/09/14/zero-inflated-beta-sas.html/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			<enclosure url="https://blogs.sas.com/content/iml/files/2026/09/ZIBeta1-150x150.png" />
	</item>
	</channel>
</rss>
