RegalFire's picture
Publish verified RegalFire scientific product v2
346ecdb verified
Raw History Blame Contribute Delete
339 kB
{"accepted_answer": {"answer_html": "<p>I would suggest you look at a changing a couple of things:</p>\n<ol>\n<li><p>The distribution of <code>Age</code> is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.</p>\n<p>If you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.</p>\n</li>\n<li><p>The <code>fs</code> smooths by <code>Taxon</code> aren't really doing much because they are very restricted in terms of basis functions.</p>\n</li>\n<li><p>There is potential for an identifiability issue as you include a <code>Taxon</code> random intercept through the <code>fs</code> smooths, and then again through the ranef structure.</p>\n<p>Identifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the <code>random</code> argument and the <code>fs</code> basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.</p>\n</li>\n<li><p>You will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is <code>To</code> <code>Fa</code> for example?).</p>\n</li>\n</ol>\n<p>Unless you think the mean of <code>Asfc</code> for individual taxa changes over time smoothly, then there is no reason to use the taxon specific <code>fs</code> smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of <code>Asfc</code> per <code>Facet</code>? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need <code>Taxon</code> at the highest level of the random effect structure.</p>\n<p>Finally, your model assume that the response <code>Acsf</code> values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are <em>not</em> observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.</p>\n<blockquote>\n<p>As an aside, how do I only plot the first plot?</p>\n</blockquote>\n<p>Use the <code>select</code> argument to <em>gratia</em>' <code>draw()</code> function. This is a generic function so you need to look at the <a href=\"https://gavinsimpson.github.io/gratia/reference/draw.gam.html\" rel=\"nofollow noreferrer\">help for the <code>gam</code> method</a>.</p>\n", "answer_id": 676895, "answer_text": "I would suggest you look at a changing a couple of things:\n\n\n\n\n\n\n\nThe distribution of Age is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.\n\n\n\n\nIf you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.\n\n\n\n\n\n\n\n\n\nThe fs smooths by Taxon aren't really doing much because they are very restricted in terms of basis functions.\n\n\n\n\n\n\n\n\n\nThere is potential for an identifiability issue as you include a Taxon random intercept through the fs smooths, and then again through the ranef structure.\n\n\n\n\nIdentifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the random argument and the fs basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.\n\n\n\n\n\n\n\n\n\nYou will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is To Fa for example?).\n\n\n\n\n\n\n\n\nUnless you think the mean of Asfc for individual taxa changes over time smoothly, then there is no reason to use the taxon specific fs smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of Asfc per Facet? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need Taxon at the highest level of the random effect structure.\n\n\n\n\nFinally, your model assume that the response Acsf values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are not observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.\n\n\n\n\n\n\n\nAs an aside, how do I only plot the first plot?\n\n\n\n\n\n\n\nUse the select argument to gratia' draw() function. This is a generic function so you need to look at the help for the gam method (https://gavinsimpson.github.io/gratia/reference/draw.gam.html).", "answer_url": "https://stats.stackexchange.com/a/676895", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-17T09:31:11+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676893, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-17T09:31:11+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "344FFDF7-D995-42B0-B0C3-7BDBCFF41311", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/344FFDF7-D995-42B0-B0C3-7BDBCFF41311/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-18T07:38:43+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7758802C-386E-40D4-A5C5-B896DDCE2569", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7758802C-386E-40D4-A5C5-B896DDCE2569/view-source"}], "score": 5, "updated_at": "2026-08-18T07:38:43+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "temp3 <- gamm4(Asfc ~ s(Age, k = 8, bs = \"tp\") + s(Age, taxon, bs = \"fs\", k = 3), data = df, random = ~(1|taxon/Specimen/To/Fa))\ntemp4 <- gamm4(Asfc ~ s(Age, k = 8, bs = \"tp\") + s(Age, taxon, bs = \"fs\", k = 3), data = df, random = ~(1|Specimen/To/Fa))\ndraw(temp3$gam, residuals = TRUE)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676893, "sha256": "240b98345e850296df1179d3dba0fb668fdf9c03ce68b1a29a042e89b58a23b2", "source_url": "https://stats.stackexchange.com/questions/676893/is-this-the-correct-specification-for-gamm4-splines-where-species-are-short-te"}, {"block_index": 1, "code_text": "$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3606.394\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen (Intercept) 0.4767 \n ToothNoLR:Specimen (Intercept) 0.3814 \n Specimen (Intercept) 0.6024 \n Xr s(sqrt(Age)) 7.7972 \n Residual 0.4563 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen, 1430; ToothNoLR:Specimen, 542; Specimen, 421; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n 0.008243 -0.872465 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n5.56 total = 6.56 \n\nlmer.REML score: 3606.394 \n\nattr(,\"class\")\n[1] \"gamm4\" \"list\" \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676893, "sha256": "040d8eaaca938aa94bac4839bcb434a3369207a5fa288e1557d391cf8a1e8829", "source_url": "https://stats.stackexchange.com/questions/676893/is-this-the-correct-specification-for-gamm4-splines-where-species-are-short-te"}, {"block_index": 2, "code_text": "> temp3 <- gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.052\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4786 \n ToothNoLR:Specimen:taxon (Intercept) 0.3614 \n Specimen:taxon (Intercept) 0.5246 \n taxon (Intercept) 0.4379 \n Xr s(sqrt(Age)) 4.5753 \n Residual 0.4561 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n -0.04013 -0.01014 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n4.3 total = 5.3 \n\nlmer.REML score: 3566.053\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676893, "sha256": "7fd17e0b981fc6b5918257dbe25b5a4963afcd9ffe92387edc8eb5c5cb8d424d", "source_url": "https://stats.stackexchange.com/questions/676893/is-this-the-correct-specification-for-gamm4-splines-where-species-are-short-te"}, {"block_index": 3, "code_text": "> temp3 <- gamm4(Asfc ~ s(Age, k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.762\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4651 \n ToothNoLR:Specimen:taxon (Intercept) 0.3611 \n Specimen:taxon (Intercept) 0.5317 \n taxon (Intercept) 0.3790 \n Xr s(Age) 7.4438 \n Residual 0.4692 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\nX(Intercept) Xs(Age)Fx1 \n -0.04286 -0.98535 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(Age, k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n4.77 total = 5.77 \n\nlmer.REML score: 3566.762 \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676893, "sha256": "7196013cc0581d9308ec8bd162d49f25573bac853a85515b002ed11e43a8595d", "source_url": "https://stats.stackexchange.com/questions/676893/is-this-the-correct-specification-for-gamm4-splines-where-species-are-short-te"}], "other_answers": [], "product": "code_qa", "question": "I have ~1400 measurements of teeth from ~40 species (taxon) that go back in time ~35mya (Age).\nThe data is noisy, so there is repetition in measurements from specimens that requires nesting as a random effect.\n\n\n\n\nI wish to see if there are trends in this data through time. I can see the trends as individual taxon boxplots if I roughly order them by time, but I would highly prefer Age as a continuous variable and the repetition accounted for.\n\n\n\n\nThe problem is that taxa (i.e. species) generally exist for 1my or less, and there are large gaps, so if I understand gamms properly (not a given here lol) then the smoothing splines will be (in my simple terms) trying to extrapolate/estimate the curves for a species across the entire dataset where they don't really exist. I have tried to compensate for this using factor smoothing for taxon.\n\n\n\n\nTo cut to the point after much testing and fiddling, I came up with this:\n\n\n\n\ntemp3 <- gamm4(Asfc ~ s(Age, k = 8, bs = \"tp\") + s(Age, taxon, bs = \"fs\", k = 3), data = df, random = ~(1|taxon/Specimen/To/Fa))\ntemp4 <- gamm4(Asfc ~ s(Age, k = 8, bs = \"tp\") + s(Age, taxon, bs = \"fs\", k = 3), data = df, random = ~(1|Specimen/To/Fa))\ndraw(temp3$gam, residuals = TRUE)\n\n\n\n\n\nAnd I get something like this:\n[image: gamm4 plot; source: https://i.sstatic.net/M6wP2hpB.jpg] (https://i.sstatic.net/M6wP2hpB.jpg)\n\n\n\n\nFor this data am I \"gamm-ing\" correctly? The second plot suggests errr no, or is that just the intercept and slope for taxon influence?\n\n\n\n\nShould taxon be in the random effect structure? There are many specimens of each taxon.\n\n\n\n\nAs an aside, how do I only plot the first plot?\n\n\n\n\n------ Edit for clarification from questions (and comments) below ------\n\n\n\n\nEach measurement is in this example a \"complexity\" value of a single facet (Fa has four levels), from a tooth (To has 8 levels). There are 1 to 8 measurements per Specimen requiring it to be a random effect. Each Specimen does belong to a species, though Species may or may not require nesting, or inclusion in the model per se, since most species have a single value for age, or are spread over 0.5 million years at most, it is highly correlated to Age and may be superfluous. Asfc is continuous, well normalised, and is considered gaussian.\n\n\n\n\nThis is an updated model with model check based on comments : gamm4(Asfc ~ s(sqrtAge, k = 8, bs =\"tp\"), data = df, random = ~(1|Specimen/ToothNoLR/Facet))\n[image: newGamm; source: https://i.sstatic.net/UmccNppE.jpg] (https://i.sstatic.net/UmccNppE.jpg)\n\n\n\n\n[image: checkgamm; source: https://i.sstatic.net/gYiJQdTI.jpg] (https://i.sstatic.net/gYiJQdTI.jpg)\n\n\n\n\nRE check_model() I'm doing this to look for verifiable trends, not for prediction. I realise the large gaps would make the latter difficult, so this is more exploratory to see if a signal is present.\n\n\n\n\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3606.394\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen (Intercept) 0.4767 \n ToothNoLR:Specimen (Intercept) 0.3814 \n Specimen (Intercept) 0.6024 \n Xr s(sqrt(Age)) 7.7972 \n Residual 0.4563 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen, 1430; ToothNoLR:Specimen, 542; Specimen, 421; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n 0.008243 -0.872465 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n5.56 total = 6.56 \n\nlmer.REML score: 3606.394 \n\nattr(,\"class\")\n[1] \"gamm4\" \"list\" \n\n\n\n\n\n------ 2nd edit updating random effect structure ------\nHere is the model with taxon added. The CI's are worse, but I suspect it is a \"truer\" model. gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n\n\n\n\n[image: REtaxonadded; source: https://i.sstatic.net/KnHUkWbG.jpg] (https://i.sstatic.net/KnHUkWbG.jpg)\n\n\n\n\nThe check shows a more even spread of residuals.\n\n\n\n\n[image: retaxoncheck; source: https://i.sstatic.net/IXmEOkWk.jpg] (https://i.sstatic.net/IXmEOkWk.jpg)\n\n\n\n\nThese are the new results.\n\n\n\n\n> temp3 <- gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.052\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4786 \n ToothNoLR:Specimen:taxon (Intercept) 0.3614 \n Specimen:taxon (Intercept) 0.5246 \n taxon (Intercept) 0.4379 \n Xr s(sqrt(Age)) 4.5753 \n Residual 0.4561 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n -0.04013 -0.01014 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n4.3 total = 5.3 \n\nlmer.REML score: 3566.053\n\n\n\n\n\nCompare them to the results where Age is not sqrt()'ed\n\n\n\n\n> temp3 <- gamm4(Asfc ~ s(Age, k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.762\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4651 \n ToothNoLR:Specimen:taxon (Intercept) 0.3611 \n Specimen:taxon (Intercept) 0.5317 \n taxon (Intercept) 0.3790 \n Xr s(Age) 7.4438 \n Residual 0.4692 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\nX(Intercept) Xs(Age)Fx1 \n -0.04286 -0.98535 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(Age, k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n4.77 total = 5.77 \n\nlmer.REML score: 3566.762 \n\n\n\n\n\nI would appreciate any help in interpreting all this.\n\n\n\n\n------ Edit ------\nIn reply to the posterior predictive check. Removal of Facet.\n[image: enter image description here; source: https://i.sstatic.net/iV7wvyRj.jpg] (https://i.sstatic.net/iV7wvyRj.jpg)\ntemp3 without Facet in nesting, temp4 with Facet in nesting.\n\n\n\n\n> compare_performance(temp3, temp4)\n# Comparison of Model Performance Indices\n\nName | Model | AIC (weights) | BIC (weights) | R2 | RMSE | Sigma\n-----------------------------------------------------------------------\ntemp3 | gamm4 | 4031.8 (0.475) | 4065.0 (0.484) | 0.049 | 0.572 | 0.573\ntemp4 | gamm4 | 4031.6 (0.525) | 4064.8 (0.516) | 0.049 | 0.274 | 0.275\n\n\n\n\n\n------ quick edit ------\nSo, yes, when I check $mer I get these results, and it appears to be(?), the missing \"components\" to complete the response?:\n\n\n\n\n> model_performance(temp3$mer)\n# Indices of model performance\n\nAIC | AICc | BIC | R2 (cond.) | R2 (marg.) | ICC | RMSE | Sigma\n--------------------------------------------------------------------------\n3581.9 | 3582.0 | 3618.9 | 0.579 | 1.298e-04 | 0.579 | 0.572 | 0.660\n\n> icc(temp3$mer, by_group = TRUE)\n\nGroup | ICC\n--------------------------------\nToothNoLR:Specimen:taxon | 0.127\nSpecimen:taxon | 0.267\ntaxon | 0.185\n> check_model(temp3$mer)\n\n\n\n\n\nJust the lmer component predictive curve.\n[image: enter image description here; source: https://i.sstatic.net/H3mCUZgO.jpg] (https://i.sstatic.net/H3mCUZgO.jpg)\n\n\n\n\n> check_model(temp3) Throws an error, so it seems it is incapable of incorporating both $mer and $gam into the check.", "record_id": "Scientific-Code-and-Analysis-QA:stats:676893", "selected_answer": {"answer_html": "<p>I would suggest you look at a changing a couple of things:</p>\n<ol>\n<li><p>The distribution of <code>Age</code> is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.</p>\n<p>If you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.</p>\n</li>\n<li><p>The <code>fs</code> smooths by <code>Taxon</code> aren't really doing much because they are very restricted in terms of basis functions.</p>\n</li>\n<li><p>There is potential for an identifiability issue as you include a <code>Taxon</code> random intercept through the <code>fs</code> smooths, and then again through the ranef structure.</p>\n<p>Identifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the <code>random</code> argument and the <code>fs</code> basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.</p>\n</li>\n<li><p>You will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is <code>To</code> <code>Fa</code> for example?).</p>\n</li>\n</ol>\n<p>Unless you think the mean of <code>Asfc</code> for individual taxa changes over time smoothly, then there is no reason to use the taxon specific <code>fs</code> smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of <code>Asfc</code> per <code>Facet</code>? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need <code>Taxon</code> at the highest level of the random effect structure.</p>\n<p>Finally, your model assume that the response <code>Acsf</code> values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are <em>not</em> observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.</p>\n<blockquote>\n<p>As an aside, how do I only plot the first plot?</p>\n</blockquote>\n<p>Use the <code>select</code> argument to <em>gratia</em>' <code>draw()</code> function. This is a generic function so you need to look at the <a href=\"https://gavinsimpson.github.io/gratia/reference/draw.gam.html\" rel=\"nofollow noreferrer\">help for the <code>gam</code> method</a>.</p>\n", "answer_id": 676895, "answer_text": "I would suggest you look at a changing a couple of things:\n\n\n\n\n\n\n\nThe distribution of Age is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.\n\n\n\n\nIf you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.\n\n\n\n\n\n\n\n\n\nThe fs smooths by Taxon aren't really doing much because they are very restricted in terms of basis functions.\n\n\n\n\n\n\n\n\n\nThere is potential for an identifiability issue as you include a Taxon random intercept through the fs smooths, and then again through the ranef structure.\n\n\n\n\nIdentifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the random argument and the fs basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.\n\n\n\n\n\n\n\n\n\nYou will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is To Fa for example?).\n\n\n\n\n\n\n\n\nUnless you think the mean of Asfc for individual taxa changes over time smoothly, then there is no reason to use the taxon specific fs smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of Asfc per Facet? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need Taxon at the highest level of the random effect structure.\n\n\n\n\nFinally, your model assume that the response Acsf values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are not observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.\n\n\n\n\n\n\n\nAs an aside, how do I only plot the first plot?\n\n\n\n\n\n\n\nUse the select argument to gratia' draw() function. This is a generic function so you need to look at the help for the gam method (https://gavinsimpson.github.io/gratia/reference/draw.gam.html).", "answer_url": "https://stats.stackexchange.com/a/676895", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-17T09:31:11+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676893, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-17T09:31:11+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "344FFDF7-D995-42B0-B0C3-7BDBCFF41311", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/344FFDF7-D995-42B0-B0C3-7BDBCFF41311/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-18T07:38:43+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7758802C-386E-40D4-A5C5-B896DDCE2569", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7758802C-386E-40D4-A5C5-B896DDCE2569/view-source"}], "score": 5, "updated_at": "2026-08-18T07:38:43+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 676895, "answers": [{"answer_html": "<p>I would suggest you look at a changing a couple of things:</p>\n<ol>\n<li><p>The distribution of <code>Age</code> is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.</p>\n<p>If you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.</p>\n</li>\n<li><p>The <code>fs</code> smooths by <code>Taxon</code> aren't really doing much because they are very restricted in terms of basis functions.</p>\n</li>\n<li><p>There is potential for an identifiability issue as you include a <code>Taxon</code> random intercept through the <code>fs</code> smooths, and then again through the ranef structure.</p>\n<p>Identifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the <code>random</code> argument and the <code>fs</code> basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.</p>\n</li>\n<li><p>You will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is <code>To</code> <code>Fa</code> for example?).</p>\n</li>\n</ol>\n<p>Unless you think the mean of <code>Asfc</code> for individual taxa changes over time smoothly, then there is no reason to use the taxon specific <code>fs</code> smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of <code>Asfc</code> per <code>Facet</code>? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need <code>Taxon</code> at the highest level of the random effect structure.</p>\n<p>Finally, your model assume that the response <code>Acsf</code> values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are <em>not</em> observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.</p>\n<blockquote>\n<p>As an aside, how do I only plot the first plot?</p>\n</blockquote>\n<p>Use the <code>select</code> argument to <em>gratia</em>' <code>draw()</code> function. This is a generic function so you need to look at the <a href=\"https://gavinsimpson.github.io/gratia/reference/draw.gam.html\" rel=\"nofollow noreferrer\">help for the <code>gam</code> method</a>.</p>\n", "answer_id": 676895, "answer_text": "I would suggest you look at a changing a couple of things:\n\n\n\n\n\n\n\nThe distribution of Age is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.\n\n\n\n\nIf you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.\n\n\n\n\n\n\n\n\n\nThe fs smooths by Taxon aren't really doing much because they are very restricted in terms of basis functions.\n\n\n\n\n\n\n\n\n\nThere is potential for an identifiability issue as you include a Taxon random intercept through the fs smooths, and then again through the ranef structure.\n\n\n\n\nIdentifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the random argument and the fs basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.\n\n\n\n\n\n\n\n\n\nYou will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is To Fa for example?).\n\n\n\n\n\n\n\n\nUnless you think the mean of Asfc for individual taxa changes over time smoothly, then there is no reason to use the taxon specific fs smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of Asfc per Facet? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need Taxon at the highest level of the random effect structure.\n\n\n\n\nFinally, your model assume that the response Acsf values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are not observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.\n\n\n\n\n\n\n\nAs an aside, how do I only plot the first plot?\n\n\n\n\n\n\n\nUse the select argument to gratia' draw() function. This is a generic function so you need to look at the help for the gam method (https://gavinsimpson.github.io/gratia/reference/draw.gam.html).", "answer_url": "https://stats.stackexchange.com/a/676895", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-17T09:31:11+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676893, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-17T09:31:11+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "344FFDF7-D995-42B0-B0C3-7BDBCFF41311", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/344FFDF7-D995-42B0-B0C3-7BDBCFF41311/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-18T07:38:43+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7758802C-386E-40D4-A5C5-B896DDCE2569", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7758802C-386E-40D4-A5C5-B896DDCE2569/view-source"}], "score": 5, "updated_at": "2026-08-18T07:38:43+00:00"}], "domain": "statistics", "external_links": ["https://gavinsimpson.github.io/gratia/reference/draw.gam.html", "https://i.sstatic.net/H3mCUZgO.jpg", "https://i.sstatic.net/IXmEOkWk.jpg", "https://i.sstatic.net/KnHUkWbG.jpg", "https://i.sstatic.net/M6wP2hpB.jpg", "https://i.sstatic.net/UmccNppE.jpg", "https://i.sstatic.net/gYiJQdTI.jpg", "https://i.sstatic.net/iV7wvyRj.jpg"], "medical_sensitive": true, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:03.428408+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/774052c18cd9e8fa951e893347bfa3c1a85e743fc46ec4667572002cadb10cbf_1790825224163423600_0.json", "raw_sha256": "fe4dd06d3de6c0b1bb33ba88aee0ed4284118e01f76a58dcdce220a4946329b2", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "MrSwaggins", "question_author_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "question_author_user_type": "registered", "question_created_at": "2026-08-17T05:08:58+00:00", "question_html": "<p>I have ~1400 measurements of teeth from ~40 species (taxon) that go back in time ~35mya (Age).\nThe data is noisy, so there is repetition in measurements from specimens that requires nesting as a random effect.</p>\n<p>I wish to see if there are trends in this data through time. I can see the trends as individual taxon boxplots if I roughly order them by time, but I would highly prefer Age as a continuous variable and the repetition accounted for.</p>\n<p>The problem is that taxa (i.e. species) generally exist for 1my or less, and there are large gaps, so if I understand gamms properly (not a given here lol) then the smoothing splines will be (in my simple terms) trying to extrapolate/estimate the curves for a species across the entire dataset where they don't really exist. I have tried to compensate for this using factor smoothing for taxon.</p>\n<p>To cut to the point after much testing and fiddling, I came up with this:</p>\n<pre><code>temp3 &lt;- gamm4(Asfc ~ s(Age, k = 8, bs = &quot;tp&quot;) + s(Age, taxon, bs = &quot;fs&quot;, k = 3), data = df, random = ~(1|taxon/Specimen/To/Fa))\ntemp4 &lt;- gamm4(Asfc ~ s(Age, k = 8, bs = &quot;tp&quot;) + s(Age, taxon, bs = &quot;fs&quot;, k = 3), data = df, random = ~(1|Specimen/To/Fa))\ndraw(temp3$gam, residuals = TRUE)\n</code></pre>\n<p>And I get something like this:\n<a href=\"https://i.sstatic.net/M6wP2hpB.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/M6wP2hpB.jpg\" alt=\"gamm4 plot\" /></a></p>\n<p>For this data am I &quot;gamm-ing&quot; correctly? The second plot suggests errr no, or is that just the intercept and slope for taxon influence?</p>\n<p>Should taxon be in the random effect structure? There are many specimens of each taxon.</p>\n<p>As an aside, how do I only plot the first plot?</p>\n<p>------ Edit for clarification from questions (and comments) below ------</p>\n<p>Each measurement is in this example a &quot;complexity&quot; value of a single facet (Fa has four levels), from a tooth (To has 8 levels). There are 1 to 8 measurements per Specimen requiring it to be a random effect. Each Specimen does belong to a species, though Species may or may not require nesting, or inclusion in the model per se, since most species have a single value for age, or are spread over 0.5 million years at most, it is highly correlated to Age and may be superfluous. Asfc is continuous, well normalised, and is considered gaussian.</p>\n<p>This is an updated model with model check based on comments : <code>gamm4(Asfc ~ s(sqrtAge, k = 8, bs =&quot;tp&quot;), data = df, random = ~(1|Specimen/ToothNoLR/Facet))</code>\n<a href=\"https://i.sstatic.net/UmccNppE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/UmccNppE.jpg\" alt=\"newGamm\" /></a></p>\n<p><a href=\"https://i.sstatic.net/gYiJQdTI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/gYiJQdTI.jpg\" alt=\"checkgamm\" /></a></p>\n<p>RE <code>check_model()</code> I'm doing this to look for verifiable trends, not for prediction. I realise the large gaps would make the latter difficult, so this is more exploratory to see if a signal is present.</p>\n<pre><code>$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3606.394\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen (Intercept) 0.4767 \n ToothNoLR:Specimen (Intercept) 0.3814 \n Specimen (Intercept) 0.6024 \n Xr s(sqrt(Age)) 7.7972 \n Residual 0.4563 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen, 1430; ToothNoLR:Specimen, 542; Specimen, 421; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n 0.008243 -0.872465 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = &quot;tp&quot;)\n\nEstimated degrees of freedom:\n5.56 total = 6.56 \n\nlmer.REML score: 3606.394 \n\nattr(,&quot;class&quot;)\n[1] &quot;gamm4&quot; &quot;list&quot; \n</code></pre>\n<p>------ 2nd edit updating random effect structure ------\nHere is the model with taxon added. The CI's are worse, but I suspect it is a &quot;truer&quot; model. <code>gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =&quot;tp&quot;), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))</code></p>\n<p><a href=\"https://i.sstatic.net/KnHUkWbG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/KnHUkWbG.jpg\" alt=\"REtaxonadded\" /></a></p>\n<p>The check shows a more even spread of residuals.</p>\n<p><a href=\"https://i.sstatic.net/IXmEOkWk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/IXmEOkWk.jpg\" alt=\"retaxoncheck\" /></a></p>\n<p>These are the new results.</p>\n<pre><code>&gt; temp3 &lt;- gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =&quot;tp&quot;), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n&gt; temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.052\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4786 \n ToothNoLR:Specimen:taxon (Intercept) 0.3614 \n Specimen:taxon (Intercept) 0.5246 \n taxon (Intercept) 0.4379 \n Xr s(sqrt(Age)) 4.5753 \n Residual 0.4561 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n -0.04013 -0.01014 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = &quot;tp&quot;)\n\nEstimated degrees of freedom:\n4.3 total = 5.3 \n\nlmer.REML score: 3566.053\n</code></pre>\n<p>Compare them to the results where <code>Age</code> is not <code>sqrt()</code>'ed</p>\n<pre><code>&gt; temp3 &lt;- gamm4(Asfc ~ s(Age, k = 8, bs =&quot;tp&quot;), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n&gt; temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.762\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4651 \n ToothNoLR:Specimen:taxon (Intercept) 0.3611 \n Specimen:taxon (Intercept) 0.5317 \n taxon (Intercept) 0.3790 \n Xr s(Age) 7.4438 \n Residual 0.4692 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\nX(Intercept) Xs(Age)Fx1 \n -0.04286 -0.98535 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(Age, k = 8, bs = &quot;tp&quot;)\n\nEstimated degrees of freedom:\n4.77 total = 5.77 \n\nlmer.REML score: 3566.762 \n</code></pre>\n<p>I would appreciate any help in interpreting all this.</p>\n<p>------ Edit ------\nIn reply to the posterior predictive check. Removal of Facet.\n<a href=\"https://i.sstatic.net/iV7wvyRj.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/iV7wvyRj.jpg\" alt=\"enter image description here\" /></a>\ntemp3 without Facet in nesting, temp4 with Facet in nesting.</p>\n<pre><code>&gt; compare_performance(temp3, temp4)\n# Comparison of Model Performance Indices\n\nName | Model | AIC (weights) | BIC (weights) | R2 | RMSE | Sigma\n-----------------------------------------------------------------------\ntemp3 | gamm4 | 4031.8 (0.475) | 4065.0 (0.484) | 0.049 | 0.572 | 0.573\ntemp4 | gamm4 | 4031.6 (0.525) | 4064.8 (0.516) | 0.049 | 0.274 | 0.275\n</code></pre>\n<p>------ quick edit ------\nSo, yes, when I check <code>$mer</code> I get these results, and it appears to be(?), the missing &quot;components&quot; to complete the response?:</p>\n<pre><code>&gt; model_performance(temp3$mer)\n# Indices of model performance\n\nAIC | AICc | BIC | R2 (cond.) | R2 (marg.) | ICC | RMSE | Sigma\n--------------------------------------------------------------------------\n3581.9 | 3582.0 | 3618.9 | 0.579 | 1.298e-04 | 0.579 | 0.572 | 0.660\n\n&gt; icc(temp3$mer, by_group = TRUE)\n\nGroup | ICC\n--------------------------------\nToothNoLR:Specimen:taxon | 0.127\nSpecimen:taxon | 0.267\ntaxon | 0.185\n&gt; check_model(temp3$mer)\n</code></pre>\n<p>Just the lmer component predictive curve.\n<a href=\"https://i.sstatic.net/H3mCUZgO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/H3mCUZgO.jpg\" alt=\"enter image description here\" /></a></p>\n<p><code>&gt; check_model(temp3)</code> Throws an error, so it seems it is incapable of incorporating both <code>$mer</code> and <code>$gam</code> into the check.</p>\n", "question_id": 676893, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I have ~1400 measurements of teeth from ~40 species (taxon) that go back in time ~35mya (Age).\nThe data is noisy, so there is repetition in measurements from specimens that requires nesting as a random effect.\n\n\n\n\nI wish to see if there are trends in this data through time. I can see the trends as individual taxon boxplots if I roughly order them by time, but I would highly prefer Age as a continuous variable and the repetition accounted for.\n\n\n\n\nThe problem is that taxa (i.e. species) generally exist for 1my or less, and there are large gaps, so if I understand gamms properly (not a given here lol) then the smoothing splines will be (in my simple terms) trying to extrapolate/estimate the curves for a species across the entire dataset where they don't really exist. I have tried to compensate for this using factor smoothing for taxon.\n\n\n\n\nTo cut to the point after much testing and fiddling, I came up with this:\n\n\n\n\ntemp3 <- gamm4(Asfc ~ s(Age, k = 8, bs = \"tp\") + s(Age, taxon, bs = \"fs\", k = 3), data = df, random = ~(1|taxon/Specimen/To/Fa))\ntemp4 <- gamm4(Asfc ~ s(Age, k = 8, bs = \"tp\") + s(Age, taxon, bs = \"fs\", k = 3), data = df, random = ~(1|Specimen/To/Fa))\ndraw(temp3$gam, residuals = TRUE)\n\n\n\n\n\nAnd I get something like this:\n[image: gamm4 plot; source: https://i.sstatic.net/M6wP2hpB.jpg] (https://i.sstatic.net/M6wP2hpB.jpg)\n\n\n\n\nFor this data am I \"gamm-ing\" correctly? The second plot suggests errr no, or is that just the intercept and slope for taxon influence?\n\n\n\n\nShould taxon be in the random effect structure? There are many specimens of each taxon.\n\n\n\n\nAs an aside, how do I only plot the first plot?\n\n\n\n\n------ Edit for clarification from questions (and comments) below ------\n\n\n\n\nEach measurement is in this example a \"complexity\" value of a single facet (Fa has four levels), from a tooth (To has 8 levels). There are 1 to 8 measurements per Specimen requiring it to be a random effect. Each Specimen does belong to a species, though Species may or may not require nesting, or inclusion in the model per se, since most species have a single value for age, or are spread over 0.5 million years at most, it is highly correlated to Age and may be superfluous. Asfc is continuous, well normalised, and is considered gaussian.\n\n\n\n\nThis is an updated model with model check based on comments : gamm4(Asfc ~ s(sqrtAge, k = 8, bs =\"tp\"), data = df, random = ~(1|Specimen/ToothNoLR/Facet))\n[image: newGamm; source: https://i.sstatic.net/UmccNppE.jpg] (https://i.sstatic.net/UmccNppE.jpg)\n\n\n\n\n[image: checkgamm; source: https://i.sstatic.net/gYiJQdTI.jpg] (https://i.sstatic.net/gYiJQdTI.jpg)\n\n\n\n\nRE check_model() I'm doing this to look for verifiable trends, not for prediction. I realise the large gaps would make the latter difficult, so this is more exploratory to see if a signal is present.\n\n\n\n\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3606.394\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen (Intercept) 0.4767 \n ToothNoLR:Specimen (Intercept) 0.3814 \n Specimen (Intercept) 0.6024 \n Xr s(sqrt(Age)) 7.7972 \n Residual 0.4563 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen, 1430; ToothNoLR:Specimen, 542; Specimen, 421; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n 0.008243 -0.872465 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n5.56 total = 6.56 \n\nlmer.REML score: 3606.394 \n\nattr(,\"class\")\n[1] \"gamm4\" \"list\" \n\n\n\n\n\n------ 2nd edit updating random effect structure ------\nHere is the model with taxon added. The CI's are worse, but I suspect it is a \"truer\" model. gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n\n\n\n\n[image: REtaxonadded; source: https://i.sstatic.net/KnHUkWbG.jpg] (https://i.sstatic.net/KnHUkWbG.jpg)\n\n\n\n\nThe check shows a more even spread of residuals.\n\n\n\n\n[image: retaxoncheck; source: https://i.sstatic.net/IXmEOkWk.jpg] (https://i.sstatic.net/IXmEOkWk.jpg)\n\n\n\n\nThese are the new results.\n\n\n\n\n> temp3 <- gamm4(Asfc ~ s(sqrt(Age), k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.052\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4786 \n ToothNoLR:Specimen:taxon (Intercept) 0.3614 \n Specimen:taxon (Intercept) 0.5246 \n taxon (Intercept) 0.4379 \n Xr s(sqrt(Age)) 4.5753 \n Residual 0.4561 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n -0.04013 -0.01014 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n4.3 total = 5.3 \n\nlmer.REML score: 3566.053\n\n\n\n\n\nCompare them to the results where Age is not sqrt()'ed\n\n\n\n\n> temp3 <- gamm4(Asfc ~ s(Age, k = 8, bs =\"tp\"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.762\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4651 \n ToothNoLR:Specimen:taxon (Intercept) 0.3611 \n Specimen:taxon (Intercept) 0.5317 \n taxon (Intercept) 0.3790 \n Xr s(Age) 7.4438 \n Residual 0.4692 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\nX(Intercept) Xs(Age)Fx1 \n -0.04286 -0.98535 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(Age, k = 8, bs = \"tp\")\n\nEstimated degrees of freedom:\n4.77 total = 5.77 \n\nlmer.REML score: 3566.762 \n\n\n\n\n\nI would appreciate any help in interpreting all this.\n\n\n\n\n------ Edit ------\nIn reply to the posterior predictive check. Removal of Facet.\n[image: enter image description here; source: https://i.sstatic.net/iV7wvyRj.jpg] (https://i.sstatic.net/iV7wvyRj.jpg)\ntemp3 without Facet in nesting, temp4 with Facet in nesting.\n\n\n\n\n> compare_performance(temp3, temp4)\n# Comparison of Model Performance Indices\n\nName | Model | AIC (weights) | BIC (weights) | R2 | RMSE | Sigma\n-----------------------------------------------------------------------\ntemp3 | gamm4 | 4031.8 (0.475) | 4065.0 (0.484) | 0.049 | 0.572 | 0.573\ntemp4 | gamm4 | 4031.6 (0.525) | 4064.8 (0.516) | 0.049 | 0.274 | 0.275\n\n\n\n\n\n------ quick edit ------\nSo, yes, when I check $mer I get these results, and it appears to be(?), the missing \"components\" to complete the response?:\n\n\n\n\n> model_performance(temp3$mer)\n# Indices of model performance\n\nAIC | AICc | BIC | R2 (cond.) | R2 (marg.) | ICC | RMSE | Sigma\n--------------------------------------------------------------------------\n3581.9 | 3582.0 | 3618.9 | 0.579 | 1.298e-04 | 0.579 | 0.572 | 0.660\n\n> icc(temp3$mer, by_group = TRUE)\n\nGroup | ICC\n--------------------------------\nToothNoLR:Specimen:taxon | 0.127\nSpecimen:taxon | 0.267\ntaxon | 0.185\n> check_model(temp3$mer)\n\n\n\n\n\nJust the lmer component predictive curve.\n[image: enter image description here; source: https://i.sstatic.net/H3mCUZgO.jpg] (https://i.sstatic.net/H3mCUZgO.jpg)\n\n\n\n\n> check_model(temp3) Throws an error, so it seems it is incapable of incorporating both $mer and $gam into the check.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MrSwaggins", "profile_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "user_type": "registered"}, "created_at": "2026-08-17T05:08:58+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "47586972-AD7B-40E3-B14E-9C6D7A77FE0E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/47586972-AD7B-40E3-B14E-9C6D7A77FE0E/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-17T19:27:20+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "BCF98811-131E-4543-9FE5-CF416E78ABB8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/BCF98811-131E-4543-9FE5-CF416E78ABB8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MrSwaggins", "profile_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "user_type": "registered"}, "created_at": "2026-08-18T09:40:10+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "8F665663-5EBD-4CA8-91C8-1904B3B19560", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/8F665663-5EBD-4CA8-91C8-1904B3B19560/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MrSwaggins", "profile_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "user_type": "registered"}, "created_at": "2026-08-19T05:12:30+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "E76ADF52-89E5-43C8-9481-7B5A889ABCD7", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E76ADF52-89E5-43C8-9481-7B5A889ABCD7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MrSwaggins", "profile_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "user_type": "registered"}, "created_at": "2026-08-21T00:40:31+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "6617B7F1-6315-4F02-8A26-A7052F54E477", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/6617B7F1-6315-4F02-8A26-A7052F54E477/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MrSwaggins", "profile_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "user_type": "registered"}, "created_at": "2026-08-21T00:47:14+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "74A2C20C-CFC3-4434-A619-7146386C6A20", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/74A2C20C-CFC3-4434-A619-7146386C6A20/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MrSwaggins", "profile_url": "https://stats.stackexchange.com/users/331950/mrswaggins", "user_type": "registered"}, "created_at": "2026-08-21T02:48:10+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "8D79A3B0-2AE6-4E89-94B4-B4BB66830EE2", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/8D79A3B0-2AE6-4E89-94B4-B4BB66830EE2/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676893/is-this-the-correct-specification-for-gamm4-splines-where-species-are-short-te", "split": "test", "split_group": "61409f7f49db16a90eedb3018c6f3602d4fb05c1b06859ec9e29c98cb27d345b", "tags": ["time-series", "lme4-nlme", "trend", "gamm4"], "thread_id": "stats:676893", "title": "Is this the correct specification for gamm4() splines where Species are short term, but time period is very long?"}}
{"accepted_answer": {"answer_html": "<p>As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)</p>\n<p><span class=\"math-container\">\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &amp;= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t&amp; \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}</span></p>\n<p>I guess I must have been so eager to verify the original results that I conditioned myself to &quot;see&quot; the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.</p>\n", "answer_id": 676993, "answer_text": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.", "answer_url": "https://stats.stackexchange.com/a/676993", "author": "Ettore S", "author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:08:55+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676952, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:08:55+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E33B0B4F-D54D-46E9-8E25-81C77E90B942", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:15:33+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "71D393BD-A8FB-4799-92AF-8FD04BFA27AE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}], "score": 0, "updated_at": "2026-08-28T23:15:33+00:00"}, "code_blocks": [{"block_index": 0, "code_text": " n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676952, "sha256": "fe8ee795d4c0d8f93e4394aef787c0dca0457bed49da29328a16bd289f7ec7c0", "source_url": "https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r"}], "other_answers": [], "product": "code_qa", "question": "In the context of zero-truncated negative binomial regression (see this other post (https://stats.stackexchange.com/q/676385/513606)) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper (https://www.jstor.org/stable/2096628)):\n\n\n\n\n$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$\n\n\n\n\nwhere:\n\n\n\n\n\n$y_i > 0 \\quad (i=1,2,\\dots,n)$ denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);\n\n\n\n\n$\\mathbf{x}^T_i$ is the $i$-th row of the regression data matrix;\n\n\n\n\n$\\boldsymbol{\\beta}$ is the unknown vector of regression coefficients (to be estimated);\n\n\n\n\n$\\alpha$ is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter ($\\alpha$ is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial see e.g., p.745, in this book (https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3)).\n\n\n\n\nAlso notice that the first summation is just the Hessian of the \"parent\" specification: that one works fine i.e., its elements are negative as expected.\n\n\n\n\n\nThe above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.\n\n\n\n\nMaybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, \"bound to\" have positive elements?\n\n\n\n\nI thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.\n\n\n\n\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.\n\n\n\n\nExample\n\n\n\n\nFor the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c(\"los\", \"died\", \"hmo\", \"type2\", \"type3\")] corresponds to the example reported in this STATA documentation for tnbreg (https://www.stata.com/manuals13/rtnbreg.pdf).\n\n\n\n\n\n\n\nInitialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;\n\n\n\n\n\n\n\n\n\nFollowing the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).\n\n\n\n\n\n\n\n\n\nWith X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:\n\n\n\n\n n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n\n\n\n\n\n\n\n\n\nAnd I get a positive Hessian - as I always do\n\n\n\n\n> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n\n\n\n\n\nAny thoughts? Am I missing anything trivial here? Thanks in advance.", "record_id": "Scientific-Code-and-Analysis-QA:stats:676952", "selected_answer": {"answer_html": "<p>As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)</p>\n<p><span class=\"math-container\">\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &amp;= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t&amp; \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}</span></p>\n<p>I guess I must have been so eager to verify the original results that I conditioned myself to &quot;see&quot; the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.</p>\n", "answer_id": 676993, "answer_text": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.", "answer_url": "https://stats.stackexchange.com/a/676993", "author": "Ettore S", "author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:08:55+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676952, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:08:55+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E33B0B4F-D54D-46E9-8E25-81C77E90B942", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:15:33+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "71D393BD-A8FB-4799-92AF-8FD04BFA27AE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}], "score": 0, "updated_at": "2026-08-28T23:15:33+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 676993, "answers": [{"answer_html": "<p>As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)</p>\n<p><span class=\"math-container\">\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &amp;= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t&amp; \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}</span></p>\n<p>I guess I must have been so eager to verify the original results that I conditioned myself to &quot;see&quot; the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.</p>\n", "answer_id": 676993, "answer_text": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.", "answer_url": "https://stats.stackexchange.com/a/676993", "author": "Ettore S", "author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:08:55+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676952, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:08:55+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E33B0B4F-D54D-46E9-8E25-81C77E90B942", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:15:33+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "71D393BD-A8FB-4799-92AF-8FD04BFA27AE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}], "score": 0, "updated_at": "2026-08-28T23:15:33+00:00"}], "domain": "statistics", "external_links": ["https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3", "https://www.jstor.org/stable/2096628", "https://www.stata.com/manuals13/rtnbreg.pdf"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:03.428408+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/774052c18cd9e8fa951e893347bfa3c1a85e743fc46ec4667572002cadb10cbf_1790825224163423600_0.json", "raw_sha256": "fe4dd06d3de6c0b1bb33ba88aee0ed4284118e01f76a58dcdce220a4946329b2", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Ettore S", "question_author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "question_author_user_type": "registered", "question_created_at": "2026-08-24T16:36:39+00:00", "question_html": "<p>In the context of zero-truncated negative binomial regression (see <a href=\"https://stats.stackexchange.com/q/676385/513606\">this other post</a>) , twice-differentiating the loglikelihood yields a well-known result (<a href=\"https://www.jstor.org/stable/2096628\" rel=\"nofollow noreferrer\">see e.g., footnote 5 in this paper</a>):</p>\n<p><span class=\"math-container\">$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &amp;= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t&amp; \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$</span></p>\n<p>where:</p>\n<ul>\n<li><span class=\"math-container\">$y_i &gt; 0 \\quad (i=1,2,\\dots,n)$</span> denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);</li>\n<li><span class=\"math-container\">$\\mathbf{x}^T_i$</span> is the <span class=\"math-container\">$i$</span>-th row of the regression data matrix;</li>\n<li><span class=\"math-container\">$\\boldsymbol{\\beta}$</span> is the unknown vector of regression coefficients (to be estimated);</li>\n<li><span class=\"math-container\">$\\alpha$</span> is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter (<span class=\"math-container\">$\\alpha$</span> is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial <a href=\"https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3\" rel=\"nofollow noreferrer\">see e.g., p.745, in this book</a>).</li>\n<li>Also notice that the first summation is just the Hessian of the &quot;parent&quot; specification: that one works fine i.e., its elements are negative as expected.</li>\n</ul>\n<p>The above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an <em>Hessian with positive elements</em>.</p>\n<p>Maybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, &quot;bound to&quot; have positive elements?</p>\n<p>I thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.</p>\n<p>I appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.</p>\n<h2>Example</h2>\n<p>For the sake of illustration, consider <code>data(medpar)</code> available from the <code>R</code> package <code>COUNT</code>. The data subset <code>data_medpar &lt;- medpar[,c(&quot;los&quot;, &quot;died&quot;, &quot;hmo&quot;, &quot;type2&quot;, &quot;type3&quot;)]</code> corresponds to the example reported in <a href=\"https://www.stata.com/manuals13/rtnbreg.pdf\" rel=\"nofollow noreferrer\">this STATA documentation for tnbreg</a>.</p>\n<ul>\n<li><p>Initialising the regression coefficients with a zero-truncated Poisson model gives me (<code>intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750</code>) -- call this vector <code>beta_iter</code>;</p>\n</li>\n<li><p>Following the alternating method of <code>glm.nb</code> from package <code>MASS</code> I also obtain an initial guess for <span class=\"math-container\">$\\alpha$</span>, call this scalar <code>p_alpha &lt;- 1.903</code> (what STATA calls alpha in the document is the recirpocal <span class=\"math-container\">$\\theta=\\alpha^{-1}=0.525$</span> i.e. the so-called dispersion parameter).</p>\n</li>\n<li><p>With <code>X</code> the data matrix (including the intercept) and <code>y</code> the response variable vector corresponding to <code>los</code> I plug <code>p_lambda = exp(X %*% beta_iter)</code> and <code>p_alpha</code> in my <code>R</code> implementation below - which I believe should correspond to the second derivatives in question:</p>\n<pre><code> n_regressors &lt;- ncol(X)\n n_observ &lt;- nrow(X)\n phi_sub &lt;- (1 + p_theta*p_lambda)\n H_parent &lt;- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a &lt;- (1 / (phi_sub)^(1+p_alpha))\n phi &lt;- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A &lt;- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B &lt;- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter &lt;- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x &lt;- X[i,]\n x &lt;- as.numeric(x)\n outprod_X &lt;- (x %o% x) \n A &lt;- H_parent[i]\n if(zerotrunc){\n B &lt;- H_zt_A[i]\n C &lt;- H_zt_B[i]\n } else {\n B &lt;- C &lt;- 0\n }\n Hessian_iter &lt;- Hessian_iter - ( A - B + C )*outprod_X \n }\n</code></pre>\n</li>\n</ul>\n<p>And I get a positive Hessian - as I always do</p>\n<pre><code>&gt; Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n</code></pre>\n<p>Any thoughts? Am I missing anything trivial here? Thanks in advance.</p>\n", "question_id": 676952, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "In the context of zero-truncated negative binomial regression (see this other post (https://stats.stackexchange.com/q/676385/513606)) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper (https://www.jstor.org/stable/2096628)):\n\n\n\n\n$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$\n\n\n\n\nwhere:\n\n\n\n\n\n$y_i > 0 \\quad (i=1,2,\\dots,n)$ denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);\n\n\n\n\n$\\mathbf{x}^T_i$ is the $i$-th row of the regression data matrix;\n\n\n\n\n$\\boldsymbol{\\beta}$ is the unknown vector of regression coefficients (to be estimated);\n\n\n\n\n$\\alpha$ is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter ($\\alpha$ is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial see e.g., p.745, in this book (https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3)).\n\n\n\n\nAlso notice that the first summation is just the Hessian of the \"parent\" specification: that one works fine i.e., its elements are negative as expected.\n\n\n\n\n\nThe above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.\n\n\n\n\nMaybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, \"bound to\" have positive elements?\n\n\n\n\nI thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.\n\n\n\n\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.\n\n\n\n\nExample\n\n\n\n\nFor the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c(\"los\", \"died\", \"hmo\", \"type2\", \"type3\")] corresponds to the example reported in this STATA documentation for tnbreg (https://www.stata.com/manuals13/rtnbreg.pdf).\n\n\n\n\n\n\n\nInitialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;\n\n\n\n\n\n\n\n\n\nFollowing the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).\n\n\n\n\n\n\n\n\n\nWith X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:\n\n\n\n\n n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n\n\n\n\n\n\n\n\n\nAnd I get a positive Hessian - as I always do\n\n\n\n\n> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n\n\n\n\n\nAny thoughts? Am I missing anything trivial here? Thanks in advance.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-24T16:36:39+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "07E45709-2DC4-449E-9EF1-F194BCC37017", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/07E45709-2DC4-449E-9EF1-F194BCC37017/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-24T16:44:54+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "62966E35-E17B-49AB-8C07-589F8E1C8272", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/62966E35-E17B-49AB-8C07-589F8E1C8272/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r", "split": "test", "split_group": "7b59a2f46aa3d8cb6ef7b86f03502a2ea8a90a231427a0a51d2360f8ed2dd472", "tags": ["nonlinear-regression", "count-data", "negative-binomial-distribution", "hessian", "truncated-distributions"], "thread_id": "stats:676952", "title": "Hessian with invariably positive elements for zero-truncated negative binomial regression"}}
{"accepted_answer": {"answer_html": "<p>The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.</p>\n<p>My <code>fit_mle</code> function is inspired by <code>Rfast::betabinom.mle</code>, adapted to handle edge cases.</p>\n<pre class=\"lang-r prettyprint-override\"><code>fit_mle &lt;- function(x, k) {\n m1 &lt;- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n V &lt;- NA\n } else {\n n &lt;- length(x)\n z1 &lt;- sort(unique(x))\n n1 &lt;- tabulate(match(x, z1))\n z2 &lt;- sort(unique(k - x))\n n2 &lt;- tabulate(match(k - x, z2))\n m2 &lt;- mean(x^2)\n d &lt;- 1/(k*(m2/m1 - m1) - k + m1)\n a &lt;- (k*m1 - m2)*d\n b &lt;- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d &lt; 0) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n } else if (a &lt;= 0 || b &lt;= 0) {\n a &lt;- max(m1*0.1/k, 1e-5)\n b &lt;- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab &lt;- a + b\n t1 &lt;- digamma(ab) - digamma(k + ab)\n S1 &lt;- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 &lt;- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 &lt;- trigamma(ab) - trigamma(k + ab)\n J11 &lt;- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 &lt;- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 &lt;- a*b*t2*n\n if (abs(detJ &lt;- J11*J22 - J12^2) &lt; 1e-12) break\n step1 &lt;- (J22*S1 - J12*S2)/detJ\n step2 &lt;- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) &lt; 1e-8) break\n step_norm &lt;- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm &lt; 1) {\n step1 &lt;- step1*step_norm\n step2 &lt;- step2*step_norm\n }\n \n a &lt;- a*exp(-step1)\n b &lt;- b*exp(-step2)\n }\n \n g &lt;- a*b/(a + b)^2\n V &lt;- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp; V &lt; 1 / (4 * n)) V else NA)\n}\n</code></pre>\n<p><a href=\"https://i.sstatic.net/yrEHvkk0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/yrEHvkk0.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.sstatic.net/9nEiiFBK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/9nEiiFBK.png\" alt=\"enter image description here\" /></a></p>\n<p>Full code:</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(MASS)\n\nz &lt;- qnorm(0.975)\n\n## Simulate \nmu_true &lt;- 0.5\nv_true &lt;- 0.249\nn_vals &lt;- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals &lt;- c(1, 2, 3, 4, 5, 6,7,8,9)\nR &lt;- 1000\n\n\nsim_data &lt;- function(n, k, mu, v) {\n nu &lt;- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle &lt;- function(x, k) {\n xx &lt;&lt;- x\n kk &lt;&lt;- k\n m1 &lt;- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n V &lt;- NA\n } else {\n n &lt;- length(x)\n z1 &lt;- sort(unique(x))\n n1 &lt;- tabulate(match(x, z1))\n z2 &lt;- sort(unique(k - x))\n n2 &lt;- tabulate(match(k - x, z2))\n m2 &lt;- mean(x^2)\n d &lt;- 1/(k*(m2/m1 - m1) - k + m1)\n a &lt;- (k*m1 - m2)*d\n b &lt;- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d &lt; 0) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n } else if (a &lt;= 0 || b &lt;= 0) {\n a &lt;- max(m1*0.1/k, 1e-5)\n b &lt;- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab &lt;- a + b\n t1 &lt;- digamma(ab) - digamma(k + ab)\n S1 &lt;- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 &lt;- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 &lt;- trigamma(ab) - trigamma(k + ab)\n J11 &lt;- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 &lt;- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 &lt;- a*b*t2*n\n if (abs(detJ &lt;- J11*J22 - J12^2) &lt; 1e-12) break\n step1 &lt;- (J22*S1 - J12*S2)/detJ\n step2 &lt;- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) &lt; 1e-8) break\n step_norm &lt;- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm &lt; 1) {\n step1 &lt;- step1*step_norm\n step2 &lt;- step2*step_norm\n }\n \n a &lt;- a*exp(-step1)\n b &lt;- b*exp(-step2)\n }\n \n g &lt;- a*b/(a + b)^2\n V &lt;- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp; V &lt; 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom &lt;- function(x, k) {\n p &lt;- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore &lt;- function(m, V, mu) {\n s &lt;- sqrt(V); ok &lt;- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) &lt;= z * s, na.rm = TRUE))\n}\n\nrun_cell &lt;- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(&quot;[%2d/%2d] n = %3d, k = %d ... &quot;, i, tot, n, k))\n e &lt;- replicate(R, { x &lt;- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(&quot;done (%.1fs elapsed)\\n&quot;,\n as.numeric(difftime(Sys.time(), t0, units = &quot;secs&quot;))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(&quot;moments&quot;, &quot;mle&quot;),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 &lt;- Sys.time()\ng &lt;- expand.grid(n = n_vals, k = k_vals)\nres &lt;- do.call(rbind, Map(run_cell, mu_true, v_true, g<span class=\"math-container\">$n, g$</span>k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df &lt;- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols &lt;- c(&quot;true_mean&quot;, &quot;true_variance&quot;, &quot;n&quot;, &quot;k&quot;, &quot;true_var_of_mean&quot;, \n &quot;mean_estimate&quot;, &quot;bias&quot;, &quot;mc_se&quot;, &quot;sd_estimate&quot;, \n &quot;variance_estimate&quot;, &quot;length_of_interval&quot;, &quot;coverage&quot;)\nres_df[num_cols] &lt;- lapply(res_df[num_cols], as.numeric)\nres_df<span class=\"math-container\">$k_factor &lt;- as.factor(res_df$</span>k)\n\ndf_mom &lt;- subset(res_df, method == &quot;moments&quot;)\ndf_mle &lt;- subset(res_df, method == &quot;mle&quot;)\n\n# Helper function to generate the panels\nmake_panel &lt;- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p &lt;- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = &quot;n&quot;, y = y_label, color = &quot;k&quot;) +\n theme_bw() +\n theme(legend.position = &quot;bottom&quot;,\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p &lt;- p + geom_hline(yintercept = hline, linetype = &quot;dashed&quot;, linewidth = 0.5)\n }\n return(p)\n}\n\np1 &lt;- make_panel(df_mom, &quot;bias&quot;, &quot;Moments: bias of the estimated mean&quot;, \n &quot;Average estimate minus the truth. Dashed line at 0.&quot;, &quot;bias&quot;, 0)\np2 &lt;- make_panel(df_mle, &quot;bias&quot;, &quot;MLE: bias of the estimated mean&quot;, \n &quot;Average estimate minus the truth. Dashed line at 0.&quot;, &quot;bias&quot;, 0)\np3 &lt;- make_panel(df_mom, &quot;sd_estimate&quot;, &quot;Moments: SD of the estimated mean&quot;, \n &quot;Spread of the estimate across studies.&quot;, &quot;SD&quot;)\np4 &lt;- make_panel(df_mle, &quot;sd_estimate&quot;, &quot;MLE: SD of the estimated mean&quot;, \n &quot;Spread of the estimate across studies.&quot;, &quot;SD&quot;)\n\n# Combine using patchwork\ncombined_grid &lt;- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov &lt;- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = &quot;dashed&quot;) +\n facet_grid(~ k, labeller = label_both) +\n labs(title = &quot;Coverage of the nominal 95% interval&quot;,\n subtitle = &quot;Share of 1000 intervals containing the true mean. Dashed line at 0.95.&quot;,\n x = &quot;n&quot;,\n y = &quot;coverage&quot;,\n color = &quot;method&quot;) +\n theme_bw() +\n theme(legend.position = &quot;bottom&quot;,\n strip.background = element_rect(fill = &quot;grey90&quot;))\n\nprint(p_cov)\n</code></pre>\n", "answer_id": 677117, "answer_text": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)", "answer_url": "https://stats.stackexchange.com/a/677117", "author": "jblood94", "author_url": "https://stats.stackexchange.com/users/214015/jblood94", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-09T13:02:57+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677094, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jblood94", "profile_url": "https://stats.stackexchange.com/users/214015/jblood94", "user_type": "registered"}, "created_at": "2026-09-09T13:02:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "09E52470-6B69-4568-A8B3-D52476EA341B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "20C3E36B-1564-462F-9257-5BBE5B9B70EF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}], "score": 3, "updated_at": "2026-09-09T13:02:57+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677094, "sha256": "748b8957c64ad9c882e5131628ded56e236fa132e526ea16319627b14f44d2e8", "source_url": "https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases"}, {"block_index": 0, "code_text": "fit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677117, "sha256": "51cc539111e4e5bb9577cca7f1743154014577b6d727c2354ce8054c03f21b29", "source_url": "https://stats.stackexchange.com/a/677117"}, {"block_index": 1, "code_text": "library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677117, "sha256": "b749e1889b6f66b0bc1acd992da72507b9cf5e17536a32c9b5d036efb773fd2a", "source_url": "https://stats.stackexchange.com/a/677117"}], "other_answers": [], "product": "code_qa", "question": "Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):\n\n\n\n\n$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$\n\n\n\n\n$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$\n\n\n\n\n$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$\n\n\n\n\nFor a single unit,\n\n\n\n\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\nand\n\n\n\n\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$\n\n\n\n\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).\n\n\n\n\nThe first way is with moments (I can show the manipulations if needed):\n\n\n\n\n$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$\n\n\n\n\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\n$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$\n\n\n\n\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).\n\n\n\n\nHere is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\n\n\n\n\nHere are the results:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/kEDelnub.png] (https://i.sstatic.net/kEDelnub.png)\n[image: enter image description here; source: https://i.sstatic.net/H3ywscwO.png] (https://i.sstatic.net/H3ywscwO.png)\n\n\n\n\nPrior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).\n\n\n\n\nWhy is this happening?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677094", "selected_answer": {"answer_html": "<p>The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.</p>\n<p>My <code>fit_mle</code> function is inspired by <code>Rfast::betabinom.mle</code>, adapted to handle edge cases.</p>\n<pre class=\"lang-r prettyprint-override\"><code>fit_mle &lt;- function(x, k) {\n m1 &lt;- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n V &lt;- NA\n } else {\n n &lt;- length(x)\n z1 &lt;- sort(unique(x))\n n1 &lt;- tabulate(match(x, z1))\n z2 &lt;- sort(unique(k - x))\n n2 &lt;- tabulate(match(k - x, z2))\n m2 &lt;- mean(x^2)\n d &lt;- 1/(k*(m2/m1 - m1) - k + m1)\n a &lt;- (k*m1 - m2)*d\n b &lt;- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d &lt; 0) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n } else if (a &lt;= 0 || b &lt;= 0) {\n a &lt;- max(m1*0.1/k, 1e-5)\n b &lt;- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab &lt;- a + b\n t1 &lt;- digamma(ab) - digamma(k + ab)\n S1 &lt;- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 &lt;- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 &lt;- trigamma(ab) - trigamma(k + ab)\n J11 &lt;- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 &lt;- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 &lt;- a*b*t2*n\n if (abs(detJ &lt;- J11*J22 - J12^2) &lt; 1e-12) break\n step1 &lt;- (J22*S1 - J12*S2)/detJ\n step2 &lt;- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) &lt; 1e-8) break\n step_norm &lt;- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm &lt; 1) {\n step1 &lt;- step1*step_norm\n step2 &lt;- step2*step_norm\n }\n \n a &lt;- a*exp(-step1)\n b &lt;- b*exp(-step2)\n }\n \n g &lt;- a*b/(a + b)^2\n V &lt;- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp; V &lt; 1 / (4 * n)) V else NA)\n}\n</code></pre>\n<p><a href=\"https://i.sstatic.net/yrEHvkk0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/yrEHvkk0.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.sstatic.net/9nEiiFBK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/9nEiiFBK.png\" alt=\"enter image description here\" /></a></p>\n<p>Full code:</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(MASS)\n\nz &lt;- qnorm(0.975)\n\n## Simulate \nmu_true &lt;- 0.5\nv_true &lt;- 0.249\nn_vals &lt;- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals &lt;- c(1, 2, 3, 4, 5, 6,7,8,9)\nR &lt;- 1000\n\n\nsim_data &lt;- function(n, k, mu, v) {\n nu &lt;- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle &lt;- function(x, k) {\n xx &lt;&lt;- x\n kk &lt;&lt;- k\n m1 &lt;- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n V &lt;- NA\n } else {\n n &lt;- length(x)\n z1 &lt;- sort(unique(x))\n n1 &lt;- tabulate(match(x, z1))\n z2 &lt;- sort(unique(k - x))\n n2 &lt;- tabulate(match(k - x, z2))\n m2 &lt;- mean(x^2)\n d &lt;- 1/(k*(m2/m1 - m1) - k + m1)\n a &lt;- (k*m1 - m2)*d\n b &lt;- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d &lt; 0) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n } else if (a &lt;= 0 || b &lt;= 0) {\n a &lt;- max(m1*0.1/k, 1e-5)\n b &lt;- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab &lt;- a + b\n t1 &lt;- digamma(ab) - digamma(k + ab)\n S1 &lt;- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 &lt;- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 &lt;- trigamma(ab) - trigamma(k + ab)\n J11 &lt;- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 &lt;- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 &lt;- a*b*t2*n\n if (abs(detJ &lt;- J11*J22 - J12^2) &lt; 1e-12) break\n step1 &lt;- (J22*S1 - J12*S2)/detJ\n step2 &lt;- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) &lt; 1e-8) break\n step_norm &lt;- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm &lt; 1) {\n step1 &lt;- step1*step_norm\n step2 &lt;- step2*step_norm\n }\n \n a &lt;- a*exp(-step1)\n b &lt;- b*exp(-step2)\n }\n \n g &lt;- a*b/(a + b)^2\n V &lt;- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp; V &lt; 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom &lt;- function(x, k) {\n p &lt;- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore &lt;- function(m, V, mu) {\n s &lt;- sqrt(V); ok &lt;- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) &lt;= z * s, na.rm = TRUE))\n}\n\nrun_cell &lt;- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(&quot;[%2d/%2d] n = %3d, k = %d ... &quot;, i, tot, n, k))\n e &lt;- replicate(R, { x &lt;- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(&quot;done (%.1fs elapsed)\\n&quot;,\n as.numeric(difftime(Sys.time(), t0, units = &quot;secs&quot;))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(&quot;moments&quot;, &quot;mle&quot;),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 &lt;- Sys.time()\ng &lt;- expand.grid(n = n_vals, k = k_vals)\nres &lt;- do.call(rbind, Map(run_cell, mu_true, v_true, g<span class=\"math-container\">$n, g$</span>k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df &lt;- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols &lt;- c(&quot;true_mean&quot;, &quot;true_variance&quot;, &quot;n&quot;, &quot;k&quot;, &quot;true_var_of_mean&quot;, \n &quot;mean_estimate&quot;, &quot;bias&quot;, &quot;mc_se&quot;, &quot;sd_estimate&quot;, \n &quot;variance_estimate&quot;, &quot;length_of_interval&quot;, &quot;coverage&quot;)\nres_df[num_cols] &lt;- lapply(res_df[num_cols], as.numeric)\nres_df<span class=\"math-container\">$k_factor &lt;- as.factor(res_df$</span>k)\n\ndf_mom &lt;- subset(res_df, method == &quot;moments&quot;)\ndf_mle &lt;- subset(res_df, method == &quot;mle&quot;)\n\n# Helper function to generate the panels\nmake_panel &lt;- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p &lt;- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = &quot;n&quot;, y = y_label, color = &quot;k&quot;) +\n theme_bw() +\n theme(legend.position = &quot;bottom&quot;,\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p &lt;- p + geom_hline(yintercept = hline, linetype = &quot;dashed&quot;, linewidth = 0.5)\n }\n return(p)\n}\n\np1 &lt;- make_panel(df_mom, &quot;bias&quot;, &quot;Moments: bias of the estimated mean&quot;, \n &quot;Average estimate minus the truth. Dashed line at 0.&quot;, &quot;bias&quot;, 0)\np2 &lt;- make_panel(df_mle, &quot;bias&quot;, &quot;MLE: bias of the estimated mean&quot;, \n &quot;Average estimate minus the truth. Dashed line at 0.&quot;, &quot;bias&quot;, 0)\np3 &lt;- make_panel(df_mom, &quot;sd_estimate&quot;, &quot;Moments: SD of the estimated mean&quot;, \n &quot;Spread of the estimate across studies.&quot;, &quot;SD&quot;)\np4 &lt;- make_panel(df_mle, &quot;sd_estimate&quot;, &quot;MLE: SD of the estimated mean&quot;, \n &quot;Spread of the estimate across studies.&quot;, &quot;SD&quot;)\n\n# Combine using patchwork\ncombined_grid &lt;- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov &lt;- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = &quot;dashed&quot;) +\n facet_grid(~ k, labeller = label_both) +\n labs(title = &quot;Coverage of the nominal 95% interval&quot;,\n subtitle = &quot;Share of 1000 intervals containing the true mean. Dashed line at 0.95.&quot;,\n x = &quot;n&quot;,\n y = &quot;coverage&quot;,\n color = &quot;method&quot;) +\n theme_bw() +\n theme(legend.position = &quot;bottom&quot;,\n strip.background = element_rect(fill = &quot;grey90&quot;))\n\nprint(p_cov)\n</code></pre>\n", "answer_id": 677117, "answer_text": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)", "answer_url": "https://stats.stackexchange.com/a/677117", "author": "jblood94", "author_url": "https://stats.stackexchange.com/users/214015/jblood94", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-09T13:02:57+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677094, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jblood94", "profile_url": "https://stats.stackexchange.com/users/214015/jblood94", "user_type": "registered"}, "created_at": "2026-09-09T13:02:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "09E52470-6B69-4568-A8B3-D52476EA341B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "20C3E36B-1564-462F-9257-5BBE5B9B70EF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}], "score": 3, "updated_at": "2026-09-09T13:02:57+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 677117, "answers": [{"answer_html": "<p>The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.</p>\n<p>My <code>fit_mle</code> function is inspired by <code>Rfast::betabinom.mle</code>, adapted to handle edge cases.</p>\n<pre class=\"lang-r prettyprint-override\"><code>fit_mle &lt;- function(x, k) {\n m1 &lt;- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n V &lt;- NA\n } else {\n n &lt;- length(x)\n z1 &lt;- sort(unique(x))\n n1 &lt;- tabulate(match(x, z1))\n z2 &lt;- sort(unique(k - x))\n n2 &lt;- tabulate(match(k - x, z2))\n m2 &lt;- mean(x^2)\n d &lt;- 1/(k*(m2/m1 - m1) - k + m1)\n a &lt;- (k*m1 - m2)*d\n b &lt;- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d &lt; 0) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n } else if (a &lt;= 0 || b &lt;= 0) {\n a &lt;- max(m1*0.1/k, 1e-5)\n b &lt;- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab &lt;- a + b\n t1 &lt;- digamma(ab) - digamma(k + ab)\n S1 &lt;- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 &lt;- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 &lt;- trigamma(ab) - trigamma(k + ab)\n J11 &lt;- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 &lt;- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 &lt;- a*b*t2*n\n if (abs(detJ &lt;- J11*J22 - J12^2) &lt; 1e-12) break\n step1 &lt;- (J22*S1 - J12*S2)/detJ\n step2 &lt;- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) &lt; 1e-8) break\n step_norm &lt;- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm &lt; 1) {\n step1 &lt;- step1*step_norm\n step2 &lt;- step2*step_norm\n }\n \n a &lt;- a*exp(-step1)\n b &lt;- b*exp(-step2)\n }\n \n g &lt;- a*b/(a + b)^2\n V &lt;- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp; V &lt; 1 / (4 * n)) V else NA)\n}\n</code></pre>\n<p><a href=\"https://i.sstatic.net/yrEHvkk0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/yrEHvkk0.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.sstatic.net/9nEiiFBK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/9nEiiFBK.png\" alt=\"enter image description here\" /></a></p>\n<p>Full code:</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(MASS)\n\nz &lt;- qnorm(0.975)\n\n## Simulate \nmu_true &lt;- 0.5\nv_true &lt;- 0.249\nn_vals &lt;- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals &lt;- c(1, 2, 3, 4, 5, 6,7,8,9)\nR &lt;- 1000\n\n\nsim_data &lt;- function(n, k, mu, v) {\n nu &lt;- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle &lt;- function(x, k) {\n xx &lt;&lt;- x\n kk &lt;&lt;- k\n m1 &lt;- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n V &lt;- NA\n } else {\n n &lt;- length(x)\n z1 &lt;- sort(unique(x))\n n1 &lt;- tabulate(match(x, z1))\n z2 &lt;- sort(unique(k - x))\n n2 &lt;- tabulate(match(k - x, z2))\n m2 &lt;- mean(x^2)\n d &lt;- 1/(k*(m2/m1 - m1) - k + m1)\n a &lt;- (k*m1 - m2)*d\n b &lt;- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d &lt; 0) {\n a &lt;- max(m1*100/k, 1e-5)\n b &lt;- max(100 - a, 1e-5)\n } else if (a &lt;= 0 || b &lt;= 0) {\n a &lt;- max(m1*0.1/k, 1e-5)\n b &lt;- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab &lt;- a + b\n t1 &lt;- digamma(ab) - digamma(k + ab)\n S1 &lt;- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 &lt;- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 &lt;- trigamma(ab) - trigamma(k + ab)\n J11 &lt;- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 &lt;- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 &lt;- a*b*t2*n\n if (abs(detJ &lt;- J11*J22 - J12^2) &lt; 1e-12) break\n step1 &lt;- (J22*S1 - J12*S2)/detJ\n step2 &lt;- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) &lt; 1e-8) break\n step_norm &lt;- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm &lt; 1) {\n step1 &lt;- step1*step_norm\n step2 &lt;- step2*step_norm\n }\n \n a &lt;- a*exp(-step1)\n b &lt;- b*exp(-step2)\n }\n \n g &lt;- a*b/(a + b)^2\n V &lt;- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp; V &lt; 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom &lt;- function(x, k) {\n p &lt;- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore &lt;- function(m, V, mu) {\n s &lt;- sqrt(V); ok &lt;- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) &lt;= z * s, na.rm = TRUE))\n}\n\nrun_cell &lt;- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(&quot;[%2d/%2d] n = %3d, k = %d ... &quot;, i, tot, n, k))\n e &lt;- replicate(R, { x &lt;- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(&quot;done (%.1fs elapsed)\\n&quot;,\n as.numeric(difftime(Sys.time(), t0, units = &quot;secs&quot;))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(&quot;moments&quot;, &quot;mle&quot;),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 &lt;- Sys.time()\ng &lt;- expand.grid(n = n_vals, k = k_vals)\nres &lt;- do.call(rbind, Map(run_cell, mu_true, v_true, g<span class=\"math-container\">$n, g$</span>k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df &lt;- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols &lt;- c(&quot;true_mean&quot;, &quot;true_variance&quot;, &quot;n&quot;, &quot;k&quot;, &quot;true_var_of_mean&quot;, \n &quot;mean_estimate&quot;, &quot;bias&quot;, &quot;mc_se&quot;, &quot;sd_estimate&quot;, \n &quot;variance_estimate&quot;, &quot;length_of_interval&quot;, &quot;coverage&quot;)\nres_df[num_cols] &lt;- lapply(res_df[num_cols], as.numeric)\nres_df<span class=\"math-container\">$k_factor &lt;- as.factor(res_df$</span>k)\n\ndf_mom &lt;- subset(res_df, method == &quot;moments&quot;)\ndf_mle &lt;- subset(res_df, method == &quot;mle&quot;)\n\n# Helper function to generate the panels\nmake_panel &lt;- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p &lt;- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = &quot;n&quot;, y = y_label, color = &quot;k&quot;) +\n theme_bw() +\n theme(legend.position = &quot;bottom&quot;,\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p &lt;- p + geom_hline(yintercept = hline, linetype = &quot;dashed&quot;, linewidth = 0.5)\n }\n return(p)\n}\n\np1 &lt;- make_panel(df_mom, &quot;bias&quot;, &quot;Moments: bias of the estimated mean&quot;, \n &quot;Average estimate minus the truth. Dashed line at 0.&quot;, &quot;bias&quot;, 0)\np2 &lt;- make_panel(df_mle, &quot;bias&quot;, &quot;MLE: bias of the estimated mean&quot;, \n &quot;Average estimate minus the truth. Dashed line at 0.&quot;, &quot;bias&quot;, 0)\np3 &lt;- make_panel(df_mom, &quot;sd_estimate&quot;, &quot;Moments: SD of the estimated mean&quot;, \n &quot;Spread of the estimate across studies.&quot;, &quot;SD&quot;)\np4 &lt;- make_panel(df_mle, &quot;sd_estimate&quot;, &quot;MLE: SD of the estimated mean&quot;, \n &quot;Spread of the estimate across studies.&quot;, &quot;SD&quot;)\n\n# Combine using patchwork\ncombined_grid &lt;- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov &lt;- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = &quot;dashed&quot;) +\n facet_grid(~ k, labeller = label_both) +\n labs(title = &quot;Coverage of the nominal 95% interval&quot;,\n subtitle = &quot;Share of 1000 intervals containing the true mean. Dashed line at 0.95.&quot;,\n x = &quot;n&quot;,\n y = &quot;coverage&quot;,\n color = &quot;method&quot;) +\n theme_bw() +\n theme(legend.position = &quot;bottom&quot;,\n strip.background = element_rect(fill = &quot;grey90&quot;))\n\nprint(p_cov)\n</code></pre>\n", "answer_id": 677117, "answer_text": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)", "answer_url": "https://stats.stackexchange.com/a/677117", "author": "jblood94", "author_url": "https://stats.stackexchange.com/users/214015/jblood94", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-09T13:02:57+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677094, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jblood94", "profile_url": "https://stats.stackexchange.com/users/214015/jblood94", "user_type": "registered"}, "created_at": "2026-09-09T13:02:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "09E52470-6B69-4568-A8B3-D52476EA341B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "20C3E36B-1564-462F-9257-5BBE5B9B70EF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}], "score": 3, "updated_at": "2026-09-09T13:02:57+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/9nEiiFBK.png", "https://i.sstatic.net/H3ywscwO.png", "https://i.sstatic.net/kEDelnub.png", "https://i.sstatic.net/yrEHvkk0.png"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:03.428408+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/774052c18cd9e8fa951e893347bfa3c1a85e743fc46ec4667572002cadb10cbf_1790825224163423600_0.json", "raw_sha256": "fe4dd06d3de6c0b1bb33ba88aee0ed4284118e01f76a58dcdce220a4946329b2", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "adamkostanov", "question_author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "question_author_user_type": "registered", "question_created_at": "2026-09-07T06:07:31+00:00", "question_html": "<p>Here is a beta-binomial model (treated like repeated measures - <span class=\"math-container\">$i$</span> is an index for each individual, <span class=\"math-container\">$n$</span> total individuals, and exactly <span class=\"math-container\">$k$</span> measurements per individual):</p>\n<p><span class=\"math-container\">$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$</span></p>\n<p><span class=\"math-container\">$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$</span></p>\n<p><span class=\"math-container\">$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$</span></p>\n<p><span class=\"math-container\">$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$</span></p>\n<p>For a single unit,</p>\n<p><span class=\"math-container\">$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$</span></p>\n<p>and</p>\n<p><span class=\"math-container\">$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$</span></p>\n<p>There are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).</p>\n<p>The first way is with moments (I can show the manipulations if needed):</p>\n<p><span class=\"math-container\">$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$</span></p>\n<p><span class=\"math-container\">$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$</span></p>\n<p><span class=\"math-container\">$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$</span></p>\n<p>And the second way is using MLE (delta method for variances and log/exp constraint for optimization).</p>\n<p>Here is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of <span class=\"math-container\">$n,k$</span> for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):</p>\n<pre><code>library(MASS)\n\nz &lt;- qnorm(0.975)\n\n## Simulate \nmu_true &lt;- 0.5\nv_true &lt;- 0.249\nn_vals &lt;- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals &lt;- c(1, 2, 3, 4, 5, 6,7,8,9)\nR &lt;- 1000\n\n\nsim_data &lt;- function(n, k, mu, v) {\n nu &lt;- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll &lt;- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle &lt;- function(x, k) {\n n &lt;- length(x)\n o &lt;- try(optim(c(0, 0), bb_nll, x = x, k = k, method = &quot;BFGS&quot;,\n hessian = TRUE), silent = TRUE)\n if (inherits(o, &quot;try-error&quot;)) return(c(NA, NA))\n a &lt;- exp(o<span class=\"math-container\">$par[1]); b &lt;- exp(o$</span>par[2])\n g &lt;- a * b / (a + b)^2 * c(1, -1)\n V &lt;- try(drop(crossprod(g, ginv(o<span class=\"math-container\">$hessian) %*% g)), silent = TRUE)\n ok &lt;- !inherits(V, \"try-error\") &amp;&amp; is.finite(V) &amp;&amp; V &gt; 0 &amp;&amp;\n V &lt; 1 / (4 * n) &amp;&amp; rcond(o$</span>hessian) &gt; 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom &lt;- function(x, k) {\n p &lt;- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore &lt;- function(m, V, mu) {\n s &lt;- sqrt(V); ok &lt;- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) &lt;= z * s, na.rm = TRUE))\n}\n\nrun_cell &lt;- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(&quot;[%2d/%2d] n = %3d, k = %d ... &quot;, i, tot, n, k))\n e &lt;- replicate(R, { x &lt;- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(&quot;done (%.1fs elapsed)\\n&quot;,\n as.numeric(difftime(Sys.time(), t0, units = &quot;secs&quot;))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(&quot;moments&quot;, &quot;mle&quot;),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng &lt;- expand.grid(n = n_vals, k = k_vals)\nres &lt;- do.call(rbind, Map(run_cell, mu_true, v_true, g<span class=\"math-container\">$n, g$</span>k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n</code></pre>\n<p>Here are the results:</p>\n<p><a href=\"https://i.sstatic.net/kEDelnub.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/kEDelnub.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/H3ywscwO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/H3ywscwO.png\" alt=\"enter image description here\" /></a></p>\n<p>Prior to running this script, I would have thought that larger <span class=\"math-container\">$n,k$</span> combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as <span class=\"math-container\">$n$</span> increases (jagged pattern).</p>\n<p>Why is this happening?</p>\n", "question_id": 677094, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):\n\n\n\n\n$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$\n\n\n\n\n$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$\n\n\n\n\n$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$\n\n\n\n\nFor a single unit,\n\n\n\n\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\nand\n\n\n\n\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$\n\n\n\n\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).\n\n\n\n\nThe first way is with moments (I can show the manipulations if needed):\n\n\n\n\n$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$\n\n\n\n\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\n$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$\n\n\n\n\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).\n\n\n\n\nHere is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\n\n\n\n\nHere are the results:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/kEDelnub.png] (https://i.sstatic.net/kEDelnub.png)\n[image: enter image description here; source: https://i.sstatic.net/H3ywscwO.png] (https://i.sstatic.net/H3ywscwO.png)\n\n\n\n\nPrior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).\n\n\n\n\nWhy is this happening?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:07:31+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "BE06C153-8C52-4CC0-883B-294D30B035A1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/BE06C153-8C52-4CC0-883B-294D30B035A1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:17:50+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "E476317C-DD27-4C9B-AE2F-6BCDF9875E56", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E476317C-DD27-4C9B-AE2F-6BCDF9875E56/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:25:11+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "30B3CCCA-ABFC-44BA-A8AA-62F762C98FC8", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/30B3CCCA-ABFC-44BA-A8AA-62F762C98FC8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:33:19+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "2E412836-177B-410E-B0A8-2FD925F88199", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2E412836-177B-410E-B0A8-2FD925F88199/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:41:52+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "246BB9D4-0913-4A5D-BA26-19A883E71D2E", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/246BB9D4-0913-4A5D-BA26-19A883E71D2E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T08:45:32+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "06091D8C-4AF4-44C7-A257-DDB59EE43D39", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/06091D8C-4AF4-44C7-A257-DDB59EE43D39/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-09T06:13:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "4B6B337A-AB66-48A4-9852-835642560D4F", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/4B6B337A-AB66-48A4-9852-835642560D4F/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-09T06:13:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "FF6141BB-F0C5-4F25-80CC-121B75A68FE8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/FF6141BB-F0C5-4F25-80CC-121B75A68FE8/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "398480DB-D18F-4C34-B57A-2901985CD8FF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/398480DB-D18F-4C34-B57A-2901985CD8FF/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "E442CC1D-1B8D-4B82-A247-1B52D8C54699", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/E442CC1D-1B8D-4B82-A247-1B52D8C54699/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases", "split": "test", "split_group": "9708b014da60835c67095344e417c92716420d5056f8162fcbb5adcca7853c04", "tags": ["r", "maximum-likelihood"], "thread_id": "stats:677094", "title": "Can coverage probability decrease as sample size increases?"}}
{"accepted_answer": {"answer_html": "<p>The integral is incorrect. It should be:</p>\n<p><span class=\"math-container\">$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$</span></p>\n<p>The reason is that <span class=\"math-container\">$[2, 0, 0]$</span> maps to <em>two</em> level 0 cosines each with norm <span class=\"math-container\">$\\sqrt{2}$</span></p>\n", "answer_id": 45287, "answer_text": "The integral is incorrect. It should be:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$\n\n\n\n\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$", "answer_url": "https://scicomp.stackexchange.com/a/45287", "author": "Makogan", "author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:39:36+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T06:39:36+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFA52975-239F-441C-8A99-5359D4A5D377", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFA52975-239F-441C-8A99-5359D4A5D377/view-source"}], "score": 2, "updated_at": "2025-11-21T06:39:36+00:00"}, "code_blocks": [{"block_index": 1, "code_text": "fn fourier_projection<F, S: RealField, const DIM: usize>(\n mut function: F,\n interval: [[S; 2]; DIM],\n basis_index: [usize; DIM],\n resolution: usize,\n) -> S\nwhere\n F: FnMut([S; DIM]) -> S,\n{\n let trapezoidal_weight = |i: usize| {\n if i == 0 || i == resolution - 1\n {\n S::from(0.5).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n };\n\n let mut res = S::default();\n\n for xi in IterDimensions::new([resolution; DIM])\n {\n let mut point = [S::default(); DIM];\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let x = t * range + interval[d][0];\n\n point[d] = x;\n }\n\n let mut val = function(point);\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let dx = range / S::from(resolution - 1).unwrap();\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let xp = t * S::from(2).unwrap() - S::from(1).unwrap();\n\n val *= fourier_basis(xp, basis_index[d]) * trapezoidal_weight(xi[d]) * dx\n / fourier_norm_on_standard_interval(basis_index[d]);\n }\n\n res += val\n }\n\n res\n}\n\npub fn fourier_norm_on_standard_interval<S: RealField>(basis_index: usize) -> S\n{\n // Only for the very first function (constant) is the norm different.\n if basis_index == 0\n {\n S::from(f64::sqrt(2.)).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n}\n\npub fn fourier_basis<S: RealField>(t: S, basis_index: usize) -> S\n{\n let pi = S::from(PI).unwrap();\n\n let n = basis_index / 2;\n if basis_index % 2 == 0\n {\n ((t * pi) * S::from(n).unwrap()).cos()\n }\n else\n {\n ((t * pi) * S::from(n + 1).unwrap()).sin()\n }\n}\n\n// test\n let test = fourier_projection(\n |[x, y, z]| (PI * x).cos(),\n [[-1., 1.]; 3],\n [2, 0, 0],\n 100,\n );\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45285, "sha256": "e1dcefc0d5d1500fcb42230ce83debd4e2fd54094435a14a5ff7f9f0413f58c0", "source_url": "https://scicomp.stackexchange.com/questions/45285/issues-deriving-a-periodic-basis-in-r3"}], "other_answers": [{"answer_html": "<p>The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!</p>\n<p>If you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. <a href=\"https://en.wikipedia.org/wiki/Discrete_cosine_transform\" rel=\"nofollow noreferrer\">cosine transform</a></p>\n<p>edit:\n<strong>I think I was wrong on this</strong>. It might be possible although i am not sure about the continuities at the borders of the cell.</p>\n", "answer_id": 45286, "answer_text": "The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!\n\n\n\n\nIf you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. cosine transform (https://en.wikipedia.org/wiki/Discrete_cosine_transform)\n\n\n\n\nedit:\nI think I was wrong on this. It might be possible although i am not sure about the continuities at the borders of the cell.", "answer_url": "https://scicomp.stackexchange.com/a/45286", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:31:22+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T06:31:22+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "CBEFF318-897B-4078-914B-16A6943BCDC5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CBEFF318-897B-4078-914B-16A6943BCDC5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T10:25:12+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "64E18437-B71C-4033-8D9E-EBECF3C94E96", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64E18437-B71C-4033-8D9E-EBECF3C94E96/view-source"}], "score": 1, "updated_at": "2025-11-21T10:25:12+00:00"}], "product": "code_qa", "question": "Math preamble\n\n\n\n\nI am trying to create a functional basis for $[-1, 1]^3$ in $\\mathbb{R}^3$. To this effect I take the real expression of the fourier basis and index it with an integer such that\n\n\n\n\n$$\\phi_i(x) = \\cos(\\pi n/2 x)$$\n\n\n\n\nif $i$ is even and\n\n\n\n\n$$\\phi_i(x) = \\sin(\\pi [(n/2) + 1] x)$$\n\n\n\n\nif $i$ is odd.\n\n\n\n\nThen I normalize them, so for simplicity of writing, assume $\\phi_i$ is the normalized version of the function.\n\n\n\n\nWith that definition I create the basis through the tensor product.\n\n\n\n\n$$\\Phi_{i,j,k}(x, y, z) = \\phi_i(x) \\phi_j(y) \\phi_k(z)$$\n\n\n\n\nAlgorithm\n\n\n\n\nNow to render the above basis computable I am only dealing with triplets such that $i + j + k \\leq N$ for some integer $N$.\n\n\n\n\nI am using the trapezoidal rule (also extended through the tensor product) in order to compute integrals, so\n\n\n\n\n$$\\int_\\Omega f(X) \\Phi_{i, j, k}(X) dV \\approx \\sum w_l w_m w_n f(X_{l, m, n})) \\Phi_{i, j, k}(X_{l, m, n}) \\Delta x \\Delta y \\Delta z$$\n\n\n\n\nwhere $w_i$ refer to the weights from the trapezoidal rule. 0.5 at the margins and 1 in the interior.\n\n\n\n\nUsing the above I am projecting different functions onto the discretized basis and then reconstructing them to see the accuracy.\n\n\n\n\nExperiments\n\n\n\n\nI am testing my code and I am noticing discrepancies, for example. I am trying to project $f(x, y, z) = \\cos(\\pi x)$ onto $\\Phi_{2, 0, 0}$\n\n\n\n\nFrom the original definition you will notice that $\\Phi_{2, 0, 0}$ should be $\\cos(\\pi x) / \\sqrt{2}$\n\n\n\n\nSo my expectation is that I am computing:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{\\sqrt{2}} dx dy dz \\approx 2.83$$\n\n\n\n\nHowever, what I am getting is\n\n\n\n\n1.9999999999967393\n\n\n\n\n\nThis is my code (written in rust):\n\n\n\n\nfn fourier_projection<F, S: RealField, const DIM: usize>(\n mut function: F,\n interval: [[S; 2]; DIM],\n basis_index: [usize; DIM],\n resolution: usize,\n) -> S\nwhere\n F: FnMut([S; DIM]) -> S,\n{\n let trapezoidal_weight = |i: usize| {\n if i == 0 || i == resolution - 1\n {\n S::from(0.5).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n };\n\n let mut res = S::default();\n\n for xi in IterDimensions::new([resolution; DIM])\n {\n let mut point = [S::default(); DIM];\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let x = t * range + interval[d][0];\n\n point[d] = x;\n }\n\n let mut val = function(point);\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let dx = range / S::from(resolution - 1).unwrap();\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let xp = t * S::from(2).unwrap() - S::from(1).unwrap();\n\n val *= fourier_basis(xp, basis_index[d]) * trapezoidal_weight(xi[d]) * dx\n / fourier_norm_on_standard_interval(basis_index[d]);\n }\n\n res += val\n }\n\n res\n}\n\npub fn fourier_norm_on_standard_interval<S: RealField>(basis_index: usize) -> S\n{\n // Only for the very first function (constant) is the norm different.\n if basis_index == 0\n {\n S::from(f64::sqrt(2.)).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n}\n\npub fn fourier_basis<S: RealField>(t: S, basis_index: usize) -> S\n{\n let pi = S::from(PI).unwrap();\n\n let n = basis_index / 2;\n if basis_index % 2 == 0\n {\n ((t * pi) * S::from(n).unwrap()).cos()\n }\n else\n {\n ((t * pi) * S::from(n + 1).unwrap()).sin()\n }\n}\n\n// test\n let test = fourier_projection(\n |[x, y, z]| (PI * x).cos(),\n [[-1., 1.]; 3],\n [2, 0, 0],\n 100,\n );\n\n\n\n\n\nI was hoping someone could point out where I made a mistake.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45285", "selected_answer": {"answer_html": "<p>The integral is incorrect. It should be:</p>\n<p><span class=\"math-container\">$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$</span></p>\n<p>The reason is that <span class=\"math-container\">$[2, 0, 0]$</span> maps to <em>two</em> level 0 cosines each with norm <span class=\"math-container\">$\\sqrt{2}$</span></p>\n", "answer_id": 45287, "answer_text": "The integral is incorrect. It should be:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$\n\n\n\n\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$", "answer_url": "https://scicomp.stackexchange.com/a/45287", "author": "Makogan", "author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:39:36+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T06:39:36+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFA52975-239F-441C-8A99-5359D4A5D377", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFA52975-239F-441C-8A99-5359D4A5D377/view-source"}], "score": 2, "updated_at": "2025-11-21T06:39:36+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 45287, "answers": [{"answer_html": "<p>The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!</p>\n<p>If you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. <a href=\"https://en.wikipedia.org/wiki/Discrete_cosine_transform\" rel=\"nofollow noreferrer\">cosine transform</a></p>\n<p>edit:\n<strong>I think I was wrong on this</strong>. It might be possible although i am not sure about the continuities at the borders of the cell.</p>\n", "answer_id": 45286, "answer_text": "The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!\n\n\n\n\nIf you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. cosine transform (https://en.wikipedia.org/wiki/Discrete_cosine_transform)\n\n\n\n\nedit:\nI think I was wrong on this. It might be possible although i am not sure about the continuities at the borders of the cell.", "answer_url": "https://scicomp.stackexchange.com/a/45286", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:31:22+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T06:31:22+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "CBEFF318-897B-4078-914B-16A6943BCDC5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CBEFF318-897B-4078-914B-16A6943BCDC5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T10:25:12+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "64E18437-B71C-4033-8D9E-EBECF3C94E96", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64E18437-B71C-4033-8D9E-EBECF3C94E96/view-source"}], "score": 1, "updated_at": "2025-11-21T10:25:12+00:00"}, {"answer_html": "<p>The integral is incorrect. It should be:</p>\n<p><span class=\"math-container\">$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$</span></p>\n<p>The reason is that <span class=\"math-container\">$[2, 0, 0]$</span> maps to <em>two</em> level 0 cosines each with norm <span class=\"math-container\">$\\sqrt{2}$</span></p>\n", "answer_id": 45287, "answer_text": "The integral is incorrect. It should be:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$\n\n\n\n\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$", "answer_url": "https://scicomp.stackexchange.com/a/45287", "author": "Makogan", "author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:39:36+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T06:39:36+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFA52975-239F-441C-8A99-5359D4A5D377", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFA52975-239F-441C-8A99-5359D4A5D377/view-source"}], "score": 2, "updated_at": "2025-11-21T06:39:36+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Discrete_cosine_transform"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:44.584971+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json", "raw_sha256": "27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Makogan", "question_author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "question_author_user_type": "registered", "question_created_at": "2025-11-21T02:24:58+00:00", "question_html": "<h1>Math preamble</h1>\n<p>I am trying to create a functional basis for <span class=\"math-container\">$[-1, 1]^3$</span> in <span class=\"math-container\">$\\mathbb{R}^3$</span>. To this effect I take the real expression of the fourier basis and index it with an integer such that</p>\n<p><span class=\"math-container\">$$\\phi_i(x) = \\cos(\\pi n/2 x)$$</span></p>\n<p>if <span class=\"math-container\">$i$</span> is even and</p>\n<p><span class=\"math-container\">$$\\phi_i(x) = \\sin(\\pi [(n/2) + 1] x)$$</span></p>\n<p>if <span class=\"math-container\">$i$</span> is odd.</p>\n<p>Then I normalize them, so for simplicity of writing, assume <span class=\"math-container\">$\\phi_i$</span> is the normalized version of the function.</p>\n<p>With that definition I create the basis through the tensor product.</p>\n<p><span class=\"math-container\">$$\\Phi_{i,j,k}(x, y, z) = \\phi_i(x) \\phi_j(y) \\phi_k(z)$$</span></p>\n<h1>Algorithm</h1>\n<p>Now to render the above basis computable I am only dealing with triplets such that <span class=\"math-container\">$i + j + k \\leq N$</span> for some integer <span class=\"math-container\">$N$</span>.</p>\n<p>I am using the trapezoidal rule (also extended through the tensor product) in order to compute integrals, so</p>\n<p><span class=\"math-container\">$$\\int_\\Omega f(X) \\Phi_{i, j, k}(X) dV \\approx \\sum w_l w_m w_n f(X_{l, m, n})) \\Phi_{i, j, k}(X_{l, m, n}) \\Delta x \\Delta y \\Delta z$$</span></p>\n<p>where <span class=\"math-container\">$w_i$</span> refer to the weights from the trapezoidal rule. 0.5 at the margins and 1 in the interior.</p>\n<p>Using the above I am projecting different functions onto the discretized basis and then reconstructing them to see the accuracy.</p>\n<h1>Experiments</h1>\n<p>I am testing my code and I am noticing discrepancies, for example. I am trying to project <span class=\"math-container\">$f(x, y, z) = \\cos(\\pi x)$</span> onto <span class=\"math-container\">$\\Phi_{2, 0, 0}$</span></p>\n<p>From the original definition you will notice that <span class=\"math-container\">$\\Phi_{2, 0, 0}$</span> should be <span class=\"math-container\">$\\cos(\\pi x) / \\sqrt{2}$</span></p>\n<p>So my expectation is that I am computing:</p>\n<p><span class=\"math-container\">$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{\\sqrt{2}} dx dy dz \\approx 2.83$$</span></p>\n<p>However, what I am getting is</p>\n<pre><code>1.9999999999967393\n</code></pre>\n<p>This is my code (written in rust):</p>\n<pre class=\"lang-rs prettyprint-override\"><code>fn fourier_projection&lt;F, S: RealField, const DIM: usize&gt;(\n mut function: F,\n interval: [[S; 2]; DIM],\n basis_index: [usize; DIM],\n resolution: usize,\n) -&gt; S\nwhere\n F: FnMut([S; DIM]) -&gt; S,\n{\n let trapezoidal_weight = |i: usize| {\n if i == 0 || i == resolution - 1\n {\n S::from(0.5).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n };\n\n let mut res = S::default();\n\n for xi in IterDimensions::new([resolution; DIM])\n {\n let mut point = [S::default(); DIM];\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let x = t * range + interval[d][0];\n\n point[d] = x;\n }\n\n let mut val = function(point);\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let dx = range / S::from(resolution - 1).unwrap();\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let xp = t * S::from(2).unwrap() - S::from(1).unwrap();\n\n val *= fourier_basis(xp, basis_index[d]) * trapezoidal_weight(xi[d]) * dx\n / fourier_norm_on_standard_interval(basis_index[d]);\n }\n\n res += val\n }\n\n res\n}\n\npub fn fourier_norm_on_standard_interval&lt;S: RealField&gt;(basis_index: usize) -&gt; S\n{\n // Only for the very first function (constant) is the norm different.\n if basis_index == 0\n {\n S::from(f64::sqrt(2.)).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n}\n\npub fn fourier_basis&lt;S: RealField&gt;(t: S, basis_index: usize) -&gt; S\n{\n let pi = S::from(PI).unwrap();\n\n let n = basis_index / 2;\n if basis_index % 2 == 0\n {\n ((t * pi) * S::from(n).unwrap()).cos()\n }\n else\n {\n ((t * pi) * S::from(n + 1).unwrap()).sin()\n }\n}\n\n// test\n let test = fourier_projection(\n |[x, y, z]| (PI * x).cos(),\n [[-1., 1.]; 3],\n [2, 0, 0],\n 100,\n );\n</code></pre>\n<p>I was hoping someone could point out where I made a mistake.</p>\n", "question_id": 45285, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "Math preamble\n\n\n\n\nI am trying to create a functional basis for $[-1, 1]^3$ in $\\mathbb{R}^3$. To this effect I take the real expression of the fourier basis and index it with an integer such that\n\n\n\n\n$$\\phi_i(x) = \\cos(\\pi n/2 x)$$\n\n\n\n\nif $i$ is even and\n\n\n\n\n$$\\phi_i(x) = \\sin(\\pi [(n/2) + 1] x)$$\n\n\n\n\nif $i$ is odd.\n\n\n\n\nThen I normalize them, so for simplicity of writing, assume $\\phi_i$ is the normalized version of the function.\n\n\n\n\nWith that definition I create the basis through the tensor product.\n\n\n\n\n$$\\Phi_{i,j,k}(x, y, z) = \\phi_i(x) \\phi_j(y) \\phi_k(z)$$\n\n\n\n\nAlgorithm\n\n\n\n\nNow to render the above basis computable I am only dealing with triplets such that $i + j + k \\leq N$ for some integer $N$.\n\n\n\n\nI am using the trapezoidal rule (also extended through the tensor product) in order to compute integrals, so\n\n\n\n\n$$\\int_\\Omega f(X) \\Phi_{i, j, k}(X) dV \\approx \\sum w_l w_m w_n f(X_{l, m, n})) \\Phi_{i, j, k}(X_{l, m, n}) \\Delta x \\Delta y \\Delta z$$\n\n\n\n\nwhere $w_i$ refer to the weights from the trapezoidal rule. 0.5 at the margins and 1 in the interior.\n\n\n\n\nUsing the above I am projecting different functions onto the discretized basis and then reconstructing them to see the accuracy.\n\n\n\n\nExperiments\n\n\n\n\nI am testing my code and I am noticing discrepancies, for example. I am trying to project $f(x, y, z) = \\cos(\\pi x)$ onto $\\Phi_{2, 0, 0}$\n\n\n\n\nFrom the original definition you will notice that $\\Phi_{2, 0, 0}$ should be $\\cos(\\pi x) / \\sqrt{2}$\n\n\n\n\nSo my expectation is that I am computing:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{\\sqrt{2}} dx dy dz \\approx 2.83$$\n\n\n\n\nHowever, what I am getting is\n\n\n\n\n1.9999999999967393\n\n\n\n\n\nThis is my code (written in rust):\n\n\n\n\nfn fourier_projection<F, S: RealField, const DIM: usize>(\n mut function: F,\n interval: [[S; 2]; DIM],\n basis_index: [usize; DIM],\n resolution: usize,\n) -> S\nwhere\n F: FnMut([S; DIM]) -> S,\n{\n let trapezoidal_weight = |i: usize| {\n if i == 0 || i == resolution - 1\n {\n S::from(0.5).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n };\n\n let mut res = S::default();\n\n for xi in IterDimensions::new([resolution; DIM])\n {\n let mut point = [S::default(); DIM];\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let x = t * range + interval[d][0];\n\n point[d] = x;\n }\n\n let mut val = function(point);\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let dx = range / S::from(resolution - 1).unwrap();\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let xp = t * S::from(2).unwrap() - S::from(1).unwrap();\n\n val *= fourier_basis(xp, basis_index[d]) * trapezoidal_weight(xi[d]) * dx\n / fourier_norm_on_standard_interval(basis_index[d]);\n }\n\n res += val\n }\n\n res\n}\n\npub fn fourier_norm_on_standard_interval<S: RealField>(basis_index: usize) -> S\n{\n // Only for the very first function (constant) is the norm different.\n if basis_index == 0\n {\n S::from(f64::sqrt(2.)).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n}\n\npub fn fourier_basis<S: RealField>(t: S, basis_index: usize) -> S\n{\n let pi = S::from(PI).unwrap();\n\n let n = basis_index / 2;\n if basis_index % 2 == 0\n {\n ((t * pi) * S::from(n).unwrap()).cos()\n }\n else\n {\n ((t * pi) * S::from(n + 1).unwrap()).sin()\n }\n}\n\n// test\n let test = fourier_projection(\n |[x, y, z]| (PI * x).cos(),\n [[-1., 1.]; 3],\n [2, 0, 0],\n 100,\n );\n\n\n\n\n\nI was hoping someone could point out where I made a mistake.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T02:24:58+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "B9CFB5A4-3B47-4382-BEF6-D74DBB33E85A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B9CFB5A4-3B47-4382-BEF6-D74DBB33E85A/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45285/issues-deriving-a-periodic-basis-in-r3", "split": "test", "split_group": "96bd03d5e1726730a642e946c45093801632d13b9c66e58b80e7027e3583e631", "tags": ["numerics", "algorithms", "fourier-analysis"], "thread_id": "scicomp:45285", "title": "Issues deriving a periodic basis in r^3"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "from mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45291, "sha256": "986e2bb7e76ea41218a3f1e6b7c67a6ca5385c0dc9eb4b9bb4c49ee3fe19b82d", "source_url": "https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms"}, {"block_index": 0, "code_text": "from mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45295, "sha256": "b2c96936281d10430ccaf43e37df226edf2465e0445a080363a43be285aeda8c", "source_url": "https://scicomp.stackexchange.com/a/45295"}], "other_answers": [{"answer_html": "<p>An efficient way to compute <span class=\"math-container\">$\\sin(kx)$</span> in the context of iteration over <span class=\"math-container\">$k$</span> is to make use of the recursive formula <span class=\"math-container\">$\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$</span>.</p>\n<p>However, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some <em>quick</em> experiments indicate that this would be the case here.</p>\n<p>The issue of subtractive cancellation can be largely mitigated by the use of a <em>fused</em> multiply-add operation, or FMA. This operation first computes the <em>full</em>, unrounded, product <span class=\"math-container\">$ab$</span> before applying the addition of <span class=\"math-container\">$c$</span>, finally returning the final result <span class=\"math-container\">$ab+c$</span> with a <em>single</em> rounding. This operation is supported in many programming environments as a function <code>fma()</code> for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.</p>\n<p>However, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to <em>approximately</em> emulate it by computing <span class=\"math-container\">$ab+c$</span> at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.</p>\n<p>With FMA support, one computes <span class=\"math-container\">$\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$</span>.</p>\n", "answer_id": 45293, "answer_text": "An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.\n\n\n\n\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.\n\n\n\n\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.\n\n\n\n\nHowever, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.\n\n\n\n\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.", "answer_url": "https://scicomp.stackexchange.com/a/45293", "author": "njuffa", "author_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-26T23:33:21+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "njuffa", "profile_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "user_type": "registered"}, "created_at": "2025-11-26T23:33:21+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "B6ACA9A9-61E5-4827-8876-77505A1EE621", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B6ACA9A9-61E5-4827-8876-77505A1EE621/view-source"}], "score": 4, "updated_at": "2025-11-26T23:33:21+00:00"}, {"answer_html": "<p>One idea would be to use part of the series expansion of <span class=\"math-container\">$sin(x)$</span> for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.</p>\n<p>That way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of <span class=\"math-container\">$sin(x)$</span> as before.</p>\n<p><span class=\"math-container\">\\begin{align}\n\\sin(x) &amp;= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &amp;= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}</span></p>\n<p>Note that the expansion looses precision the further away you are from 0.</p>\n", "answer_id": 45294, "answer_text": "One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.\n\n\n\n\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.\n\n\n\n\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}\n\n\n\n\nNote that the expansion looses precision the further away you are from 0.", "answer_url": "https://scicomp.stackexchange.com/a/45294", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T07:31:18+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:31:18+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "968C67F8-16E6-40D8-80A4-8E5335D3FC2C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/968C67F8-16E6-40D8-80A4-8E5335D3FC2C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:36:23+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "1885B799-B6E4-4653-BEFB-37E50B86F7E6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/1885B799-B6E4-4653-BEFB-37E50B86F7E6/view-source"}], "score": 2, "updated_at": "2025-11-27T07:36:23+00:00"}], "product": "code_qa", "question": "I have this recurrence formula for $\\pi$ with convergence order $2m+1$:\n\n\n\n\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$\n\n\n\n\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$\n\n\n\n\nAfter four iterations, $\\pi$ is accurate to $761$ digits:\n\n\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n\n\n\n\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.\n\n\n\n\nQuestion\n\n\n\n\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?\n\n\n\n\nUpdate\n\n\n\n\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:\n\n\n\n\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$\n\n\n\n\nThanks!", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45291", "selected_answer": {"answer_html": "<p>Given the recurrence\n<span class=\"math-container\">$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$</span></p>\n<p>We can use the <a href=\"https://en.wikipedia.org/wiki/Chebyshev_polynomials\" rel=\"noreferrer\">Chebyshev polynomial</a> of the second kind:\n<span class=\"math-container\">$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$</span></p>\n<p>Plugging <span class=\"math-container\">$n = k-1$</span> into this definition gives\n<span class=\"math-container\">$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$</span></p>\n<p>Therefore, the iteration can be written equivalently as\n<span class=\"math-container\">$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$</span>\nwith\n<span class=\"math-container\">$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$</span></p>\n<p>and</p>\n<p><span class=\"math-container\">$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$</span></p>\n<p>Therefore, the new iteration can be written as\n<span class=\"math-container\">$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$</span></p>\n<p>where <span class=\"math-container\">$P_m$</span> is the polynomial\n<span class=\"math-container\">$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$</span></p>\n<p>So instead of computing <span class=\"math-container\">$\\sin(k x_n)$</span> for every <span class=\"math-container\">$k$</span>, we can:</p>\n<ul>\n<li>Compute <span class=\"math-container\">$s = \\sin(x_n)$</span> once,</li>\n<li>Compute <span class=\"math-container\">$c = \\cos(x_n)$</span> once,</li>\n<li>Evaluate the polynomial <span class=\"math-container\">$P_m(c)$</span>.</li>\n</ul>\n<h2>Example</h2>\n<p>We start from the Chebyshev representation for <span class=\"math-container\">$m=5$</span>:\n<span class=\"math-container\">$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$</span>\nwith\n<span class=\"math-container\">$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$</span>\nand\n<span class=\"math-container\">$$\n\\begin{aligned}\nU_0(t) &amp;= 1,\\\\\nU_1(t) &amp;= 2t,\\\\\nU_2(t) &amp;= 4t^2 - 1,\\\\\nU_3(t) &amp;= 8t^3 - 4t,\\\\\nU_4(t) &amp;= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$</span></p>\n<p>Thus\n<span class=\"math-container\">$$\n\\begin{aligned}\nP_5(t)\n&amp;= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&amp;= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$</span></p>\n<p>Simplifying each term:\n<span class=\"math-container\">$$\n\\begin{aligned}\nP_5(t)\n&amp;= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&amp;= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$</span></p>\n<p>Now collect like powers of <span class=\"math-container\">$t$</span>.</p>\n<p><span class=\"math-container\">$t^4$</span> term:\n<span class=\"math-container\">$$\n\\frac{8}{315}t^4.\n$$</span></p>\n<p><span class=\"math-container\">$t^3$</span> term:\n<span class=\"math-container\">$$\n\\frac{10}{63}t^3.\n$$</span></p>\n<p><span class=\"math-container\">$t^2$</span> term:\n<span class=\"math-container\">$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$</span></p>\n<p><span class=\"math-container\">$t^1$</span> term:\n<span class=\"math-container\">$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$</span></p>\n<p>Constant term:\n<span class=\"math-container\">$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$</span></p>\n<p>So we obtain\n<span class=\"math-container\">$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$</span></p>\n<p>Factoring out <span class=\"math-container\">$\\frac{1}{315}$</span> gives the compact form\n<span class=\"math-container\">$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$</span></p>\n<h2>Test Case</h2>\n<p>For <span class=\"math-container\">$m = 5$</span> we have\n<span class=\"math-container\">$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$</span>\nand the iteration\n<span class=\"math-container\">$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$</span></p>\n<pre><code>from mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n &quot;&quot;&quot;\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n &quot;&quot;&quot;\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(&quot;Approximate pi (m=5):&quot;)\nprint(mp.nstr(x, 1000))\nprint(f&quot;\\nTime Taken: {end - start:.6f} seconds&quot;)\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(&quot;\\nError x - pi:&quot;)\nprint(mp.nstr(err, 5))\n</code></pre>\n<hr />\n<p>Approximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199</p>\n<p>Time Taken: 0.001180 seconds</p>\n<p>Error x - pi:\n0.0</p>\n", "answer_id": 45295, "answer_text": "Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$\n\n\n\n\nWe can use the Chebyshev polynomial (https://en.wikipedia.org/wiki/Chebyshev_polynomials) of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$\n\n\n\n\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$\n\n\n\n\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$\n\n\n\n\nand\n\n\n\n\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$\n\n\n\n\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:\n\n\n\n\n\nCompute $s = \\sin(x_n)$ once,\n\n\n\n\nCompute $c = \\cos(x_n)$ once,\n\n\n\n\nEvaluate the polynomial $P_m(c)$.\n\n\n\n\n\nExample\n\n\n\n\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$\n\n\n\n\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$\n\n\n\n\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$\n\n\n\n\nNow collect like powers of $t$.\n\n\n\n\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$\n\n\n\n\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$\n\n\n\n\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$\n\n\n\n\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$\n\n\n\n\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$\n\n\n\n\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$\n\n\n\n\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$\n\n\n\n\nTest Case\n\n\n\n\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n\n\n\n\n\n\n\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199\n\n\n\n\nTime Taken: 0.001180 seconds\n\n\n\n\nError x - pi:\n0.0", "answer_url": "https://scicomp.stackexchange.com/a/45295", "author": "vengy", "author_url": "https://scicomp.stackexchange.com/users/56070/vengy", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T16:01:03+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:01:03+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "12F528C5-3339-4BD9-82C4-1F98C0E30ABD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F528C5-3339-4BD9-82C4-1F98C0E30ABD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:46:02+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "94F6BA8F-8639-48FE-844B-374EC8092EC7", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/94F6BA8F-8639-48FE-844B-374EC8092EC7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T17:19:25+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C72508F8-E2C5-4479-B135-70BE30A2F07C", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C72508F8-E2C5-4479-B135-70BE30A2F07C/view-source"}], "score": 7, "updated_at": "2025-11-27T17:19:25+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "<p>An efficient way to compute <span class=\"math-container\">$\\sin(kx)$</span> in the context of iteration over <span class=\"math-container\">$k$</span> is to make use of the recursive formula <span class=\"math-container\">$\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$</span>.</p>\n<p>However, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some <em>quick</em> experiments indicate that this would be the case here.</p>\n<p>The issue of subtractive cancellation can be largely mitigated by the use of a <em>fused</em> multiply-add operation, or FMA. This operation first computes the <em>full</em>, unrounded, product <span class=\"math-container\">$ab$</span> before applying the addition of <span class=\"math-container\">$c$</span>, finally returning the final result <span class=\"math-container\">$ab+c$</span> with a <em>single</em> rounding. This operation is supported in many programming environments as a function <code>fma()</code> for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.</p>\n<p>However, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to <em>approximately</em> emulate it by computing <span class=\"math-container\">$ab+c$</span> at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.</p>\n<p>With FMA support, one computes <span class=\"math-container\">$\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$</span>.</p>\n", "answer_id": 45293, "answer_text": "An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.\n\n\n\n\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.\n\n\n\n\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.\n\n\n\n\nHowever, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.\n\n\n\n\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.", "answer_url": "https://scicomp.stackexchange.com/a/45293", "author": "njuffa", "author_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-26T23:33:21+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "njuffa", "profile_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "user_type": "registered"}, "created_at": "2025-11-26T23:33:21+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "B6ACA9A9-61E5-4827-8876-77505A1EE621", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B6ACA9A9-61E5-4827-8876-77505A1EE621/view-source"}], "score": 4, "updated_at": "2025-11-26T23:33:21+00:00"}, {"answer_html": "<p>One idea would be to use part of the series expansion of <span class=\"math-container\">$sin(x)$</span> for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.</p>\n<p>That way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of <span class=\"math-container\">$sin(x)$</span> as before.</p>\n<p><span class=\"math-container\">\\begin{align}\n\\sin(x) &amp;= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &amp;= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}</span></p>\n<p>Note that the expansion looses precision the further away you are from 0.</p>\n", "answer_id": 45294, "answer_text": "One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.\n\n\n\n\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.\n\n\n\n\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}\n\n\n\n\nNote that the expansion looses precision the further away you are from 0.", "answer_url": "https://scicomp.stackexchange.com/a/45294", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T07:31:18+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:31:18+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "968C67F8-16E6-40D8-80A4-8E5335D3FC2C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/968C67F8-16E6-40D8-80A4-8E5335D3FC2C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:36:23+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "1885B799-B6E4-4653-BEFB-37E50B86F7E6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/1885B799-B6E4-4653-BEFB-37E50B86F7E6/view-source"}], "score": 2, "updated_at": "2025-11-27T07:36:23+00:00"}, {"answer_html": "<p>Given the recurrence\n<span class=\"math-container\">$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$</span></p>\n<p>We can use the <a href=\"https://en.wikipedia.org/wiki/Chebyshev_polynomials\" rel=\"noreferrer\">Chebyshev polynomial</a> of the second kind:\n<span class=\"math-container\">$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$</span></p>\n<p>Plugging <span class=\"math-container\">$n = k-1$</span> into this definition gives\n<span class=\"math-container\">$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$</span></p>\n<p>Therefore, the iteration can be written equivalently as\n<span class=\"math-container\">$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$</span>\nwith\n<span class=\"math-container\">$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$</span></p>\n<p>and</p>\n<p><span class=\"math-container\">$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$</span></p>\n<p>Therefore, the new iteration can be written as\n<span class=\"math-container\">$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$</span></p>\n<p>where <span class=\"math-container\">$P_m$</span> is the polynomial\n<span class=\"math-container\">$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$</span></p>\n<p>So instead of computing <span class=\"math-container\">$\\sin(k x_n)$</span> for every <span class=\"math-container\">$k$</span>, we can:</p>\n<ul>\n<li>Compute <span class=\"math-container\">$s = \\sin(x_n)$</span> once,</li>\n<li>Compute <span class=\"math-container\">$c = \\cos(x_n)$</span> once,</li>\n<li>Evaluate the polynomial <span class=\"math-container\">$P_m(c)$</span>.</li>\n</ul>\n<h2>Example</h2>\n<p>We start from the Chebyshev representation for <span class=\"math-container\">$m=5$</span>:\n<span class=\"math-container\">$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$</span>\nwith\n<span class=\"math-container\">$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$</span>\nand\n<span class=\"math-container\">$$\n\\begin{aligned}\nU_0(t) &amp;= 1,\\\\\nU_1(t) &amp;= 2t,\\\\\nU_2(t) &amp;= 4t^2 - 1,\\\\\nU_3(t) &amp;= 8t^3 - 4t,\\\\\nU_4(t) &amp;= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$</span></p>\n<p>Thus\n<span class=\"math-container\">$$\n\\begin{aligned}\nP_5(t)\n&amp;= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&amp;= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$</span></p>\n<p>Simplifying each term:\n<span class=\"math-container\">$$\n\\begin{aligned}\nP_5(t)\n&amp;= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&amp;= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$</span></p>\n<p>Now collect like powers of <span class=\"math-container\">$t$</span>.</p>\n<p><span class=\"math-container\">$t^4$</span> term:\n<span class=\"math-container\">$$\n\\frac{8}{315}t^4.\n$$</span></p>\n<p><span class=\"math-container\">$t^3$</span> term:\n<span class=\"math-container\">$$\n\\frac{10}{63}t^3.\n$$</span></p>\n<p><span class=\"math-container\">$t^2$</span> term:\n<span class=\"math-container\">$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$</span></p>\n<p><span class=\"math-container\">$t^1$</span> term:\n<span class=\"math-container\">$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$</span></p>\n<p>Constant term:\n<span class=\"math-container\">$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$</span></p>\n<p>So we obtain\n<span class=\"math-container\">$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$</span></p>\n<p>Factoring out <span class=\"math-container\">$\\frac{1}{315}$</span> gives the compact form\n<span class=\"math-container\">$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$</span></p>\n<h2>Test Case</h2>\n<p>For <span class=\"math-container\">$m = 5$</span> we have\n<span class=\"math-container\">$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$</span>\nand the iteration\n<span class=\"math-container\">$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$</span></p>\n<pre><code>from mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n &quot;&quot;&quot;\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n &quot;&quot;&quot;\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(&quot;Approximate pi (m=5):&quot;)\nprint(mp.nstr(x, 1000))\nprint(f&quot;\\nTime Taken: {end - start:.6f} seconds&quot;)\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(&quot;\\nError x - pi:&quot;)\nprint(mp.nstr(err, 5))\n</code></pre>\n<hr />\n<p>Approximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199</p>\n<p>Time Taken: 0.001180 seconds</p>\n<p>Error x - pi:\n0.0</p>\n", "answer_id": 45295, "answer_text": "Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$\n\n\n\n\nWe can use the Chebyshev polynomial (https://en.wikipedia.org/wiki/Chebyshev_polynomials) of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$\n\n\n\n\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$\n\n\n\n\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$\n\n\n\n\nand\n\n\n\n\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$\n\n\n\n\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:\n\n\n\n\n\nCompute $s = \\sin(x_n)$ once,\n\n\n\n\nCompute $c = \\cos(x_n)$ once,\n\n\n\n\nEvaluate the polynomial $P_m(c)$.\n\n\n\n\n\nExample\n\n\n\n\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$\n\n\n\n\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$\n\n\n\n\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$\n\n\n\n\nNow collect like powers of $t$.\n\n\n\n\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$\n\n\n\n\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$\n\n\n\n\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$\n\n\n\n\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$\n\n\n\n\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$\n\n\n\n\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$\n\n\n\n\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$\n\n\n\n\nTest Case\n\n\n\n\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n\n\n\n\n\n\n\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199\n\n\n\n\nTime Taken: 0.001180 seconds\n\n\n\n\nError x - pi:\n0.0", "answer_url": "https://scicomp.stackexchange.com/a/45295", "author": "vengy", "author_url": "https://scicomp.stackexchange.com/users/56070/vengy", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T16:01:03+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:01:03+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "12F528C5-3339-4BD9-82C4-1F98C0E30ABD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F528C5-3339-4BD9-82C4-1F98C0E30ABD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:46:02+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "94F6BA8F-8639-48FE-844B-374EC8092EC7", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/94F6BA8F-8639-48FE-844B-374EC8092EC7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T17:19:25+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C72508F8-E2C5-4479-B135-70BE30A2F07C", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C72508F8-E2C5-4479-B135-70BE30A2F07C/view-source"}], "score": 7, "updated_at": "2025-11-27T17:19:25+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Chebyshev_polynomials"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:44.584971+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json", "raw_sha256": "27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "vengy", "question_author_url": "https://scicomp.stackexchange.com/users/56070/vengy", "question_author_user_type": "registered", "question_created_at": "2025-11-26T20:12:50+00:00", "question_html": "<p>I have this recurrence formula for <span class=\"math-container\">$\\pi$</span> with convergence order <span class=\"math-container\">$2m+1$</span>:</p>\n<p><span class=\"math-container\">$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$</span></p>\n<p>For example, let <span class=\"math-container\">$m=2$</span>. The recurrence is:\n<span class=\"math-container\">$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$</span></p>\n<p>After four iterations, <span class=\"math-container\">$\\pi$</span> is accurate to <span class=\"math-container\">$761$</span> digits:</p>\n<p><em><strong>3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134</strong></em>3082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131</p>\n<pre class=\"lang-py prettyprint-override\"><code>from mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(&quot;Approximate pi:&quot;, mp.nstr(x, 1000))\nprint(f&quot;Time Taken: {end - start:.6f} seconds&quot;)\n</code></pre>\n<p>However, evaluating <span class=\"math-container\">$\\sin(k x_n)$</span> at high precision becomes very slow, especially for large <span class=\"math-container\">$m$</span>.</p>\n<h2>Question</h2>\n<p>Are there efficient approximations or methods for computing <span class=\"math-container\">$\\sin(k x_n)$</span> in iterative algorithms?</p>\n<h2>Update</h2>\n<p>Based on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of <span class=\"math-container\">$\\sin$</span>, one of <span class=\"math-container\">$\\cos$</span>, and a polynomial\nevaluation:</p>\n<p><span class=\"math-container\">$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$</span></p>\n<p>Thanks!</p>\n", "question_id": 45291, "question_license": "CC BY-SA 4.0", "question_score": 6, "question_text": "I have this recurrence formula for $\\pi$ with convergence order $2m+1$:\n\n\n\n\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$\n\n\n\n\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$\n\n\n\n\nAfter four iterations, $\\pi$ is accurate to $761$ digits:\n\n\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n\n\n\n\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.\n\n\n\n\nQuestion\n\n\n\n\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?\n\n\n\n\nUpdate\n\n\n\n\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:\n\n\n\n\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$\n\n\n\n\nThanks!", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-26T20:12:50+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "E62E0A8C-8E01-4C14-B7C2-285A89EF1CC1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E62E0A8C-8E01-4C14-B7C2-285A89EF1CC1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-28T14:23:44+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "38B727A1-9571-4258-B34C-572EA2A4CA69", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/38B727A1-9571-4258-B34C-572EA2A4CA69/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-12-27T13:30:00+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "26017B5A-7A85-4984-8B51-2083CED200D4", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/26017B5A-7A85-4984-8B51-2083CED200D4/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms", "split": "test", "split_group": "1bfd52fa7b070e0b5559d8e3ecd78760d9854e9302a5ee1988f94d4b3224295f", "tags": ["optimization", "numerics"], "thread_id": "scicomp:45291", "title": "Efficient computation of $\\sin(k x_n)$ in iterative algorithms"}}
{"accepted_answer": {"answer_html": "<p>Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n<span class=\"math-container\">$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$</span>\nwhich is correct, but I thought that the parameter <span class=\"math-container\">$g$</span> was the same as the parameter <span class=\"math-container\">$h$</span>, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n<span class=\"math-container\">$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$</span>\nso, <span class=\"math-container\">$g$</span> is not <span class=\"math-container\">$h$</span>, it is <span class=\"math-container\">$g=h/J$</span>. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used <span class=\"math-container\">$h$</span> as a parameter by correctly passing <span class=\"math-container\">$g \\to g=h/J$</span>, then I would get the diagram I expected:\n<a href=\"https://i.sstatic.net/BHts2usz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/BHts2usz.png\" alt=\"Expected phase diagram for magnetization\" /></a></p>\n", "answer_id": 45345, "answer_text": "Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n[image: Expected phase diagram for magnetization; source: https://i.sstatic.net/BHts2usz.png] (https://i.sstatic.net/BHts2usz.png)", "answer_url": "https://scicomp.stackexchange.com/a/45345", "author": "Andreas Christophilopoulos", "author_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-20T08:42:22+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45344, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Andreas Christophilopoulos", "profile_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "user_type": "registered"}, "created_at": "2026-01-20T08:42:22+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "48A405D5-BF35-4435-851C-8D73362C5805", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/48A405D5-BF35-4435-851C-8D73362C5805/view-source"}], "score": 3, "updated_at": "2026-01-20T08:42:22+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "using MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n H = transverse_field_ising(; J=J, g=g)\n groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n return abs(expectation_value(groundstate, 1 => σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel=\"J\", ylabel=\"g\", title=\"Magnetization M(g, J)\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45344, "sha256": "6d0c731a6161c6549a7907a370d22e309f0185f732b83d7612acffee8fc728e4", "source_url": "https://scicomp.stackexchange.com/questions/45344/dmrg-returns-weird-results-for-the-tfim-ground-state-magnetization"}], "other_answers": [], "product": "code_qa", "question": "If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.\n\n\n\n\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5<g<0.5$. In other words, it doesn't matter how strong or weak $J$ is (as long as it is positive), there is always ferromagnetic order as long as $|g|$ is smaller than $0.5$, and $M=0$ everywhere else.\n\n\n\n\nThis is a very odd result that doesn't make sense to me, so I am inclined to believe there is something wrong with my computational methods. I attach the code I used and the diagram that it produced. My code closely mirrors the example from MPSKit.jl's github (https://github.com/QuantumKitHub/MPSKit.jl):\n\n\n\n\nusing MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n H = transverse_field_ising(; J=J, g=g)\n groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n return abs(expectation_value(groundstate, 1 => σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel=\"J\", ylabel=\"g\", title=\"Magnetization M(g, J)\")\n\n\n\n\n\nAnd here is the resulting heatmap:\n\n\n\n\n[image: heatmap; source: https://i.sstatic.net/82wynbiT.png] (https://i.sstatic.net/82wynbiT.png)\n\n\n\n\nI tried increasing the bond dimension $D$, but it did nothing. Now, this is VUMPS, but I got the same result more or less with finite $L$ DMRG. I'm at my wit's end! Any help would be appreciated.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45344", "selected_answer": {"answer_html": "<p>Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n<span class=\"math-container\">$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$</span>\nwhich is correct, but I thought that the parameter <span class=\"math-container\">$g$</span> was the same as the parameter <span class=\"math-container\">$h$</span>, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n<span class=\"math-container\">$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$</span>\nso, <span class=\"math-container\">$g$</span> is not <span class=\"math-container\">$h$</span>, it is <span class=\"math-container\">$g=h/J$</span>. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used <span class=\"math-container\">$h$</span> as a parameter by correctly passing <span class=\"math-container\">$g \\to g=h/J$</span>, then I would get the diagram I expected:\n<a href=\"https://i.sstatic.net/BHts2usz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/BHts2usz.png\" alt=\"Expected phase diagram for magnetization\" /></a></p>\n", "answer_id": 45345, "answer_text": "Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n[image: Expected phase diagram for magnetization; source: https://i.sstatic.net/BHts2usz.png] (https://i.sstatic.net/BHts2usz.png)", "answer_url": "https://scicomp.stackexchange.com/a/45345", "author": "Andreas Christophilopoulos", "author_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-20T08:42:22+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45344, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Andreas Christophilopoulos", "profile_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "user_type": "registered"}, "created_at": "2026-01-20T08:42:22+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "48A405D5-BF35-4435-851C-8D73362C5805", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/48A405D5-BF35-4435-851C-8D73362C5805/view-source"}], "score": 3, "updated_at": "2026-01-20T08:42:22+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 45345, "answers": [{"answer_html": "<p>Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n<span class=\"math-container\">$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$</span>\nwhich is correct, but I thought that the parameter <span class=\"math-container\">$g$</span> was the same as the parameter <span class=\"math-container\">$h$</span>, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n<span class=\"math-container\">$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$</span>\nso, <span class=\"math-container\">$g$</span> is not <span class=\"math-container\">$h$</span>, it is <span class=\"math-container\">$g=h/J$</span>. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used <span class=\"math-container\">$h$</span> as a parameter by correctly passing <span class=\"math-container\">$g \\to g=h/J$</span>, then I would get the diagram I expected:\n<a href=\"https://i.sstatic.net/BHts2usz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/BHts2usz.png\" alt=\"Expected phase diagram for magnetization\" /></a></p>\n", "answer_id": 45345, "answer_text": "Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n[image: Expected phase diagram for magnetization; source: https://i.sstatic.net/BHts2usz.png] (https://i.sstatic.net/BHts2usz.png)", "answer_url": "https://scicomp.stackexchange.com/a/45345", "author": "Andreas Christophilopoulos", "author_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-20T08:42:22+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45344, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Andreas Christophilopoulos", "profile_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "user_type": "registered"}, "created_at": "2026-01-20T08:42:22+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "48A405D5-BF35-4435-851C-8D73362C5805", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/48A405D5-BF35-4435-851C-8D73362C5805/view-source"}], "score": 3, "updated_at": "2026-01-20T08:42:22+00:00"}], "domain": "computational_science", "external_links": ["https://github.com/QuantumKitHub/MPSKit.jl", "https://i.sstatic.net/82wynbiT.png", "https://i.sstatic.net/BHts2usz.png"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:44.584971+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json", "raw_sha256": "27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Andreas Christophilopoulos", "question_author_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "question_author_user_type": "registered", "question_created_at": "2026-01-19T13:26:44+00:00", "question_html": "<p>If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for <span class=\"math-container\">$|J/g|&gt;1$</span> with positive <span class=\"math-container\">$J$</span> (here <span class=\"math-container\">$J$</span> is the coupling and <span class=\"math-container\">$g$</span> the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.</p>\n<p>I tried to run a DMRG simulation, and instead of this behavior, the <span class=\"math-container\">$M=1$</span> phase appears for <span class=\"math-container\">$J&gt;0$</span> and <span class=\"math-container\">$-0.5&lt;g&lt;0.5$</span>. In other words, it doesn't matter how strong or weak <span class=\"math-container\">$J$</span> is (as long as it is positive), there is always ferromagnetic order as long as <span class=\"math-container\">$|g|$</span> is smaller than <span class=\"math-container\">$0.5$</span>, and <span class=\"math-container\">$M=0$</span> everywhere else.</p>\n<p>This is a very odd result that doesn't make sense to me, so I am inclined to believe there is something wrong with my computational methods. I attach the code I used and the diagram that it produced. My code <a href=\"https://github.com/QuantumKitHub/MPSKit.jl\" rel=\"nofollow noreferrer\">closely mirrors the example from MPSKit.jl's github</a>:</p>\n<pre class=\"lang-julia prettyprint-override\"><code>using MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n H = transverse_field_ising(; J=J, g=g)\n groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n return abs(expectation_value(groundstate, 1 =&gt; σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel=&quot;J&quot;, ylabel=&quot;g&quot;, title=&quot;Magnetization M(g, J)&quot;)\n</code></pre>\n<p>And here is the resulting heatmap:</p>\n<p><a href=\"https://i.sstatic.net/82wynbiT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/82wynbiT.png\" alt=\"heatmap\" /></a></p>\n<p>I tried increasing the bond dimension <span class=\"math-container\">$D$</span>, but it did nothing. Now, this is VUMPS, but I got the same result more or less with finite <span class=\"math-container\">$L$</span> DMRG. I'm at my wit's end! Any help would be appreciated.</p>\n", "question_id": 45344, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.\n\n\n\n\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5<g<0.5$. In other words, it doesn't matter how strong or weak $J$ is (as long as it is positive), there is always ferromagnetic order as long as $|g|$ is smaller than $0.5$, and $M=0$ everywhere else.\n\n\n\n\nThis is a very odd result that doesn't make sense to me, so I am inclined to believe there is something wrong with my computational methods. I attach the code I used and the diagram that it produced. My code closely mirrors the example from MPSKit.jl's github (https://github.com/QuantumKitHub/MPSKit.jl):\n\n\n\n\nusing MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n H = transverse_field_ising(; J=J, g=g)\n groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n return abs(expectation_value(groundstate, 1 => σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel=\"J\", ylabel=\"g\", title=\"Magnetization M(g, J)\")\n\n\n\n\n\nAnd here is the resulting heatmap:\n\n\n\n\n[image: heatmap; source: https://i.sstatic.net/82wynbiT.png] (https://i.sstatic.net/82wynbiT.png)\n\n\n\n\nI tried increasing the bond dimension $D$, but it did nothing. Now, this is VUMPS, but I got the same result more or less with finite $L$ DMRG. I'm at my wit's end! Any help would be appreciated.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Andreas Christophilopoulos", "profile_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "user_type": "registered"}, "created_at": "2026-01-19T13:26:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9A79D116-A5E8-4995-9CDC-86061D8C4F49", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9A79D116-A5E8-4995-9CDC-86061D8C4F49/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Andreas Christophilopoulos", "profile_url": "https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos", "user_type": "registered"}, "created_at": "2026-01-19T14:39:59+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "17008AF4-25DE-4356-9CA5-A73B1EB6B8C6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/17008AF4-25DE-4356-9CA5-A73B1EB6B8C6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2026-01-21T20:16:26+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "D0303D22-34B4-4CE9-B587-04FCADC6EBF4", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D0303D22-34B4-4CE9-B587-04FCADC6EBF4/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45344/dmrg-returns-weird-results-for-the-tfim-ground-state-magnetization", "split": "test", "split_group": "66f5c7bb70e6d18950c8f6dfdfb104814d80069b9f3004b754c7ecddd2ef175d", "tags": ["quantum-mechanics", "julia"], "thread_id": "scicomp:45344", "title": "DMRG returns weird results for the TFIM ground state magnetization"}}