Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • One number, several views? Click-to-change formula experiment

    My first two-view test worked after refreshing the page, although Preview had shown the source text. That made me wonder: could a few clicks help me separate what I see, what is stored, and the exact mathematical quantity?

    Here is the fuller experiment. Click each expression repeatedly; after the last view it returns to the first. If the source text appears, try refreshing the page. No Stata installation is needed to view these recorded values. Clicking changes the display; it does not run Stata or Mata.

    A. Pi: exact target and stored approximations

    \[
    \require{action}
    \toggle
    {\text{Exact target (click): }\pi}
    {\text{Stored double: }\frac{884279719003555}{281474976710656}}
    {\text{Double displayed: }3.14159265358979312}
    {\text{Stored float: }\frac{13176795}{4194304}}
    {\text{Float displayed: }3.14159274101257324}
    \endtoggle
    \]

    The double value is shared by Stata's _pi and Mata's pi(). The fractions describe the stored values exactly; the 17-place decimal displays are rounded. Changing the card does not convert one stored value into another.

    B. The sine of pi: an identity, a calculation, and a display

    \[
    \toggle
    {\text{Identity (click): }\sin(\pi)=0}
    {\text{Recorded result: }\sin(p)\approx1.224646799\times10^{-16}}
    {\text{Six decimal places: }0.000000}
    {\text{Exact equality to zero: false}}
    {\text{Absolute value below }10^{-12}\text{: true}}
    \endtoggle
    \]

    Here p is the stored double approximation to pi in A. The sine result was recorded in Stata/MP 16.1; its final digits may depend on the platform. The exact identity uses mathematical pi, not p. The tolerance is a choice for this example.

    C. A deliberately false equation

    \[ 1+1=3 \]

    Will this also look like a perfectly respectable equation? I expect it to: typesetting a formula does not check its truth or run the expression.

    I would be interested to hear whether these longer cards also work on other browsers or touch screens. If the interaction does not work, the plain-text reference below still gives the contents.

    Code:
    Exact target: pi
    Stored double = 884279719003555 / 281474976710656
    17-place display: 3.14159265358979312
    Stored float  = 13176795 / 4194304
    17-place display: 3.14159274101257324
    
    Mathematical sin(pi) = 0
    Recorded sin(p) approximately 1.224646799e-16
    Same result displayed to six places: 0.000000
    sin(p)==0: false
    abs(sin(p))<1e-12: true
    MathJax action extension:
    https://docs.mathjax.org/en/latest/i...ns/action.html

  • #2
    Hello, Stata? A tiny animation test

    Click image for larger version

Name:	hello_stata.gif
Views:	1
Size:	16.6 KB
ID:	1787756

    Do these two messages alternate every three seconds without clicking? Just testing whether an animated GIF plays inside a Sandbox post.

    The messages are two prewritten frames, not a live response from Stata. If you see only a still image, that is useful to know too.

    Comment


    • #3
      Can colours carry the same conversation?

      The greeting worked, so I tried giving the same two messages another form: grayscale tiles.

      Click image for larger version

Name:	colour_conversation.gif
Views:	1
Size:	46.9 KB
ID:	1787758


      Each tile stores one ASCII byte b as RGB=(b,b,b). Stata drew the PNGs, and our user-written Stata/Mata PNG reader recovered both messages from their pixels. The displayed words are those recovered messages.

      This GIF replays the results; it is not decoding or speaking inside the forum. The reply was chosen in advance. The original PNGs, rather than this presentation GIF, were used for decoding.

      Earlier experiment and code: Speak-Read-Write-Listening-Stata.

      Comment


      • #4
        Revisiting a 2014 Stata Blog example

        After the greeting, I wondered whether the same approach would work for a sequence of Stata graphs.

        Chuck Huber's 24 March 2014 Stata Blog post illustrated animation with a moving normal density. Here is a fresh rendering of that simple idea.

        Click image for larger version

Name:	normal_mean_shift.gif
Views:	1
Size:	556.2 KB
ID:	1787760


        The mean moves from 0 to 1 and back, while the standard deviation stays at 1. Both axes stay fixed. Stata generated the graphs; Python/Pillow assembled the PNGs into a GIF.

        Does it play smoothly here without clicking?

        Comment


        • #5
          Can Stata draw its own celebration?

          After the animated greeting and normal density, I wondered whether Stata could draw its own fireworks.
          Click image for larger version

Name:	stata_celebration_forum.gif
Views:	1
Size:	902.0 KB
ID:	1787763



          The points, trails, curve, and lettering were all drawn in Stata. Python/Pillow only assembled the exported frames into this GIF. The curve is a symbolic path, not a forecast; the words are a user's wish for the future.

          Why 42? Gould dates the start of development to about January 1984 in his interview with H. Joseph Newton (2005, p. 19). Stata's official first release was January 1985. This celebrates 42 years since the beginnings, rather than a 42nd official-release anniversary.
          Last edited by Choonjoo Lee; 26 Oct 2026, 01:42.

          Comment


          • #6
            Can rounding a confidence interval change whether it covers the truth?

            After playing with 0.1 and sin(pi), I wondered: if a confidence limit looks like 0.10, does the interval actually include 0.1?

            I tried a small simulation: 10,000 sample means from a normal population with mean 0.1 and SD 1, with n=25.
            The population SD is treated as known, so each 95% interval is the sample mean plus or minus invnormal(.975)/sqrt(25).
            The code generates the sample means directly from their normal sampling distribution.

            I kept the same intervals and changed only how their endpoints were displayed or stored.
            No data or add-ons are needed.
            Run this as one do-file; it preserves and restores the current dataset, but sets the random-number generator and seed.

            Code:
            version 16.1
            set more off
            preserve
            clear
            set rng mt64
            set seed 20261027
            set obs 10000
            * Sample means from N(0.1,1), n=25; population SD is known.
            generate double mean = .1 + rnormal()/sqrt(25)
            generate double lo = mean - invnormal(.975)/sqrt(25)
            generate double hi = mean + invnormal(.975)/sqrt(25)
            generate byte original = (lo<=.1 & .1<=hi)
            format lo hi %5.2f
            generate byte displayed = (lo<=.1 & .1<=hi)
            generate float flo = lo
            generate float fhi = hi
            generate byte floatstored = (flo<=.1 & .1<=fhi)
            generate double rlo = round(lo,.01)
            generate double rhi = round(hi,.01)
            generate byte rounded = (rlo<=.1 & .1<=rhi)
            summarize original displayed floatstored rounded
            count if original!=displayed
            count if original!=floatstored
            count if original!=rounded
            assert original==displayed
            
            restore
            In Stata/MP 16.1, I obtained:

            Code:
            Treatment                       Coverage    Changed decisions
            Original double endpoints         95.35%          --
            Display to two decimal places     95.35%           0
            Store endpoints as float          95.35%           0
            Round endpoints to 0.01            95.60%          25
            The picture zooms in on four selected intervals whose decisions changed.
            The orange endpoints stop just short of including 0.1; after rounding, the blue endpoints land on it.
            The far endpoints are outside the picture.
            Click image for larger version

Name:	ci_precision.png
Views:	1
Size:	119.2 KB
ID:	1787784


            My takeaway is that format changed only the appearance, whereas round() changed the values being compared. Float storage made no difference to inclusion in this run; that is an observation, not a guarantee for every example.

            This is deliberate decimal rounding, not evidence that the binary approximation to 0.1 spoiled the analysis. Here 0.1 lies on the rounding grid, and endpoints count as included. Some intervals therefore gain coverage after rounding. The higher percentage does not establish a better method; the original 95.35% also has ordinary simulation variability around 95%.

            For my own calculations, I would keep the unrounded endpoints for comparisons and use format for presentation. I would be interested in examples where this distinction matters in practice, or what happens when the true mean lies between the rounding grid points.

            Reference: Stata FAQ: The accuracy of the float data type

            Comment


            • #7
              A Halton point below 1: why does its normal quantile disappear?

              In the confidence-interval experiment, storing the endpoints as float did not change any inclusion decisions. I wondered whether a small storage difference could have a more visible effect elsewhere.

              Here is one deliberately selected Halton point. Such points can be transformed with invnormal() for normal draws in a simulation. What happens if I store the probability as float first?

              No data or add-ons are needed. Run the whole block as a do-file; it preserves and restores the current dataset. Although the index is large, halton(1,1,start) requests just one point, not millions of observations.

              Code:
              version 16.1
              preserve
              clear
              set obs 1
              generate double u = .
              * Request just one point, at a deliberately selected large index.
              mata: st_store(., "u", halton(1,1,2^26-1))
              generate float u_float = u
              generate double z_double = invnormal(u)
              generate double z_float = invnormal(u_float)
              format u u_float %21.17f
              format z_double z_float %10.6f
              list u u_float z_double z_float, noobs abbreviate(16)
              assert u == 1-2^(-26)
              assert u>0 & u<1
              assert u_float==1
              assert !missing(z_double) & missing(z_float)
              * Widening storage afterwards cannot recover the lost digits.
              recast double u_float
              assert u_float==1
              restore
              In Stata/MP 16.1, I obtained:

              Code:
              u                     u_float               z_double    z_float
              0.99999998509883881   1.00000000000000000     5.542594          .
              The picture follows the same point along the two storage paths.
              Click image for larger version

Name:	halton_precision.png
Views:	1
Size:	149.8 KB
ID:	1787786

              Why choose that index? In the first, base-2 Halton dimension, index 2^26-1 gives u = 1-2^(-26). This value is exactly representable as double. It is close enough to 1 to round to 1 when stored as float.

              So the input has reached the boundary. As u approaches 1 from below, the normal quantile grows without bound; at 1 there is no finite normal quantile, and Stata returns missing. Declaring z_float as double cannot repair its already rounded input. Nor does recast double recover the lost digits.

              This is a selected boundary case, not a claim that ordinary small Halton sets routinely fail, or that halton() is faulty. The difference arises when I reduce the storage precision. In a simulation, a missing transformed draw could subsequently be omitted by a summary calculation.

              My practical takeaway is to keep these probabilities as double from the start and check that 0<u<1 before applying invnormal(). I would be interested in other small examples where storage precision changes more than the last printed digit.

              References:
              Mata: halton()
              Stata FAQ: The accuracy of the float data type

              Comment


              • #8
                Following a Halton point: digits, storage, display, and a boundary

                The disappearing normal quantile made me wonder where that Halton point came from. Could I follow it all the way from its index to its displayed value?

                I started with halton(8,1): eight points, one dimension, beginning at index 1. In the first dimension, I can reproduce each point by writing the index in base 2 and reversing its digits after the binary point:

                Code:
                Index   Binary index   Binary fraction   Decimal value
                  1          1              0.1             0.5000
                  2         10              0.01            0.2500
                  3         11              0.11            0.7500
                  4        100              0.001           0.1250
                  5        101              0.101           0.6250
                  6        110              0.011           0.3750
                  7        111              0.111           0.8750
                  8       1000              0.0001          0.0625
                For example, 6 becomes binary 110, then binary 0.011 = 0/2 + 1/4 + 1/8 = 0.375. Here binary 0.1 means one half, not decimal one tenth. These eight values are exact in both double and float. Digit reversal defines the point; float/double determine how that point is stored.

                The first picture follows that order across (0,1). This is a deterministic sequence, not independent random sampling. I am following only the first dimension: further dimensions use bases 3, 5, and so on, rather than more binary copies.
                Click image for larger version

Name:	01_halton_steps.png
Views:	1
Size:	140.6 KB
ID:	1787788

                Click image for larger version

Name:	02_halton_boundary.png
Views:	1
Size:	118.3 KB
ID:	1787789

                Now I can see why the earlier index was useful. An index of 2^26-1 consists of 26 binary ones. Reversing them gives 26 ones after the binary point:

                Code:
                u = 1/2 + 1/4 + ... + 1/2^26 = 1 - 2^(-26)
                That value is still exactly representable as double. I tried following it through storage and display. Run the whole block as a do-file; it preserves and restores the current dataset. No data or add-ons are needed.

                Code:
                version 16.1
                preserve
                clear
                set obs 8
                generate byte index = _n
                generate double u = .
                mata: st_store(., "u", halton(8,1))
                list index u, noobs
                
                clear
                set obs 1
                generate double u = .
                mata: st_store(., "u", halton(1,1,2^26-1))
                generate float uf = u
                generate double zd = invnormal(u)
                generate double zf = invnormal(uf)
                format u uf %5.2f
                list u uf, noobs
                format u uf %21.17f
                format zd zf %10.6f
                list u uf zd zf, noobs
                display "Double u<1? " (u[1]<1) "   Float u<1? " (uf[1]<1)
                assert u==1-2^(-26)
                assert uf==1
                recast double uf
                assert uf==1
                restore
                Both columns initially display 1.00. With more displayed digits, and after applying invnormal(), I get:

                Code:
                                         double path             float path
                Stored u, displayed      0.99999998509883881       1.00000000000000000
                Is u < 1?                         1                       0
                invnormal(u)                  5.542594                    .
                The second picture checks five selected indices, 2^k-1 for k=23,...,27. All original values display as 1.00 with %5.2f, but all remain below 1. In this run, float storage actually moves the last three onto 1. Only five points are requested: the third argument of halton(n,d,start) is a starting index, not a seed or a request to generate every preceding point.

                So I now have three separate questions: what value does the digit rule define, what value did I store, and what does the format show? At k=26 the first two agree for double; the short display conceals the difference from 1. Float storage changes the value itself, and invnormal(1) has no finite normal quantile, so Stata returns missing. Widening the storage afterwards does not bring the original value back.

                For this use, I would create the probability variable as double from the start and check 0<u<1 before the transformation. These are selected boundary examples, not an estimate of how often routine Halton simulations fail. I would be interested in other ways of making this path from digits to an analysis result visible.

                References:
                Mata: halton()
                Mata: floatround()

                Comment


                • #9
                  Can the same double precision give a missing value and a finite answer?

                  After the Halton experiment, I wondered: if double precision also has a boundary, do I always need more precision to get past it?

                  I tried a different route to the same mathematical target: the standard normal quantile with upper-tail probability q = 2^(-54). Normal symmetry gives

                  Code:
                  Phi^(-1)(1-q) = -Phi^(-1)(q),   0 < q < 1
                  Would these two routes agree in the computer? No data or add-ons are needed; this code does not change the dataset or existing scalars.

                  Code:
                  version 16.1
                  * No dataset or existing scalar is changed.
                  display "Tail q:          " %21.16e 2^(-54)
                  display "Computed 1-q:    " %21.17f (1-2^(-54))
                  display "Direct route:    " invnormal(1-2^(-54))
                  display "Symmetric route: " %15.10f (-invnormal(2^(-54)))
                  * Same two routes in Mata, using double precision.
                  mata: (invnormal(1-2^(-54)), -invnormal(2^(-54)))
                  In Stata/MP 16.1:

                  Code:
                  Computed 1-q:      1.00000000000000000
                  Direct route:    .
                  Symmetric route:    8.2923610758
                  Mata gives the same missing/finite pair. The picture follows the two routes.
                  Click image for larger version

Name:	normal_tail_precision.png
Views:	1
Size:	153.6 KB
ID:	1787791


                  What surprised me is that q itself is exactly representable as double. It has not become zero. The loss happens when I form 1-q: the result rounds to 1. There is then no finite normal quantile at that input, so invnormal() returns missing.

                  The second route keeps the small tail probability directly and uses normal symmetry. It avoids that subtraction, with no increase in precision. The answer is still a numerical approximation, but it is a finite one for the intended target.

                  This depends on having the original q. If only a probability already rounded to 1 remains, subtracting it from 1 cannot recover the lost tail.

                  So my next question has changed from "How many digits should I store?" to "Which intermediate calculation loses the information I need?" I would be interested in similarly small examples where rewriting a formula helps more than printing or storing extra digits.

                  So, is there really a problem if the alternative works? For this example, the alternative does solve the computational difficulty—provided I still have the original tail probability. What I learned is that mathematically equivalent formulas need not be interchangeable in floating-point arithmetic.

                  Reference: Stata/Mata distribution functions
                  Last edited by Choonjoo Lee; 27 Oct 2026, 06:05.

                  Comment


                  • #10
                    Same correlation, different 95% CIs: separating scale, SE and bias

                    A recent discussion comparing POLYCORR and CORRCI made me want to separate three choices: the scale on which a confidence interval is constructed, the standard error, and an optional bias correction.(https://www.statalist.org/forums/for...rom-corrci-ssc)

                    I used trunk and weight from auto. The correlation is the same throughout. First I keep its robust variance fixed and change only the construction scale. Then I change the standard error on the z scale, and finally the bias correction.

                    Here z means atanh(r). A Fisher-z interval is also a Wald-type interval on the transformed scale, followed by tanh(). The distinction is between constructing a symmetric interval on the r scale and constructing one on the z scale.
                    Click image for larger version

Name:	ci_intervals_sandbox.png
Views:	1
Size:	83.0 KB
ID:	1787887


                    The following code needs no add-ons or external input files. It calculates the Pearson correlation and its independent-observation robust standard error directly in Mata. The standardization uses a variance divisor of n; the influence-function variance has the n/(n-1) adjustment used by the POLYCORR version checked below. Run it as one do-file. It restores the dataset and writes ci_intervals_sandbox.png and ci_intervals_sandbox.svg in the working directory.

                    Code:
                    version 16.1
                    set more off
                    preserve
                    sysuse auto, clear
                    tempname summary intervals changes rhohat
                    capture mata: mata drop ci_postdemo()
                    mata:
                    void ci_postdemo(string scalar smat, string scalar cmat, string scalar dmat)
                    {
                        real colvector x, y, zx, zy, IF
                        real scalar n, r, sr, z, sz, sc, q, bias
                        real matrix C, D
                    
                        x=st_data(.,"trunk")
                        y=st_data(.,"weight")
                        n=rows(x)
                        zx=x:-mean(x)
                        zy=y:-mean(y)
                        zx=zx/sqrt(mean(zx:^2))
                        zy=zy/sqrt(mean(zy:^2))
                        r=mean(zx:*zy)
                        IF=zx:*zy-(r/2):*(zx:^2+zy:^2)
                        sr=sqrt(sum(IF:^2)/(n*(n-1)))
                    
                        q=invnormal(.975)
                        z=atanh(r)
                        sz=sr/(1-r^2)
                        sc=1/sqrt(n-3)
                        bias=-r/(2*(n-1))
                    
                        C=J(4,2,.)
                        C[1,]=(r-q*sr, r+q*sr)
                        C[2,]=(tanh(z-q*sz), tanh(z+q*sz))
                        C[3,]=(tanh(z-q*sc), tanh(z+q*sc))
                        C[4,]=(tanh(z+bias-q*sc), tanh(z+bias+q*sc))
                        D=C[2..4,]-C[1..3,]
                    
                        // Transforming an EXISTING interval and back leaves it unchanged.
                        assert(max(abs(tanh(atanh(C[1,]))-C[1,]))<1e-12)
                        // Reconstructing a symmetric z interval is a different operation.
                        assert(max(abs(C[2,]-C[1,]))>.01)
                        assert(max(abs(colsum(D)-(C[4,]-C[1,])))<1e-12)
                    
                        st_matrix(smat,(n,r,sr,sz,sc))
                        st_matrix(cmat,C)
                        st_matrix(dmat,D)
                    }
                    end
                    mata: ci_postdemo("`summary'","`intervals'","`changes'")
                    mata: mata drop ci_postdemo()
                    matrix colnames `summary'=n r se_r_robust se_z_robust se_z_classic
                    matrix colnames `intervals'=lower upper
                    matrix rownames `intervals'=r_robust z_robust z_classic z_bias
                    matrix colnames `changes'=lower_change upper_change
                    matrix rownames `changes'=scale_only SE_only bias_only
                    matrix list `summary', format(%12.7f)
                    matrix list `intervals', format(%12.7f)
                    matrix list `changes', format(%12.7f)
                    
                    * Draw exactly the four intervals printed above.
                    scalar `rhohat'=`summary'[1,2]
                    clear
                    svmat double `intervals', names(col)
                    generate byte method=_n
                    generate double rho=`rhohat'
                    label define ci_post_method ///
                        1 "polycorr: r Wald / robust" ///
                        2 "polycorr, cifz: z Wald / robust" ///
                        3 "corrci: z Wald / classic" ///
                        4 "corrci, fisher: z Wald / classic + bias", replace
                    label values method ci_post_method
                    twoway (rcap lower upper method, horizontal lcolor(navy) lwidth(medthick)) ///
                        (scatter method rho, msymbol(O) mcolor(maroon) msize(medium)), ///
                        ylabel(1(1)4, valuelabel angle(0) labsize(small)) yscale(reverse) ///
                        xlabel(.50(.05).80, format(%4.2f)) xscale(range(.50 .81)) ///
                        xline(`=scalar(`rhohat')', lpattern(dash) lcolor(gs8)) ///
                        legend(off) xtitle("Correlation and 95% confidence interval") ytitle("") ///
                        title("Same r, different 95% confidence intervals", size(medsmall)) ///
                        subtitle("auto: trunk and weight; n = 74; r = 0.6722", size(small)) ///
                        note("Dots and the dashed line mark the sample correlation, not interval midpoints.", size(vsmall)) ///
                        graphregion(color(white)) plotregion(color(white)) ///
                        xsize(9) ysize(4.5) name(ci_sandbox_intervals, replace)
                    graph export "ci_intervals_sandbox.png", replace width(1800)
                    graph export "ci_intervals_sandbox.svg", replace
                    restore
                    Selected output from Stata/MP 16.1 (temporary matrix identifiers omitted):

                    Code:
                     n             r   se_r_robust   se_z_robust  se_z_classic
                    74.0000000  0.6722057     0.0614078     0.1120296     0.1186782
                    
                                      lower      upper
                       r_robust   0.5518486  0.7925629
                       z_robust   0.5336126  0.7756392
                      z_classic   0.5242273  0.7807783
                         z_bias   0.5208804  0.7789745
                    
                                  lower_change  upper_change
                      scale_only    -0.0182360    -0.0169236
                         SE_only    -0.0093853     0.0051391
                       bias_only    -0.0033469    -0.0018039
                    The figure shows these same four intervals. The dots and dashed line mark the common sample correlation, not the interval midpoints. The plotting code uses the interval matrix printed above, rather than separately entered endpoints.

                    The first comparison is r_robust versus z_robust. Both use the same estimated robust variance. The delta method gives se(z) = se(r)/(1-r^2), but this is a first-order approximation. Because tanh() is nonlinear, back-transforming the newly constructed z interval does not give the original symmetric r interval. Here both endpoints move downward, and the interval is no longer symmetric around r.

                    This is different from merely transforming an existing interval's endpoints and then transforming them back: that returns the original interval. The two assertions in the code distinguish these operations. The difference here comes from reconstructing a Wald approximation on another scale, not from a display format or deliberate rounding.

                    Next, z_robust versus z_classic changes only the z-scale standard error: 0.1120296 is replaced by the classical 1/sqrt(n-3) = 0.1186782. That formula uses the conventional bivariate-normal approximation; it is not obtained simply by renaming the robust standard error.

                    Finally, z_bias shifts the z centre by -r/[2(n-1)], keeping the classical standard error. CORRCI already uses Fisher-z intervals by default; its fisher option requests this additional bias correction.

                    For the Pearson branch in the versions I checked, the rows reproduce:

                    Code:
                    r_robust   polycorr trunk weight
                    z_robust   polycorr trunk weight, cifz
                    z_classic  corrci trunk weight
                    z_bias     corrci trunk weight, fisher
                    Those comparisons used POLYCORR 1.1.4 (25 October 2026) and CORRCI 1.3.1 (18 May 2021). The self-contained code above does not call either command. It isolates their interval calculations for this complete, unweighted Pearson example.

                    The final table records successive endpoint changes along the specified path: scale, then SE, then bias. Their sum equals the total change from the first interval to the last. It is a path-specific arithmetic breakdown, not a claim that the relative importance of the three choices is independent of their order.

                    This helped me see why intervals described as "95% CIs for the same correlation" need not match. It does not tell us which has better actual coverage. That would require repeated sampling under specified population distributions, rather than this single-sample calculation.

                    References:
                    Original POLYCORR/CORRCI discussion
                    POLYCORR help
                    CORRCI help (SJ21-3 update)
                    Last edited by Choonjoo Lee; 01 Nov 2026, 17:24.

                    Comment


                    • #11
                      Do nominal 95% confidence intervals for a correlation achieve 95% coverage?

                      After separating scale, standard error and bias correction in a single-sample example, I tried the next question: how often do those intervals actually cover the population correlation?

                      I compared the same four constructions. Here z = atanh(r), q = invnormal(.975), and se_r is the independent-observation robust influence-function standard error with the n/(n-1) adjustment.

                      Code:
                      r/robust   r +/- q*se_r
                      z/robust   tanh(z +/- q*se_r/(1-r^2))
                      z/classic  tanh(z +/- q/sqrt(n-3))
                      z/bias     tanh(z - r/[2(n-1)] +/- q/sqrt(n-3))
                      These reproduce the Pearson interval calculations in POLYCORR 1.1.4 (25 October 2026) and CORRCI 1.3.1 (18 May 2021). I used direct Mata calculations for the simulation; before running it, I checked them against the commands on 18 generated samples, with agreement within 1e-10.

                      The full experiment has n = 30, 74 and 300; true Pearson rho = 0, .7 and .95; and three population models. Each of the 27 conditions has 20,000 independent samples. All four methods share each sample. Coverage means L <= true rho <= U, not whether the interval contains the observed r. I did not round or clip endpoints. There were no computational failures in this run.

                      The populations are bivariate normal, common-scale bivariate t with 5 degrees of freedom, and lognormal margins with log-SD = 1. The t model multiplies both coordinates of a bivariate normal observation by sqrt(5/U), with independent U ~ chi-square(5). Its Pearson correlation remains rho; at rho=0 its coordinates are uncorrelated but not independent. For the lognormal model, the latent normal correlation is gamma = ln(1 + rho*(exp(1)-1)), so the Pearson correlation after exponentiation is exactly the requested rho. I did not simply exponentiate normals whose correlation was rho.

                      Here is the n=74, rho=.7 result:

                      Code:
                      DGP          Method      Coverage %   MCSE (pp)   Mean width
                      Normal       r/robust       92.755       0.183       0.2296
                      Normal       z/robust       93.495       0.174       0.2312
                      Normal       z/classic      95.005       0.154       0.2391
                      Normal       z/bias         95.105       0.153       0.2406
                      t(5)         r/robust       89.545       0.216       0.2877
                      t(5)         z/robust       91.630       0.196       0.2908
                      t(5)         z/classic      84.795       0.254       0.2383
                      t(5)         z/bias         84.965       0.253       0.2398
                      Lognormal    r/robust       77.905       0.293       0.3012
                      Lognormal    z/robust       83.765       0.261       0.3122
                      Lognormal    z/classic      67.845       0.330       0.2215
                      Lognormal    z/bias         68.210       0.329       0.2229
                      MCSE is Monte Carlo standard error, in percentage points. It is sqrt(p_hat*(1-p_hat)/R), or about 0.154 percentage points at 95% coverage with R=20,000. Mean width is the average U-L. The full results also retain failures and the two directions of noncoverage.

                      Figure 1 shows coverage over the three correlations at n=74. Figure 2 varies n with rho=.7. Their whiskers are 95% Wilson intervals for Monte Carlo uncertainty, not confidence intervals for rho. Lines connect only the tested settings, and methods are offset horizontally for visibility.

                      Under normality, the classical Fisher-z intervals were close to 95%, while the robust intervals undercovered at smaller n. For the positive correlations in these t and lognormal examples, z/robust had higher coverage than z/classic, but did not reach 95% at n=74. At rho=.7, increasing n from 30 to 300 moved lognormal z/robust coverage from 79.275% to 88.595%, whereas z/classic moved from 74.625% to 59.130%. More observations do not automatically repair an unsuitable variance approximation.

                      There is an important counterexample to a blanket preference for robust intervals: in the lognormal model with rho=0 and n=74, z/classic covered 95.355%, compared with 84.820% for z/robust. These are observations under specified models, not a universal ranking of methods or an assessment of the unknown population behind auto.

                      The full experiment also uses paired MCSEs for coverage differences, because the methods share samples. For z/robust minus z/classic at n=74, rho=.7, the differences were -1.510, +6.835 and +15.920 percentage points for normal, t(5) and lognormal respectively; their paired MCSEs were 0.109, 0.202 and 0.296 percentage points. Small last-decimal differences should be read with their simulation uncertainty.

                      The code below reproduces the 12-row table above, not the entire grid. It needs no add-ons or input files and restores the dataset, but resets the RNG and changes its state. The attached coverage_sandbox_post_files.zip contains full_study_standalone.do, both figures and complete result tables. The standalone file reproduces all 27 conditions and the figures in a fresh working directory without downloads; save your data first, as it clears memory and writes coverage_results/.

                      Code:
                      version 16.1
                      set more off
                      set rng mt64
                      preserve
                      tempname output
                      capture mata: mata drop ci_covdemo()
                      mata:
                      void ci_covdemo(string scalar outname)
                      {
                          real scalar R,n,rho,gamma,g,rep,j,r,sr,z,sz,sc,q,bias,nv,p
                          real matrix Z,Y,F,L,U,valid,H,T
                          real colvector scale,x,y,IF,ok,w
                          R=20000
                          n=74
                          rho=.7
                          gamma=ln(1+rho*(exp(1)-1))
                          q=invnormal(.975)
                          sc=1/sqrt(n-3)
                          T=J(12,9,.)
                          for(g=1;g<=3;g++) {
                              // Same cell seeds as the full 27-condition experiment.
                              rseed(20261102+10000*g+202)
                              F=J(R,8,.)
                              for(rep=1;rep<=R;rep++) {
                                  Z=rnormal(n,2,0,1)
                                  if(g==3) Y=(exp(Z[,1]),exp(gamma*Z[,1]+sqrt(1-gamma^2)*Z[,2]))
                                  else {
                                      Y=(Z[,1],rho*Z[,1]+sqrt(1-rho^2)*Z[,2])
                                      if(g==2) {
                                          scale=sqrt(5:/rchi2(n,1,5))
                                          Y=Y:*(scale,scale)
                                      }
                                  }
                                  x=Y[,1]:-mean(Y[,1])
                                  y=Y[,2]:-mean(Y[,2])
                                  if(mean(x:^2)<=0 | mean(y:^2)<=0) continue
                                  x=x/sqrt(mean(x:^2))
                                  y=y/sqrt(mean(y:^2))
                                  r=mean(x:*y)
                                  if(missing(r) | abs(r)>=1) continue
                                  IF=x:*y-(r/2):*(x:^2+y:^2)
                                  sr=sqrt(sum(IF:^2)/(n*(n-1)))
                                  z=atanh(r)
                                  sz=sr/(1-r^2)
                                  bias=-r/(2*(n-1))
                                  F[rep,]=(r-q*sr,r+q*sr,tanh(z-q*sz),tanh(z+q*sz),
                                      tanh(z-q*sc),tanh(z+q*sc),tanh(z+bias-q*sc),tanh(z+bias+q*sc))
                              }
                              L=F[,(1,3,5,7)]
                              U=F[,(2,4,6,8)]
                              valid=(L:<.):&(U:<.):&(L:<=U)
                              H=valid:&(L:<=rho):&(U:>=rho)
                              for(j=1;j<=4;j++) {
                                  ok=valid[,j]
                                  nv=sum(ok)
                                  assert(nv>1)
                                  p=sum(H[,j])/nv
                                  w=select(U[,j]-L[,j],ok)
                                  T[4*(g-1)+j,]=(g,j,nv,R-nv,100*p,
                                      100*sqrt(p*(1-p)/nv),mean(w),
                                      100*sum(ok:&(U[,j]:<rho))/nv,100*sum(ok:&(L[,j]:>rho))/nv)
                              }
                          }
                          st_matrix(outname,T)
                      }
                      end
                      mata: ci_covdemo("`output'")
                      mata: mata drop ci_covdemo()
                      matrix colnames `output'=dgp method valid failures cover_pct mcse_pp width below_pct above_pct
                      clear
                      svmat double `output', names(col)
                      label define ci_dgp 1 "Normal" 2 "t(5)" 3 "Lognormal", replace
                      label define ci_method 1 "r/robust" 2 "z/robust" 3 "z/classic" 4 "z/bias", replace
                      label values dgp ci_dgp
                      label values method ci_method
                      format cover_pct mcse_pp below_pct above_pct %8.3f
                      format width %8.4f
                      list dgp method cover_pct mcse_pp width failures, noobs sepby(dgp)
                      assert abs(cover_pct+below_pct+above_pct-100)<1e-10
                      restore
                      For me, the useful distinction is between a nominal level, a large-sample approximation, and its finite-sample behavior under a stated population. "Robust" and "Fisher-z" describe parts of the calculation; neither by itself guarantees 95% coverage in every finite sample. I would be interested in similarly small comparisons, especially methods that improve coverage without an excessive increase in width.

                      References:
                      Cox (2008): Correlation with confidence, or Fisher's z revisited
                      POLYCORR help
                      CORRCI help (SJ21-3 update)
                      Attached Files
                      Last edited by Choonjoo Lee; 01 Nov 2026, 18:15.

                      Comment


                      • #12
                        Confidence intervals for Pearson's correlation: coverage and width

                        Following the single-sample comparison and the coverage experiment, I asked whether bootstrap methods could improve coverage without making confidence intervals much wider.

                        I added percentile, bias-corrected and accelerated (BCa), and Fisher-z bootstrap-t confidence intervals to the previous four methods. The encouraging result was that percentile gave a substantial improvement at a modest width cost in the lognormal example. It still fell short of 95%, and the more elaborate methods did not necessarily perform better.

                        I used n=74 and true population Pearson rho=.7, with 5,000 independent samples from each of three populations. All seven methods share each original sample; the three bootstrap methods also share its 1,999 paired resamples. The populations are bivariate normal, common-scale bivariate t(5), and lognormal with log-SD=1. The t model applies the same sqrt(5/chi2(5)) multiplier to both coordinates of each normal observation. For lognormal data, the latent normal correlation is ln(1+rho*(exp(1)-1)), so the correlation after exponentiation is exactly .7.

                        The first four methods are raw-r robust Wald, robust Wald on z=atanh(r), classical Fisher-z with SE(z)=1/sqrt(n-3), and classical Fisher-z with the additional center correction -r/[2(n-1)]. The new BCa method uses leave-one-out correlations for its acceleration. The bootstrap-t method re-estimates the robust influence-function SE in every resample, applies the delta method on the z scale, and inverts the bootstrap quantiles of T*=(atanh(r*)-atanh(r))/SE(z*). This is the delta-SE version of transformed bootstrap-t; jackknife-SE studentization is a separate method not tested here.

                        Code:
                                             Coverage (%) / mean width
                        Method                 Normal             t(5)           Lognormal
                        r/robust            91.78 / 0.2271    89.68 / 0.2879    77.98 / 0.3032
                        z/robust            93.10 / 0.2287    91.80 / 0.2910    83.82 / 0.3139
                        Fisher-z            94.44 / 0.2373    84.72 / 0.2384    67.60 / 0.2228
                        Fisher-z + bias     94.64 / 0.2388    85.06 / 0.2399    67.86 / 0.2242
                        Percentile          93.46 / 0.2318    92.64 / 0.2924    91.70 / 0.3257
                        BCa                 93.66 / 0.2342    90.86 / 0.2990    86.16 / 0.3257
                        z bootstrap-t       94.32 / 0.2444    93.00 / 0.3494    87.86 / 0.4242
                        Coverage is the proportion with L <= true rho <= U; mean width is the average U-L. There were no computational failures or clipped endpoints. Coverage MCSEs range from .32 to .66 percentage points. These are new samples and seeds, so the first four rows differ slightly from the preceding experiment.

                        In the lognormal case, percentile increased coverage from 83.82% to 91.70%, while mean width increased from .3139 to .3257, about 3.75%. The coverage gain was 7.88 percentage points, with paired MCSE .46 points. BCa had nearly the same mean width as percentile but lower coverage, 86.16%. Bootstrap-t was wider still, at .4242, with coverage of 87.86%.

                        For t(5), bootstrap-t had the highest estimated coverage, 93.00%, compared with 92.64% for percentile, but its mean width was about 19.5% greater. Under normality, the classical Fisher-z methods were close to 95%; for example, the Monte Carlo Wilson interval for the uncorrected method's 94.44% coverage was [93.77%,95.04%]. None of the seven methods reached 95% in the two nonnormal conditions.

                        Figure 1 shows coverage by method; Figure 2 plots coverage against mean width. Whiskers are 95% Wilson intervals for Monte Carlo uncertainty about coverage, rather than confidence intervals for rho. The axes in Figure 2 vary between panels.

                        BCa sometimes required very extreme bootstrap quantiles. In the lognormal condition, its adjusted tail probabilities corresponded to fewer than 10 bootstrap draws in the smaller tail in 41.64% of samples. I therefore checked B=999,1999,3999 and 19999 on the same first 500 original samples from each population, sharing resamples across B values. For those 500 lognormal samples, increasing B from 1999 to 19999 changed BCa coverage from 86.60% to 86.00% (paired MCSE for the change .53 points), and percentile from 93.20% to 93.60%. This smaller check did not show a remedy from increasing B alone; it is distinct from the 5,000-sample table above.

                        Here is a short example using built-in Stata commands to obtain percentile and BCa confidence intervals for the original auto variables. This is a single-dataset demonstration, not a reproduction of the coverage table. The dataset is restored afterwards, but the RNG state changes.

                        Code:
                        * A single-data example, not a Monte Carlo coverage experiment.
                        * Built-in Stata commands only. The dataset is restored; RNG state changes.
                        version 16.1
                        set more off
                        set rng mt64
                        preserve
                        sysuse auto, clear
                        keep if !missing(trunk,weight)
                        correlate trunk weight
                        quietly bootstrap rho=r(rho), reps(19999) bca seed(20261104) nodots: ///
                            correlate trunk weight
                        estat bootstrap, percentile bca
                        matrix P=e(ci_percentile)
                        matrix A=e(ci_bca)
                        assert P[1,1]<P[2,1] & A[1,1]<A[2,1]
                        restore
                        The final table in Stata/MP 16.1 included:

                        Code:
                        Method       Observed r       95% confidence interval
                        Percentile    .67220573       [.5358939, .7814437]
                        BCa           .67220573       [.5223209, .7732884]
                        The following code below reproduces the seven-method coverage table, the B sensitivity check and all three figures. Save your data and run it in a fresh working directory in Stata/SE or MP 16.1 or later. It clears memory and creates bootstrap_results/; no add-ons, downloads, helper files or Python are required. The recorded results, short example, validation code and method notes are also included. Percentile and BCa calculations were checked against Stata's bstat output; the transformed bootstrap-t quantiles and inverse transformation were checked separately.

                        This remains a comparison at one sample size and one correlation under three specified populations. It does not identify the population behind auto or establish a generally best method. The question of narrow intervals subject to 95% coverage remains open here: in the nonnormal examples, a narrower or more elaborate interval did not establish that coverage requirement. I would welcome suggestions for the next comparison, especially methods that improve coverage with a modest width cost.
                        Code:
                        * Full replication: seven Pearson confidence intervals, three populations.
                        * Save your data; run in a fresh working directory. Stata/SE or MP 16.1+.
                        * No downloads, add-ons, input files, helper files or Python required.
                        * Creates bootstrap_results/ and replaces files of the same names there.
                        * Clears memory, resets RNG state, and changes the graph scheme.
                        version 16.1
                        clear all
                        set more off
                        set rng mt64
                        set matsize 11000
                        capture log close
                        capture mkdir bootstrap_results
                        capture mata: mata drop ci_mc_draw()
                        capture mata: mata drop ci_mc_fit()
                        capture mata: mata drop ci_mc_run()
                        mata:
                        mata set matastrict on
                        
                        // Known population Pearson correlation rho for every DGP.
                        // 1: bivariate normal. 2: common-scale bivariate t_5 (finite fourth moments).
                        // 3: lognormal margins, log-SD=1; latent correlation calibrated analytically.
                        real matrix ci_mc_draw(real scalar n, real scalar rho, real scalar dgp)
                        {
                            real matrix Z, Y
                            real colvector scale
                            real scalar latent
                            Z=rnormal(n,2,0,1)
                            if(dgp==3) {
                                latent=ln(1+rho*(exp(1)-1))
                                assert(abs((exp(latent)-1)/(exp(1)-1)-rho)<1e-12)
                                Y=(exp(Z[,1]),exp(latent*Z[,1]+sqrt(1-latent^2)*Z[,2]))
                            }
                            else {
                                Y=(Z[,1],rho*Z[,1]+sqrt(1-rho^2)*Z[,2])
                                if(dgp==2) {
                                    scale=sqrt(5:/rchi2(n,1,5))
                                    Y=Y:*(scale,scale)
                                }
                            }
                            return(Y)
                        }
                        
                        // n, r, robust SE(r), then lower/upper for four methods.
                        // No clipping of correlations or r-Wald endpoints.
                        real rowvector ci_mc_fit(real matrix Y)
                        {
                            real scalar n, r, sr, sz, sc, q, z, bias
                            real colvector x, y, IF
                            real rowvector out
                            n=rows(Y)
                            out=J(1,11,.)
                            out[1]=n
                            x=Y[,1]:-mean(Y[,1])
                            y=Y[,2]:-mean(Y[,2])
                            if(mean(x:^2)<=0 | mean(y:^2)<=0) return(out)
                            x=x/sqrt(mean(x:^2))
                            y=y/sqrt(mean(y:^2))
                            r=mean(x:*y)
                            if(missing(r) | abs(r)>=1) return(out)
                            IF=x:*y-(r/2):*(x:^2+y:^2)
                            sr=sqrt(sum(IF:^2)/(n*(n-1)))
                            sz=sr/(1-r^2)
                            sc=1/sqrt(n-3)
                            z=atanh(r)
                            q=invnormal(.975)
                            bias=-r/(2*(n-1))
                            out=(n,r,sr,r-q*sr,r+q*sr,tanh(z-q*sz),tanh(z+q*sz),
                                tanh(z-q*sc),tanh(z+q*sc),tanh(z+bias-q*sc),tanh(z+bias+q*sc))
                            return(out)
                        }
                        
                        end
                        
                        capture mata: mata drop be_quantile()
                        capture mata: mata drop be_batch()
                        capture mata: mata drop be_jack()
                        capture mata: mata drop be_intervals()
                        capture mata: mata drop be_run()
                        capture mata: mata drop be_sensitivity()
                        mata:
                        mata set matastrict on
                        
                        // Stata's default empirical quantile: average neighbours when N*p is integer.
                        real scalar be_quantile(real colvector sorted, real scalar p)
                        {
                            real scalar n,h,k
                            n=rows(sorted)
                            if(n==0 | missing(p) | p<=0 | p>=1) return(.)
                            h=n*p
                            k=floor(h)
                            if(k==h & k>=1 & k<n) return((sorted[k]+sorted[k+1])/2)
                            return(sorted[max((1,min((n,ceil(h)))) )])
                        }
                        
                        // Paired nonparametric bootstrap, vectorized across B samples of size n.
                        // Returns r*, robust SE(r*), and T* on the Fisher-z scale.
                        // Draw one index vector: a larger B shares the same initial resamples.
                        real matrix be_batch(real matrix Y, real scalar B, real scalar r0)
                        {
                            real scalar n
                            real colvector index, allx, ally
                            real matrix X,W,IF
                            real rowvector r,sr,sz,T
                            n=rows(Y)
                            index=floor(n*runiform(n*B,1)):+1
                            allx=Y[,1]
                            ally=Y[,2]
                            X=rowshape(allx[index],B)'
                            W=rowshape(ally[index],B)'
                            X=X:-colsum(X)/n
                            W=W:-colsum(W)/n
                            X=X:/sqrt(colsum(X:^2)/n)
                            W=W:/sqrt(colsum(W:^2)/n)
                            r=colsum(X:*W)/n
                            IF=X:*W-(r/2):*(X:^2+W:^2)
                            sr=sqrt(colsum(IF:^2)/(n*(n-1)))
                            sz=sr:/(1:-r:^2)
                            T=(atanh(r):-atanh(r0)):/sz
                            T=editmissing(T,.)
                            return((r',sr',T'))
                        }
                        
                        // Exact leave-one-out correlations from full-sample centred sums.
                        real colvector be_jack(real matrix Y)
                        {
                            real scalar n,Sxx,Syy,Sxy,c
                            real colvector x,y
                            n=rows(Y)
                            x=Y[,1]:-mean(Y[,1])
                            y=Y[,2]:-mean(Y[,2])
                            Sxx=sum(x:^2)
                            Syy=sum(y:^2)
                            Sxy=sum(x:*y)
                            c=n/(n-1)
                            return((Sxy:-c*x:*y):/sqrt((Sxx:-c*x:^2):*(Syy:-c*y:^2)))
                        }
                        
                        // Rows: percentile, BCa on r, bootstrap-t on z (delta-IF studentization).
                        // Columns: lower, upper. Diagnostics retain failed bootstrap draws and tail use.
                        real matrix be_intervals(real matrix Y, real matrix boot, real rowvector original,
                                                 real rowvector diag)
                        {
                            real scalar B,n,nr,nt,r0,s0,z0,a,q,p1,p2,t1,t2,den1,den2
                            real colvector r,t,jack,d,ok
                            real matrix C
                            B=rows(boot)
                            n=rows(Y)
                            r0=original[2]
                            s0=original[3]/(1-r0^2)
                            C=J(3,2,.)
                            diag=J(1,7,.)
                            ok=(boot[,1]:<.):&(abs(boot[,1]):<=1)
                            r=sort(select(boot[,1],ok),1)
                            nr=rows(r)
                            ok=(boot[,3]:<.):&(boot[,2]:>0):&(abs(boot[,1]):<1)
                            t=sort(select(boot[,3],ok),1)
                            nt=rows(t)
                            diag[1..2]=(B-nr,B-nt)
                            // Predeclared rule: at least 99% of the attempted bootstrap draws valid.
                            if(nr>=ceil(.99*B)) {
                                C[1,]=(be_quantile(r,.025),be_quantile(r,.975))
                                p1=sum(r:<=r0)/nr
                                if(p1>0 & p1<1) {
                                    z0=invnormal(p1)
                                    jack=be_jack(Y)
                                    d=mean(jack):-jack
                                    if(sum(d:^2)>0 & !hasmissing(jack)) {
                                        a=sum(d:^3)/(6*sum(d:^2)^1.5)
                                        q=invnormal(.975)
                                        den1=1-a*(z0-q)
                                        den2=1-a*(z0+q)
                                        if(den1>0 & den2>0) {
                                            p1=normal(z0+(z0-q)/den1)
                                            p2=normal(z0+(z0+q)/den2)
                                            if(p1>0 & p2<1 & p1<p2) {
                                                C[2,]=(be_quantile(r,p1),be_quantile(r,p2))
                                                diag[3..7]=(z0,a,p1,p2,nr*min((p1,1-p2)))
                                            }
                                        }
                                    }
                                }
                            }
                            if(nt>=ceil(.99*B) & s0>0 & s0<.) {
                                t1=be_quantile(t,.025)
                                t2=be_quantile(t,.975)
                                C[3,]=(tanh(atanh(r0)-t2*s0),tanh(atanh(r0)-t1*s0))
                            }
                            return(C)
                        }
                        
                        // n=74, rho=.7, three DGPs, seven methods. Resampling never uses true rho.
                        // Independent outer/inner seeds keep outer samples fixed when B changes.
                        void be_run(real scalar R, real scalar B, real scalar outer_seed, real scalar inner_seed,
                                    string scalar prefix)
                        {
                            real scalar g,rep,j,k,row,prow,nv,nc,below,above,p,ncommon,delta,se_delta
                            real scalar n,rho,q,bias,z,sc,sz
                            real rowvector fit,diag
                            real matrix Y,boot,C,BC,draws,diagnostics,lower,upper,valid,covered,widths,S,P,G
                            real colvector ok,w,d,common
                            n=74
                            rho=.7
                            q=invnormal(.975)
                            sc=1/sqrt(n-3)
                            S=J(21,21,.)
                            P=J(63,12,.)
                            G=J(3,10,.)
                            row=0
                            prow=0
                            for(g=1;g<=3;g++) {
                                draws=J(R,14,.)
                                diagnostics=J(R,7,.)
                                for(rep=1;rep<=R;rep++) {
                                    rseed(outer_seed+10000*g+rep)
                                    Y=ci_mc_draw(n,rho,g)
                                    fit=ci_mc_fit(Y)
                                    z=atanh(fit[2])
                                    sz=fit[3]/(1-fit[2]^2)
                                    bias=-fit[2]/(2*(n-1))
                                    C=(fit[4..5]\fit[6..7]\fit[8..9]\fit[10..11])
                                    rseed(inner_seed+10000*g+rep)
                                    boot=be_batch(Y,B,fit[2])
                                    diag=J(1,7,.)
                                    BC=be_intervals(Y,boot,fit,diag)
                                    C=C\BC
                                    draws[rep,]=(C[,1]',C[,2]')
                                    diagnostics[rep,]=diag
                                    if(mod(rep,250)==0) {
                                        printf("DGP=%1.0f  outer %5.0f/%5.0f  B=%4.0f\n",g,rep,R,B)
                                        displayflush()
                                    }
                                }
                                lower=draws[,1..7]
                                upper=draws[,8..14]
                                valid=(lower:<.):&(upper:<.):&(lower:<=upper)
                                covered=valid:&(lower:<=rho):&(upper:>=rho)
                                widths=upper-lower
                                for(j=1;j<=7;j++) {
                                    row++
                                    ok=valid[,j]
                                    nv=sum(ok)
                                    nc=sum(covered[,j])
                                    assert(nv>1)
                                    p=nc/nv
                                    below=sum(ok:&(upper[,j]:<rho))
                                    above=sum(ok:&(lower[,j]:>rho))
                                    assert(nc+below+above==nv)
                                    w=select(widths[,j],ok)
                                    S[row,]=(g,n,rho,R,B,j,nv,R-nv,nc,below,above,p,nc/R,
                                        sqrt(p*(1-p)/nv),mean(w),sqrt(variance(w)/nv),
                                        mean(select(lower[,j],ok)),mean(select(upper[,j],ok)),
                                        sum(ok:&((lower[,j]:< -1):|(upper[,j]:>1)))/nv,below/nv,above/nv)
                                }
                                for(j=1;j<=6;j++) {
                                    for(k=j+1;k<=7;k++) {
                                        prow++
                                        common=valid[,j]:&valid[,k]
                                        ncommon=sum(common)
                                        d=select(covered[,j]-covered[,k],common)
                                        delta=mean(d)
                                        se_delta=sqrt(variance(d)/ncommon)
                                        P[prow,]=(g,n,rho,R,B,j,k,ncommon,delta,se_delta,sum(d:==1),sum(d:== -1))
                                    }
                                }
                                G[g,]=(g,n,rho,R,B,sum(diagnostics[,1]),sum(diagnostics[,2]),
                                    mean(select(diagnostics[,7]:<10,diagnostics[,7]:<.)),
                                    mean(select(diagnostics[,5],diagnostics[,5]:<.)),mean(select(diagnostics[,6],diagnostics[,6]:<.)))
                                st_matrix(prefix+"_draws"+strofreal(g),draws)
                                st_matrix(prefix+"_resampling"+strofreal(g),diagnostics)
                            }
                            st_matrix(prefix+"_summary",S)
                            st_matrix(prefix+"_pairs",P)
                            st_matrix(prefix+"_diagnostics",G)
                        }
                        
                        // B sensitivity on the first R outer samples used in the main run.
                        // Smaller B values are prefixes of the same 19999 resamples.
                        void be_sensitivity(real scalar R, real scalar outer_seed, real scalar inner_seed)
                        {
                            real scalar g,rep,b,j,row
                            real rowvector Bs,fit,diag
                            real matrix Y,boot,C,S
                            Bs=(999,1999,3999,19999)
                            for(g=1;g<=3;g++) {
                                S=J(R*12,15,.)
                                row=0
                                for(rep=1;rep<=R;rep++) {
                                    rseed(outer_seed+10000*g+rep)
                                    Y=ci_mc_draw(74,.7,g)
                                    fit=ci_mc_fit(Y)
                                    rseed(inner_seed+10000*g+rep)
                                    boot=be_batch(Y,19999,fit[2])
                                    for(b=1;b<=4;b++) {
                                        diag=J(1,7,.)
                                        C=be_intervals(Y,boot[1..Bs[b],],fit,diag)
                                        for(j=1;j<=3;j++) {
                                            row++
                                            S[row,]=(g,74,.7,rep,Bs[b],j+4,C[j,],diag)
                                        }
                                    }
                                }
                                st_matrix("sensitivity"+strofreal(g),S)
                            }
                        }
                        end
                        
                        log using bootstrap_results/run_mc.log, text replace
                        timer clear
                        timer on 1
                        // Predeclared comparison: no calibration or tuning against the true rho.
                        mata: be_run(5000,1999,20261103,20361103,"main")
                        matrix colnames main_summary = dgp_id n rho reps B method valid failures covered below above coverage delivered_coverage mcse mean_width mcse_width mean_lower mean_upper outside_rate miss_below miss_above
                        matrix colnames main_pairs = dgp_id n rho reps B method_a method_b n_common delta_coverage mcse_delta a_only b_only
                        matrix colnames main_diagnostics = dgp_id n rho reps B invalid_r invalid_t bca_tail_lt10 mean_p_lower mean_p_upper
                        clear
                        svmat double main_summary, names(col)
                        save bootstrap_results/bootstrap_summary.dta, replace
                        export delimited using bootstrap_results/bootstrap_summary.csv, replace
                        clear
                        svmat double main_pairs, names(col)
                        save bootstrap_results/paired_comparisons.dta, replace
                        export delimited using bootstrap_results/paired_comparisons.csv, replace
                        clear
                        svmat double main_diagnostics, names(col)
                        save bootstrap_results/bootstrap_diagnostics.dta, replace
                        export delimited using bootstrap_results/bootstrap_diagnostics.csv, replace
                        forvalues g=1/3 {
                            clear
                            matrix colnames main_draws`g' = lo1 lo2 lo3 lo4 lo5 lo6 lo7 hi1 hi2 hi3 hi4 hi5 hi6 hi7
                            svmat double main_draws`g', names(col)
                            generate int rep=_n
                            generate byte dgp_id=`g'
                            generate int n=74
                            generate double rho=.7
                            generate int B=1999
                            generate long outer_seed=20261103+10000*dgp_id+rep
                            generate long inner_seed=20361103+10000*dgp_id+rep
                            save bootstrap_results/endpoints_dgp`g'.dta, replace
                            export delimited using bootstrap_results/endpoints_dgp`g'.csv, replace
                            clear
                            matrix colnames main_resampling`g' = invalid_r invalid_t bias_z acceleration p_lower p_upper tail_count
                            svmat double main_resampling`g', names(col)
                            generate int rep=_n
                            generate byte dgp_id=`g'
                            save bootstrap_results/resampling_dgp`g'.dta, replace
                            export delimited using bootstrap_results/resampling_dgp`g'.csv, replace
                        }
                        timer off 1
                        timer list
                        display "BOOTSTRAP_EXTENSION_MAIN_PASSED"
                        log close
                        
                        log using bootstrap_results/check_B.log, text replace
                        timer clear
                        timer on 1
                        mata: be_sensitivity(500,20261103,20361103)
                        forvalues g=1/3 {
                            clear
                            matrix colnames sensitivity`g' = dgp_id n rho rep B method lower upper invalid_r invalid_t bias_z acceleration p_lower p_upper tail_count
                            svmat double sensitivity`g', names(col)
                            save bootstrap_results/B_sensitivity_dgp`g'.dta, replace
                            export delimited using bootstrap_results/B_sensitivity_dgp`g'.csv, replace
                        }
                        timer off 1
                        timer list
                        display "BOOTSTRAP_B_SENSITIVITY_PASSED"
                        log close
                        
                        // Wilson Monte Carlo intervals, calculated in Stata; no Python needed.
                        use bootstrap_results/bootstrap_summary.dta, clear
                        generate double coverage_pct=100*coverage
                        generate double mcse_pp=100*mcse
                        generate double q_mc=invnormal(.975)
                        generate double den_mc=1+q_mc^2/valid
                        generate double center_mc=(coverage+q_mc^2/(2*valid))/den_mc
                        generate double half_mc=q_mc*sqrt(coverage*(1-coverage)/valid+q_mc^2/(4*valid^2))/den_mc
                        generate double coverage_mc_lower=100*(center_mc-half_mc)
                        generate double coverage_mc_upper=100*(center_mc+half_mc)
                        drop q_mc den_mc center_mc half_mc
                        export delimited using bootstrap_results/comparison_for_plot.csv, replace
                        list dgp_id method coverage_pct mcse_pp mean_width failures, noobs sepby(dgp_id)
                        version 16.1
                        clear
                        set more off
                        set scheme s1color
                        capture log close
                        log using bootstrap_results/graphs.log, text replace
                        import delimited using bootstrap_results/comparison_for_plot.csv, clear
                        label define dg 1 "Normal" 2 "Bivariate t(5)" 3 "Lognormal", replace
                        label values dgp_id dg
                        generate byte position=8-method
                        local yl 1 "7  z bootstrap-t" 2 "6  BCa" 3 "5  Percentile" 4 "4  Fisher-z + bias" 5 "3  Fisher-z" 6 "2  z-Wald robust" 7 "1  r-Wald robust"
                        foreach focus in coverage width {
                            if "`focus'"=="coverage" {
                                generate double point=coverage_pct
                                generate double low=coverage_mc_lower
                                generate double high=coverage_mc_upper
                                local heading "Coverage of nominal 95% confidence intervals"
                                local axis "Coverage (%)"
                                local ticks "65(5)100"
                                local reference "xline(95, lcolor(gs7) lpattern(dash))"
                                local fmt "%4.1f"
                                local note "Whiskers: 95% Wilson intervals for Monte Carlo uncertainty about coverage. Dashed line: 95% target."
                            }
                            else {
                                generate double point=mean_width
                                generate double low=mean_width-1.96*mcse_width
                                generate double high=mean_width+1.96*mcse_width
                                local heading "Mean confidence interval width"
                                local axis "Average upper bound minus lower bound"
                                local ticks ".20(.05).45"
                                local reference ""
                                local fmt "%5.3f"
                                local note "Whiskers: mean width +/- 1.96 Monte Carlo standard errors. A shorter interval may have lower coverage."
                            }
                            twoway ///
                              (rcap low high position, horizontal lcolor(gs10)) ///
                              (scatter position point if method<=4, mcolor(gs7) msymbol(O) mlabel(point) mlabformat(`fmt') mlabcolor(gs7) mlabsize(vsmall) mlabposition(3)) ///
                              (scatter position point if method==5, mcolor(navy) msymbol(D) mlabel(point) mlabformat(`fmt') mlabcolor(navy) mlabsize(vsmall) mlabposition(3)) ///
                              (scatter position point if method==6, mcolor(orange_red) msymbol(T) mlabel(point) mlabformat(`fmt') mlabcolor(orange_red) mlabsize(vsmall) mlabposition(3)) ///
                              (scatter position point if method==7, mcolor(forest_green) msymbol(S) mlabel(point) mlabformat(`fmt') mlabcolor(forest_green) mlabsize(vsmall) mlabposition(3)), ///
                              by(dgp_id, cols(3) legend(off) title("`heading'", size(medsmall)) ///
                                subtitle("Pearson correlation: n = 74, true rho = 0.70; 5,000 shared samples; B = 1,999", size(small)) ///
                                note("`note'" "Independent observations; no computational failures. Gray: previous methods. Color: added methods.", size(vsmall))) ///
                              ylabel(`yl', angle(0) labsize(small)) yscale(range(.5 7.5)) ///
                              xlabel(`ticks', labsize(small)) `reference' ///
                              xtitle("`axis'", size(small)) ytitle("") legend(off) ///
                              graphregion(color(white)) xsize(13) ysize(5) name(be_`focus', replace)
                            graph export bootstrap_results/`focus'_by_method.png, replace width(2600)
                            graph export bootstrap_results/`focus'_by_method.svg, replace
                            drop point low high
                        }
                        
                        generate byte clock=cond(method==3,10,cond(method==4,2,cond(method==6,12,cond(method==5,6,cond(method==7,9,3)))))
                        replace clock=12 if dgp_id==2 & method==3
                        replace clock=3 if dgp_id==2 & method==4
                        generate double reference_y=96
                        twoway ///
                         (scatter reference_y mean_width if method==1, msymbol(i)) ///
                         (rcap coverage_mc_lower coverage_mc_upper mean_width, lcolor(gs12)) ///
                         (scatter coverage_pct mean_width if method<=4, mcolor(gs7) msymbol(O) mlabel(method) mlabcolor(gs7) mlabvposition(clock)) ///
                         (scatter coverage_pct mean_width if method==5, mcolor(navy) msymbol(D) mlabel(method) mlabcolor(navy) mlabvposition(clock)) ///
                         (scatter coverage_pct mean_width if method==6, mcolor(orange_red) msymbol(T) mlabel(method) mlabcolor(orange_red) mlabvposition(clock)) ///
                         (scatter coverage_pct mean_width if method==7, mcolor(forest_green) msymbol(S) mlabel(method) mlabcolor(forest_green) mlabvposition(clock)), ///
                         by(dgp_id, cols(3) xrescale yrescale legend(off) ///
                           title("Coverage and width of 95% confidence intervals", size(medsmall)) ///
                           subtitle("n = 74; true rho = 0.70; R = 5,000; B = 1,999", size(small)) ///
                           note("1 r robust; 2 z robust; 3 Fisher-z; 4 Fisher-z + bias; 5 Percentile; 6 BCa; 7 z bootstrap-t." ///
                                "Whiskers: 95% Monte Carlo Wilson intervals. Dashed line: 95% coverage. Panel scales vary.", size(vsmall))) ///
                         yline(95, lcolor(gs7) lpattern(dash)) ylabel(, angle(0) labsize(small)) ///
                         xlabel(, labsize(small) format(%5.3f)) legend(off) ///
                         xtitle("Mean confidence interval width", size(small)) ytitle("Coverage (%)", size(small)) ///
                         graphregion(color(white)) xsize(13) ysize(5) name(be_tradeoff, replace)
                        graph export bootstrap_results/coverage_width_tradeoff.png, replace width(2600)
                        graph export bootstrap_results/coverage_width_tradeoff.svg, replace
                        display "BOOTSTRAP_GRAPHS_PASSED"
                        log close
                        
                        display "BOOTSTRAP_STANDALONE_PASSED"
                        References:
                        Stata: bootstrap postestimation
                        Hall, Martin and Schucany (1989): Better nonparametric bootstrap confidence intervals for the correlation coefficient
                        Efron and Narasimhan (2020): The automatic construction of bootstrap confidence intervals
                        Attached Files
                        Last edited by Choonjoo Lee; 01 Nov 2026, 18:46.

                        Comment


                        • #13
                          Achieving the nominal 95% coverage remains a separate requirement, to be assessed through further calibration and independent validation.

                          Comment


                          • #14
                            Sample size and coverage of confidence intervals for Pearson's correlation

                            Can increasing the sample size bring actual coverage closer to the nominal 95% level? I extended the seven-method comparison to examine this. The most striking result was in the lognormal population: robust z coverage approached 95% while its intervals became narrower, whereas classical Fisher-z coverage deteriorated as n increased.

                            The seven methods are raw-r robust Wald, robust Wald on z=atanh(r), classical Fisher-z, classical Fisher-z with its additional center bias correction, percentile bootstrap, BCa, and Fisher-z bootstrap-t with delta/influence-function studentization. This follows the earlier coverage experiment and the n=74 bootstrap comparison.

                            I retained true population Pearson rho=.7 and the same three populations: bivariate normal, common-scale bivariate t(5), and lognormal margins with log-SD=1. All observations are independent. The lognormal latent correlation is ln(1+rho*(exp(1)-1)), so rho=.7 refers to the original variables, rather than their logs.

                            The n=74 reference rows reuse the 5,000-sample bootstrap comparison. I added 2,000 samples per population at each of n=300 and n=1,000, with B=1,999 paired resamples per original sample. Methods share samples within each condition. Different sample sizes use independent original samples. These new n=300 results use different seeds and fewer repetitions than the earlier four-method experiment.
                            Click image for larger version

Name:	coverage_by_sample_size.png
Views:	1
Size:	185.2 KB
ID:	1787900

                            Click image for larger version

Name:	lognormal_large_n.png
Views:	1
Size:	176.4 KB
ID:	1787901


                            Code:
                            Actual coverage (%) at n=1,000; R=2,000; B=1,999
                            Method                 Normal       t(5)     Lognormal
                            r/robust                 95.75     93.55     89.65
                            z/robust                 95.75     93.75     91.45
                            Fisher-z                 96.00     78.80     52.90
                            Fisher-z + bias          96.10     78.80     52.75
                            Percentile               95.35     93.65     92.95
                            BCa                      95.45     91.20     86.95
                            z bootstrap-t            95.60     93.20     91.30
                            The normal estimates ranged from 95.35% to 96.10%; they should be read alongside their Monte Carlo uncertainty. In t(5) and lognormal data, every estimated coverage remained below 95% at n=1,000. For example, lognormal percentile coverage was 92.95%, with a 95% Monte Carlo Wilson interval of [91.74%,93.99%]. Finite-sample performance also need not improve monotonically at every step. Figure 1 shows all seven trajectories at n=74,300 and 1,000.

                            I then made an additional large-n diagnostic for lognormal data: n=10,000 with 5,000 samples, and n=100,000 with 2,000 samples. Only the four original methods were computed at these larger sizes; the following table shows two of them. The three bootstrap methods were not tested beyond n=1,000.

                            Code:
                            Lognormal population: true Pearson rho=.7
                            Coverage (%); mean confidence interval width
                            n           R       z/robust    Fisher-z    Mean width (z/robust)
                                 74   5,000        83.82       67.60            0.313934
                                300   2,000        87.60       58.95            0.217979
                              1,000   2,000        91.45       52.90            0.151486
                             10,000   5,000        94.36       42.30            0.065233
                            100,000   2,000        94.80       40.20            0.024364
                            At n=100,000, robust z coverage was 94.80%, with Monte Carlo SE .50 percentage points and a 95% Monte Carlo Wilson interval of [93.74%,95.69%]. This is compatible with 95% coverage; it does not establish exact coverage or a minimum sufficient sample size. The average width fell from .313934 at n=74 to .024364 at n=100,000. Thus, collecting more observations can improve coverage while also giving narrower intervals.

                            The classical Fisher-z interval also became narrower, but its coverage fell from 67.60% to 40.20%. Increasing n does not repair a variance formula that remains inappropriate for the population. Both the true sampling SD and the calculated interval width can shrink at order 1/sqrt(n), while their ratio remains wrong. This distinction between asymptotic normality and the appropriate asymptotic variance is discussed by Angus (1991); Bishara and Hittner (2017) also report cases where increasing n worsened classical Fisher-z coverage under nonnormality.

                            Figure 2 shows the lognormal coverage and width results over the larger range of n. Coverage whiskers in both figures are individual 95% Wilson intervals for Monte Carlo uncertainty, rather than confidence intervals for rho. Width whiskers in Figure 2 are mean width +/- 1.96 Monte Carlo SEs. Lines join tested sample sizes only, and the sample-size axes are logarithmic.

                            There were no computational failures in these runs. Bootstrap methods still used the finite B=1,999 algorithm: for example, in 24.2% of lognormal samples at n=1,000, BCa's smaller adjusted tail probability multiplied by B was below 10. This is a tail-resolution diagnostic, not a formal failure. It remains relevant when interpreting the bootstrap results.

                            -Replication code is available upon request.-

                            These results show a way to approach nominal coverage in one difficult population, rather than a universal sample-size rule. They do not imply that 100,000 observations are generally necessary, that all bootstrap methods would behave similarly there, or that an interval which happens to exceed 95% coverage is automatically preferable. A useful next question is how to obtain better coverage at the sample sizes available in practice.

                            References:
                            Angus (1991): A simple asymptotic analysis of Fisher's z-statistic
                            Bishara and Hittner (2017): Confidence intervals for correlations when data are not normal

                            Comment

                            Working...
                            X