{"accepted_answer": {"answer_html": "
Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.
\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into "main" effects and pure interaction? If you fit the model as
\nm2 <- gam(\n y ~ s(subject, bs = "re") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = "REML"\n)\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.
\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the "main" effect of $z$) is doing is pulling the interaction surface up or down a bit.
\n", "answer_id": 676825, "answer_text": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.\n\n\n\n\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into \"main\" effects and pure interaction? If you fit the model as\n\n\n\n\nm2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n\n\n\n\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.\n\n\n\n\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the \"main\" effect of $z$) is doing is pulling the interaction surface up or down a bit.", "answer_url": "https://stats.stackexchange.com/a/676825", "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-10T13:46:19+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": 676821, "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-10T13:46:19+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "F2BC6152-84F6-49C2-A240-5C8FBED68528", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F2BC6152-84F6-49C2-A240-5C8FBED68528/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-10T14:27:48+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "49FD277A-D37F-425E-AE90-F3246031F5A9", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49FD277A-D37F-425E-AE90-F3246031F5A9/view-source"}], "score": 3, "updated_at": "2026-08-10T14:27:48+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676821, "sha256": "26b22c75d5bb179af3f2834caa82225c7019e801c4737401abbe51f12f71a0af", "source_url": "https://stats.stackexchange.com/questions/676821/should-a-covariates-main-effect-be-dropped-when-its-totally-confounded-concur"}, {"block_index": 1, "code_text": "library(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = \"re\") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676821, "sha256": "bbec1ef160e17f38db311ea10d2a766fc7f04eb5dc7ff5b70bcf557a69383b95", "source_url": "https://stats.stackexchange.com/questions/676821/should-a-covariates-main-effect-be-dropped-when-its-totally-confounded-concur"}, {"block_index": 0, "code_text": "m2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676825, "sha256": "d85eb81e68d8cddcd5c8461d048625abd5d44fc3710f416fc52b5b7acd084030", "source_url": "https://stats.stackexchange.com/a/676825"}], "other_answers": [], "product": "code_qa", "question": "I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.\n\n\n\n\n\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n\n\n\n\n\nconcurvity(m, full = FALSE)$estimate shows s(subject) and s(z) (z's own main effect) at 1.000 in one direction, confirming total non-identifiability — since z has zero within-subject variation, s(subject, bs=\"re\") can fully reproduce whatever flat contribution s(z) would estimate.\n\n\n\n\nMy current approach is to drop s(z) entirely and keep only ti(time, z), on the reasoning that ti()'s own identifiability constraints make it self-contained regardless of whether the (non-identifiable) main effect is present — interpreting the retained term as \"how the association between z and y changes over time,\" while treating any claim about z's flat/average association as unrecoverable given this random-effect structure.\n\n\n\n\nReproducible example:\n\n\n\n\nlibrary(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = \"re\") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n\n\n\n\n\nQuestions:\n\n\n\n\n\nIs dropping z's main effect while retaining ti(time, z) a way to handle this, or is there a better-established approach?\n\n\n\n\nDoes ti(time, z)'s own estimate depend in any way on whether the non-identifiable main effect is included or excluded from the model?\n\n\n\n\n\nMany thanks", "record_id": "Scientific-Code-and-Analysis-QA:stats:676821", "selected_answer": {"answer_html": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.
\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into "main" effects and pure interaction? If you fit the model as
\nm2 <- gam(\n y ~ s(subject, bs = "re") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = "REML"\n)\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.
\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the "main" effect of $z$) is doing is pulling the interaction surface up or down a bit.
\n", "answer_id": 676825, "answer_text": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.\n\n\n\n\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into \"main\" effects and pure interaction? If you fit the model as\n\n\n\n\nm2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n\n\n\n\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.\n\n\n\n\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the \"main\" effect of $z$) is doing is pulling the interaction surface up or down a bit.", "answer_url": "https://stats.stackexchange.com/a/676825", "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-10T13:46:19+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": 676821, "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-10T13:46:19+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "F2BC6152-84F6-49C2-A240-5C8FBED68528", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F2BC6152-84F6-49C2-A240-5C8FBED68528/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-10T14:27:48+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "49FD277A-D37F-425E-AE90-F3246031F5A9", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49FD277A-D37F-425E-AE90-F3246031F5A9/view-source"}], "score": 3, "updated_at": "2026-08-10T14:27:48+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 676825, "answers": [{"answer_html": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.
\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into "main" effects and pure interaction? If you fit the model as
\nm2 <- gam(\n y ~ s(subject, bs = "re") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = "REML"\n)\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.
\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the "main" effect of $z$) is doing is pulling the interaction surface up or down a bit.
\n", "answer_id": 676825, "answer_text": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.\n\n\n\n\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into \"main\" effects and pure interaction? If you fit the model as\n\n\n\n\nm2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n\n\n\n\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.\n\n\n\n\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the \"main\" effect of $z$) is doing is pulling the interaction surface up or down a bit.", "answer_url": "https://stats.stackexchange.com/a/676825", "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-10T13:46:19+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": 676821, "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-10T13:46:19+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "F2BC6152-84F6-49C2-A240-5C8FBED68528", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F2BC6152-84F6-49C2-A240-5C8FBED68528/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-10T14:27:48+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "49FD277A-D37F-425E-AE90-F3246031F5A9", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49FD277A-D37F-425E-AE90-F3246031F5A9/view-source"}], "score": 3, "updated_at": "2026-08-10T14:27:48+00:00"}], "domain": "statistics", "external_links": [], "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": "Elara", "question_author_url": "https://stats.stackexchange.com/users/515316/elara", "question_author_user_type": "registered", "question_created_at": "2026-08-10T10:16:49+00:00", "question_html": "I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.
\n\nm <- gam(y ~ s(time) + s(subject, bs = "re") + s(z) + ti(time, z), data = dat)\n\nconcurvity(m, full = FALSE)$estimate shows s(subject) and s(z) (z's own main effect) at 1.000 in one direction, confirming total non-identifiability — since z has zero within-subject variation, s(subject, bs="re") can fully reproduce whatever flat contribution s(z) would estimate.
\nMy current approach is to drop s(z) entirely and keep only ti(time, z), on the reasoning that ti()'s own identifiability constraints make it self-contained regardless of whether the (non-identifiable) main effect is present — interpreting the retained term as "how the association between z and y changes over time," while treating any claim about z's flat/average association as unrecoverable given this random-effect structure.
\nReproducible example:
\nlibrary(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = "re") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n\nQuestions:
\nMany thanks
\n", "question_id": 676821, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.\n\n\n\n\n\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n\n\n\n\n\nconcurvity(m, full = FALSE)$estimate shows s(subject) and s(z) (z's own main effect) at 1.000 in one direction, confirming total non-identifiability — since z has zero within-subject variation, s(subject, bs=\"re\") can fully reproduce whatever flat contribution s(z) would estimate.\n\n\n\n\nMy current approach is to drop s(z) entirely and keep only ti(time, z), on the reasoning that ti()'s own identifiability constraints make it self-contained regardless of whether the (non-identifiable) main effect is present — interpreting the retained term as \"how the association between z and y changes over time,\" while treating any claim about z's flat/average association as unrecoverable given this random-effect structure.\n\n\n\n\nReproducible example:\n\n\n\n\nlibrary(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = \"re\") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n\n\n\n\n\nQuestions:\n\n\n\n\n\nIs dropping z's main effect while retaining ti(time, z) a way to handle this, or is there a better-established approach?\n\n\n\n\nDoes ti(time, z)'s own estimate depend in any way on whether the non-identifiable main effect is included or excluded from the model?\n\n\n\n\n\nMany thanks", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Elara", "profile_url": "https://stats.stackexchange.com/users/515316/elara", "user_type": "registered"}, "created_at": "2026-08-10T10:16:49+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "E53E485F-D0B2-4D71-A71D-49FBF67B610C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E53E485F-D0B2-4D71-A71D-49FBF67B610C/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-10T18:21:03+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "87843E03-0788-44C4-AC39-D6D27DF85636", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/87843E03-0788-44C4-AC39-D6D27DF85636/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676821/should-a-covariates-main-effect-be-dropped-when-its-totally-confounded-concur", "split": "train", "split_group": "a67c79324cd462d3f9e765754df2a7a00495b44528883bd5734192a2b6a73ff1", "tags": ["interaction", "generalized-additive-model", "mgcv", "identifiability", "concurvity"], "thread_id": "stats:676821", "title": "Should a covariate's main effect be dropped when it's totally confounded (concurvity = 1) with a random intercept in a repeated-measures GAMM?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676851, "sha256": "8fb2dac783667ca934aace318bc1d59d4d831af318b2b8cc2e7524964863b77a", "source_url": "https://stats.stackexchange.com/a/676851"}, {"block_index": 2, "code_text": "set.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676851, "sha256": "0a411abb79864630d059298e04f1470aba7ba285a921cba1d89b9c7066255849", "source_url": "https://stats.stackexchange.com/a/676851"}], "other_answers": [], "product": "code_qa", "question": "The following is a multivariate Student's t distribution\n$$ p_{\\sigma^2}(\\mathrm{x})= {\\displaystyle {N_{\\nu,\\sigma^2}}\\left[1+\\frac{1}{\\nu\\sigma^2}\\sum_{i=1}^nx_i^2\\right]^{-(\\nu +n)/2}}, \\;\\mathrm{x}=[x_1,\\cdots,x_n]^{\\top}\\in \\mathbb{R}^n,\\;\\nu>2,$$ where $N_{\\nu,\\sigma^2}=\\frac {\\Gamma \\left[(\\nu +n)/2\\right]}{\\Gamma (\\nu /2)\\nu ^{n/2} \\pi^{n/2}{\\sigma}^{n}}.$ I am struggling to find the higher-order moments $E[X^{\\top}X]$, $E[X^{\\top}X(X^{\\top}X)^{\\top}]$. Is there a way to get these quantities?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676824", "selected_answer": {"answer_html": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.
\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).
\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be
\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$
\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,
\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$
\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),
\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$
\n
Otherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives
\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$
\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it
\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$
\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$
\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$
\n(a Beta function, arising e.g. from normalizing a Beta prime distribution).
\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$
\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows
\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$
\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence
\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$
\n
(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)
\nAs a check, we recover the normalizing constant as the zeroth moment,
\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$
\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$
\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing
\n$$\\kappa = k_1+k_2+\\cdots+k_n$$
\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that
\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$
\n
The question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.
\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.
#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.
For example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as
\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:
set.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.
\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.
\n", "answer_id": 676851, "answer_text": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.\n\n\n\n\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).\n\n\n\n\nInitial simplification\n\n\n\n\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be\n\n\n\n\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$\n\n\n\n\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$\n\n\n\n\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),\n\n\n\n\n\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$\n\n\n\n\n\n\n\nOtherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$\n\n\n\n\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it\n\n\n\n\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$\n\n\n\n\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$\n\n\n\n\nThe key formula\n\n\n\n\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$\n\n\n\n\n(a Beta function, arising e.g. from normalizing a Beta prime distribution (https://en.wikipedia.org/wiki/Beta_prime_distribution#Generalization)).\n\n\n\n\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$\n\n\n\n\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows\n\n\n\n\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$\n\n\n\n\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence\n\n\n\n\n\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$\n\n\n\n\n\n\n\n(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)\n\n\n\n\nAs a check, we recover the normalizing constant as the zeroth moment,\n\n\n\n\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$\n\n\n\n\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$\n\n\n\n\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing\n\n\n\n\n$$\\kappa = k_1+k_2+\\cdots+k_n$$\n\n\n\n\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that\n\n\n\n\n\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$\n\n\n\n\n\n\n\nThe question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.\n\n\n\n\nImplementation and testing\n\n\n\n\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.\n\n\n\n\n#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\n\n\n\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.\n\n\n\n\nFor example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as\n\n\n\n\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\n\n\n\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:\n\n\n\n\nset.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\n\n\n\n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.\n\n\n\n\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.", "answer_url": "https://stats.stackexchange.com/a/676851", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T15:28:16+00:00", "is_accepted": false, "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": 676824, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-08-12T15:28:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "C9CDAB77-2DD2-446E-837A-211128FD0EE9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C9CDAB77-2DD2-446E-837A-211128FD0EE9/view-source"}], "score": 2, "updated_at": "2026-08-12T15:28:16+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.
\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).
\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be
\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$
\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,
\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$
\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),
\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$
\n
Otherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives
\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$
\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it
\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$
\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$
\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$
\n(a Beta function, arising e.g. from normalizing a Beta prime distribution).
\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$
\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows
\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$
\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence
\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$
\n
(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)
\nAs a check, we recover the normalizing constant as the zeroth moment,
\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$
\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$
\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing
\n$$\\kappa = k_1+k_2+\\cdots+k_n$$
\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that
\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$
\n
The question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.
\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.
#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.
For example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as
\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:
set.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.
\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.
\n", "answer_id": 676851, "answer_text": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.\n\n\n\n\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).\n\n\n\n\nInitial simplification\n\n\n\n\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be\n\n\n\n\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$\n\n\n\n\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$\n\n\n\n\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),\n\n\n\n\n\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$\n\n\n\n\n\n\n\nOtherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$\n\n\n\n\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it\n\n\n\n\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$\n\n\n\n\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$\n\n\n\n\nThe key formula\n\n\n\n\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$\n\n\n\n\n(a Beta function, arising e.g. from normalizing a Beta prime distribution (https://en.wikipedia.org/wiki/Beta_prime_distribution#Generalization)).\n\n\n\n\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$\n\n\n\n\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows\n\n\n\n\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$\n\n\n\n\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence\n\n\n\n\n\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$\n\n\n\n\n\n\n\n(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)\n\n\n\n\nAs a check, we recover the normalizing constant as the zeroth moment,\n\n\n\n\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$\n\n\n\n\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$\n\n\n\n\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing\n\n\n\n\n$$\\kappa = k_1+k_2+\\cdots+k_n$$\n\n\n\n\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that\n\n\n\n\n\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$\n\n\n\n\n\n\n\nThe question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.\n\n\n\n\nImplementation and testing\n\n\n\n\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.\n\n\n\n\n#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\n\n\n\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.\n\n\n\n\nFor example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as\n\n\n\n\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\n\n\n\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:\n\n\n\n\nset.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\n\n\n\n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.\n\n\n\n\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.", "answer_url": "https://stats.stackexchange.com/a/676851", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T15:28:16+00:00", "is_accepted": false, "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": 676824, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-08-12T15:28:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "C9CDAB77-2DD2-446E-837A-211128FD0EE9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C9CDAB77-2DD2-446E-837A-211128FD0EE9/view-source"}], "score": 2, "updated_at": "2026-08-12T15:28:16+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Beta_prime_distribution#Generalization"], "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": "SATYA", "question_author_url": "https://stats.stackexchange.com/users/375640/satya", "question_author_user_type": "registered", "question_created_at": "2026-08-10T13:38:12+00:00", "question_html": "The following is a multivariate Student's t distribution\n$$ p_{\\sigma^2}(\\mathrm{x})= {\\displaystyle {N_{\\nu,\\sigma^2}}\\left[1+\\frac{1}{\\nu\\sigma^2}\\sum_{i=1}^nx_i^2\\right]^{-(\\nu +n)/2}}, \\;\\mathrm{x}=[x_1,\\cdots,x_n]^{\\top}\\in \\mathbb{R}^n,\\;\\nu>2,$$ where $N_{\\nu,\\sigma^2}=\\frac {\\Gamma \\left[(\\nu +n)/2\\right]}{\\Gamma (\\nu /2)\\nu ^{n/2} \\pi^{n/2}{\\sigma}^{n}}.$ I am struggling to find the higher-order moments $E[X^{\\top}X]$, $E[X^{\\top}X(X^{\\top}X)^{\\top}]$. Is there a way to get these quantities?
\n", "question_id": 676824, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "The following is a multivariate Student's t distribution\n$$ p_{\\sigma^2}(\\mathrm{x})= {\\displaystyle {N_{\\nu,\\sigma^2}}\\left[1+\\frac{1}{\\nu\\sigma^2}\\sum_{i=1}^nx_i^2\\right]^{-(\\nu +n)/2}}, \\;\\mathrm{x}=[x_1,\\cdots,x_n]^{\\top}\\in \\mathbb{R}^n,\\;\\nu>2,$$ where $N_{\\nu,\\sigma^2}=\\frac {\\Gamma \\left[(\\nu +n)/2\\right]}{\\Gamma (\\nu /2)\\nu ^{n/2} \\pi^{n/2}{\\sigma}^{n}}.$ I am struggling to find the higher-order moments $E[X^{\\top}X]$, $E[X^{\\top}X(X^{\\top}X)^{\\top}]$. Is there a way to get these quantities?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "SATYA", "profile_url": "https://stats.stackexchange.com/users/375640/satya", "user_type": "registered"}, "created_at": "2026-08-10T13:38:12+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "FE80823D-F8D4-4BF7-916A-95ECE3955E38", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FE80823D-F8D4-4BF7-916A-95ECE3955E38/view-source"}, {"content_license": null, "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-08-10T13:43:33+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "09839026-A5FE-44BE-B46A-D0FCD7254AFE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09839026-A5FE-44BE-B46A-D0FCD7254AFE/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676824/higher-moments-of-multivariate-students-t-distribution", "split": "train", "split_group": "d616db2eb7c80d9bcbf195f175fdfced0ba92b76f0e66918c59a439d07fa96f0", "tags": ["mathematical-statistics", "inference", "moments", "t-distribution"], "thread_id": "stats:676824", "title": "Higher Moments of multivariate Student's t distribution"}} {"accepted_answer": {"answer_html": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$
\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$
\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.
\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.
\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.
\n", "answer_id": 676849, "answer_text": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$\n\n\n\n\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$\n\n\n\n\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Qsmelzjn.png] (https://i.sstatic.net/Qsmelzjn.png)\n\n\n\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.\n\n\n\n\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.", "answer_url": "https://stats.stackexchange.com/a/676849", "author": "Thomas Lumley", "author_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T03:14:18+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": 676842, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:14:18+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "EF5747F6-4B6A-42A4-8968-9F80C87019F6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EF5747F6-4B6A-42A4-8968-9F80C87019F6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:21:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "A9820920-337C-4445-864A-E2CE6845065B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A9820920-337C-4445-864A-E2CE6845065B/view-source"}], "score": 4, "updated_at": "2026-08-12T03:21:16+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend(\"topright\",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676842, "sha256": "6655bd907225c7526d765f76e3438c4e3188e536db6da04f4ad8037510fb01ec", "source_url": "https://stats.stackexchange.com/questions/676842/the-asymptotic-distribution-of-likelihood-ratio-statistic-when-the-null-hypothes"}], "other_answers": [], "product": "code_qa", "question": "In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.\n\n\n\n\nQuestion. Consider an $n$-dimensional parameter $\\theta= (\\theta_1, \\cdots, \\theta_n)\\in \\Theta$ where $\\Theta$ is an open subset in $\\mathbb R^n$, and the hypothesis\n$$ H_0: \\text{either }\\theta_1= c_1 \\text{ or }\\theta_2= c_2\\longleftrightarrow\nH_1:\\text{ otherwise},$$\nwhere $c_1, c_2$ are given constant.\nWhat is the asymptotic distribution of $-2 \\log\\lambda$ where $\\lambda$ is the likelihood ratio statistic, if the true model is $\\theta_1= c_1$ and $\\theta_2= c_2$?\n(Assuming all other conditions of Wilks's Theorem).\n\n\n\n\nFor example, consider $X_1,\\cdots, X_n$ are i.i.d. samples from $N(\\mu, \\sigma^2)$,\nand test if $H_0: \\text{either }\\mu=0 \\text{ or }\\sigma^2= 1$ holds.\nThen the maximum likelihood estimation is the one in $(\\mu, \\sigma^2)= (0, \\sqrt{\\frac{1}{n}\\sum_{i=1}^n X_i^2} )$ and $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$\nwhich has a larger likelihood, and from this we can compute the LR statistic $\\lambda$.\n\n\n\n\nIf, say, the model is generated under true parameter $\\mu= 1, \\sigma^2= 1$, then\nthe simulating data shows that the empirical cdf of $-2\\log\\lambda$\nand $\\chi^2_1$ are very close, which seems to suggest that $-2\\log\\lambda\\to_d\\chi^2_1$,\nand this is in fact the case, as, when the sample size tends to infinity, the probability that the MLE under $H_0$ is $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$ (which corresponds to the true parameter) will tend to $1$, so the LR statistic is the same as testing $H_0: \\sigma^2= 1$ which probability tending to $1$.\n\n\n\n\nHowever, if the true parameter is $(\\mu, \\sigma^2)= (0, 1)$, then the empirical cdf of $-2\\log\\lambda$ is no longer close to $\\chi^2_1$, as the figure below shows.\n\n\n\n\nMy question is, does $-2\\log\\lambda$ has a general asymptotic distribution in such case?\n\n\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/cWv54DMg.png] (https://i.sstatic.net/cWv54DMg.png)\n\n\n\n\n# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend(\"topright\",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))", "record_id": "Scientific-Code-and-Analysis-QA:stats:676842", "selected_answer": {"answer_html": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$
\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$
\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.
\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.
\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.
\n", "answer_id": 676849, "answer_text": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$\n\n\n\n\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$\n\n\n\n\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Qsmelzjn.png] (https://i.sstatic.net/Qsmelzjn.png)\n\n\n\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.\n\n\n\n\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.", "answer_url": "https://stats.stackexchange.com/a/676849", "author": "Thomas Lumley", "author_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T03:14:18+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": 676842, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:14:18+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "EF5747F6-4B6A-42A4-8968-9F80C87019F6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EF5747F6-4B6A-42A4-8968-9F80C87019F6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:21:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "A9820920-337C-4445-864A-E2CE6845065B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A9820920-337C-4445-864A-E2CE6845065B/view-source"}], "score": 4, "updated_at": "2026-08-12T03:21:16+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 676849, "answers": [{"answer_html": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$
\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$
\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.
\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.
\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.
\n", "answer_id": 676849, "answer_text": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$\n\n\n\n\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$\n\n\n\n\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Qsmelzjn.png] (https://i.sstatic.net/Qsmelzjn.png)\n\n\n\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.\n\n\n\n\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.", "answer_url": "https://stats.stackexchange.com/a/676849", "author": "Thomas Lumley", "author_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T03:14:18+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": 676842, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:14:18+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "EF5747F6-4B6A-42A4-8968-9F80C87019F6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EF5747F6-4B6A-42A4-8968-9F80C87019F6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:21:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "A9820920-337C-4445-864A-E2CE6845065B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A9820920-337C-4445-864A-E2CE6845065B/view-source"}], "score": 4, "updated_at": "2026-08-12T03:21:16+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/Qsmelzjn.png", "https://i.sstatic.net/cWv54DMg.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": "Asigan", "question_author_url": "https://stats.stackexchange.com/users/499652/asigan", "question_author_user_type": "registered", "question_created_at": "2026-08-11T15:31:10+00:00", "question_html": "In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.
\nQuestion. Consider an $n$-dimensional parameter $\\theta= (\\theta_1, \\cdots, \\theta_n)\\in \\Theta$ where $\\Theta$ is an open subset in $\\mathbb R^n$, and the hypothesis\n$$ H_0: \\text{either }\\theta_1= c_1 \\text{ or }\\theta_2= c_2\\longleftrightarrow\nH_1:\\text{ otherwise},$$\nwhere $c_1, c_2$ are given constant.\nWhat is the asymptotic distribution of $-2 \\log\\lambda$ where $\\lambda$ is the likelihood ratio statistic, if the true model is $\\theta_1= c_1$ and $\\theta_2= c_2$?\n(Assuming all other conditions of Wilks's Theorem).
\nFor example, consider $X_1,\\cdots, X_n$ are i.i.d. samples from $N(\\mu, \\sigma^2)$,\nand test if $H_0: \\text{either }\\mu=0 \\text{ or }\\sigma^2= 1$ holds.\nThen the maximum likelihood estimation is the one in $(\\mu, \\sigma^2)= (0, \\sqrt{\\frac{1}{n}\\sum_{i=1}^n X_i^2} )$ and $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$\nwhich has a larger likelihood, and from this we can compute the LR statistic $\\lambda$.
\nIf, say, the model is generated under true parameter $\\mu= 1, \\sigma^2= 1$, then\nthe simulating data shows that the empirical cdf of $-2\\log\\lambda$\nand $\\chi^2_1$ are very close, which seems to suggest that $-2\\log\\lambda\\to_d\\chi^2_1$,\nand this is in fact the case, as, when the sample size tends to infinity, the probability that the MLE under $H_0$ is $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$ (which corresponds to the true parameter) will tend to $1$, so the LR statistic is the same as testing $H_0: \\sigma^2= 1$ which probability tending to $1$.
\nHowever, if the true parameter is $(\\mu, \\sigma^2)= (0, 1)$, then the empirical cdf of $-2\\log\\lambda$ is no longer close to $\\chi^2_1$, as the figure below shows.
\nMy question is, does $-2\\log\\lambda$ has a general asymptotic distribution in such case?
\n# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend("topright",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))\n\n", "question_id": 676842, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.\n\n\n\n\nQuestion. Consider an $n$-dimensional parameter $\\theta= (\\theta_1, \\cdots, \\theta_n)\\in \\Theta$ where $\\Theta$ is an open subset in $\\mathbb R^n$, and the hypothesis\n$$ H_0: \\text{either }\\theta_1= c_1 \\text{ or }\\theta_2= c_2\\longleftrightarrow\nH_1:\\text{ otherwise},$$\nwhere $c_1, c_2$ are given constant.\nWhat is the asymptotic distribution of $-2 \\log\\lambda$ where $\\lambda$ is the likelihood ratio statistic, if the true model is $\\theta_1= c_1$ and $\\theta_2= c_2$?\n(Assuming all other conditions of Wilks's Theorem).\n\n\n\n\nFor example, consider $X_1,\\cdots, X_n$ are i.i.d. samples from $N(\\mu, \\sigma^2)$,\nand test if $H_0: \\text{either }\\mu=0 \\text{ or }\\sigma^2= 1$ holds.\nThen the maximum likelihood estimation is the one in $(\\mu, \\sigma^2)= (0, \\sqrt{\\frac{1}{n}\\sum_{i=1}^n X_i^2} )$ and $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$\nwhich has a larger likelihood, and from this we can compute the LR statistic $\\lambda$.\n\n\n\n\nIf, say, the model is generated under true parameter $\\mu= 1, \\sigma^2= 1$, then\nthe simulating data shows that the empirical cdf of $-2\\log\\lambda$\nand $\\chi^2_1$ are very close, which seems to suggest that $-2\\log\\lambda\\to_d\\chi^2_1$,\nand this is in fact the case, as, when the sample size tends to infinity, the probability that the MLE under $H_0$ is $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$ (which corresponds to the true parameter) will tend to $1$, so the LR statistic is the same as testing $H_0: \\sigma^2= 1$ which probability tending to $1$.\n\n\n\n\nHowever, if the true parameter is $(\\mu, \\sigma^2)= (0, 1)$, then the empirical cdf of $-2\\log\\lambda$ is no longer close to $\\chi^2_1$, as the figure below shows.\n\n\n\n\nMy question is, does $-2\\log\\lambda$ has a general asymptotic distribution in such case?\n\n\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/cWv54DMg.png] (https://i.sstatic.net/cWv54DMg.png)\n\n\n\n\n# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend(\"topright\",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Asigan", "profile_url": "https://stats.stackexchange.com/users/499652/asigan", "user_type": "registered"}, "created_at": "2026-08-11T15:31:10+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "12CBC237-71E5-4C7A-8DB4-C9CB01074B9D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/12CBC237-71E5-4C7A-8DB4-C9CB01074B9D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-08-12T01:24:32+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "C0DDD5BE-21BF-4736-ABCF-642B92C21EDA", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C0DDD5BE-21BF-4736-ABCF-642B92C21EDA/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-12T04:37:20+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "03306B28-DD9D-42D1-990F-0DBB141FA2C2", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/03306B28-DD9D-42D1-990F-0DBB141FA2C2/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676842/the-asymptotic-distribution-of-likelihood-ratio-statistic-when-the-null-hypothes", "split": "train", "split_group": "04f52474e604252adf534b05534d06a31a2b2b196a4a54978ab75b8b8a135d5c", "tags": ["mathematical-statistics", "likelihood-ratio"], "thread_id": "stats:676842", "title": "The asymptotic distribution of likelihood ratio statistic when the null hypothesis is described by an \"or\" condition"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676858, "sha256": "e3b1e32f3f32fe01d572135a32ea1e26fbbec71586b485ee403199e72bc87c81", "source_url": "https://stats.stackexchange.com/questions/676858/how-do-i-account-for-site-in-a-dbrda-while-evaluating-the-effect-of-variables-th"}, {"block_index": 0, "code_text": "ord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676863, "sha256": "bc9680397eb4e4c17b1e6a48e377a48440fce734ee9b4c8c11f10e16e2a30592", "source_url": "https://stats.stackexchange.com/a/676863"}, {"block_index": 1, "code_text": "ctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676863, "sha256": "3f6e3af9e3118f4e94ce8847b13eba7f0f099f0c7268848fd38f3aa5704e26ce", "source_url": "https://stats.stackexchange.com/a/676863"}, {"block_index": 3, "code_text": "my_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by \"margin\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676863, "sha256": "6818238b2ed33870cc626f77e5c65b19bc5edac4c145555b6e3d34875e45702d", "source_url": "https://stats.stackexchange.com/a/676863"}], "other_answers": [], "product": "code_qa", "question": "I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.\n\n\n\n\nI wanted to account for site when testing the effect of my environmental variables, so I tried:\n\n\n\n\nlibrary(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n\n\n\n\n\nbut because all samples at a site have the same MAT, the model does not evaluate MAT.\n\n\n\n\nHow can I test the effects of all of my environmental variables while accounting for site?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676858", "selected_answer": {"answer_html": "There are two options for testing ordination models in vegan:
\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.
\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.
In both cases you would pass something to the anova() function. This gives you some options as "test the effect of my environmental variables" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?
If you want the omnibus test, essentially of the whole model, you would do:
\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).
A restricted permutation for a design-based test would be
\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:
set.seed(20260814)\nanova(ord, by = "margin")\n\nset.seed(20260814)\nanova(ord, by = "margin", permutations = ctrl)\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.
Because you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.
That said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:
my_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by "margin")\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.
This is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.
\n", "answer_id": 676863, "answer_text": "There are two options for testing ordination models in vegan:\n\n\n\n\n\nmodel-based permutations, and\n\n\n\n\ndesign-based\n\n\n\n\n\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.\n\n\n\n\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.\n\n\n\n\nIn both cases you would pass something to the anova() function. This gives you some options as \"test the effect of my environmental variables\" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?\n\n\n\n\nIf you want the omnibus test, essentially of the whole model, you would do:\n\n\n\n\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\n\n\n\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).\n\n\n\n\nA restricted permutation for a design-based test would be\n\n\n\n\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\n\n\n\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:\n\n\n\n\nset.seed(20260814)\nanova(ord, by = \"margin\")\n\nset.seed(20260814)\nanova(ord, by = \"margin\", permutations = ctrl)\n\n\n\n\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.\n\n\n\n\nBecause you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.\n\n\n\n\nThat said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:\n\n\n\n\nmy_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by \"margin\")\n\n\n\n\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.\n\n\n\n\nThis is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.", "answer_url": "https://stats.stackexchange.com/a/676863", "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-14T06:11:59+00:00", "is_accepted": false, "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": 676858, "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-14T06:11:59+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "A07F8661-3C22-4FF1-B601-E3771400D740", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A07F8661-3C22-4FF1-B601-E3771400D740/view-source"}], "score": 2, "updated_at": "2026-08-14T06:11:59+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "There are two options for testing ordination models in vegan:
\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.
\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.
In both cases you would pass something to the anova() function. This gives you some options as "test the effect of my environmental variables" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?
If you want the omnibus test, essentially of the whole model, you would do:
\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).
A restricted permutation for a design-based test would be
\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:
set.seed(20260814)\nanova(ord, by = "margin")\n\nset.seed(20260814)\nanova(ord, by = "margin", permutations = ctrl)\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.
Because you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.
That said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:
my_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by "margin")\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.
This is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.
\n", "answer_id": 676863, "answer_text": "There are two options for testing ordination models in vegan:\n\n\n\n\n\nmodel-based permutations, and\n\n\n\n\ndesign-based\n\n\n\n\n\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.\n\n\n\n\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.\n\n\n\n\nIn both cases you would pass something to the anova() function. This gives you some options as \"test the effect of my environmental variables\" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?\n\n\n\n\nIf you want the omnibus test, essentially of the whole model, you would do:\n\n\n\n\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\n\n\n\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).\n\n\n\n\nA restricted permutation for a design-based test would be\n\n\n\n\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\n\n\n\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:\n\n\n\n\nset.seed(20260814)\nanova(ord, by = \"margin\")\n\nset.seed(20260814)\nanova(ord, by = \"margin\", permutations = ctrl)\n\n\n\n\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.\n\n\n\n\nBecause you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.\n\n\n\n\nThat said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:\n\n\n\n\nmy_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by \"margin\")\n\n\n\n\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.\n\n\n\n\nThis is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.", "answer_url": "https://stats.stackexchange.com/a/676863", "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-14T06:11:59+00:00", "is_accepted": false, "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": 676858, "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-14T06:11:59+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "A07F8661-3C22-4FF1-B601-E3771400D740", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A07F8661-3C22-4FF1-B601-E3771400D740/view-source"}], "score": 2, "updated_at": "2026-08-14T06:11:59+00:00"}], "domain": "statistics", "external_links": [], "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": "Tillandsia123", "question_author_url": "https://stats.stackexchange.com/users/489435/tillandsia123", "question_author_user_type": "registered", "question_created_at": "2026-08-13T14:13:45+00:00", "question_html": "I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.
\nI wanted to account for site when testing the effect of my environmental variables, so I tried:
\nlibrary(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n\nbut because all samples at a site have the same MAT, the model does not evaluate MAT.
How can I test the effects of all of my environmental variables while accounting for site?
\n", "question_id": 676858, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.\n\n\n\n\nI wanted to account for site when testing the effect of my environmental variables, so I tried:\n\n\n\n\nlibrary(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n\n\n\n\n\nbut because all samples at a site have the same MAT, the model does not evaluate MAT.\n\n\n\n\nHow can I test the effects of all of my environmental variables while accounting for site?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Tillandsia123", "profile_url": "https://stats.stackexchange.com/users/489435/tillandsia123", "user_type": "registered"}, "created_at": "2026-08-13T14:13:45+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7B37CEAA-255C-414E-8A5C-901D88775172", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7B37CEAA-255C-414E-8A5C-901D88775172/view-source"}, {"content_license": null, "contributor": {"display_name": "Community", "profile_url": "https://stats.stackexchange.com/users/-1/community", "user_type": "moderator"}, "created_at": "2026-08-13T16:05:23+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "0B02F8B6-209E-470E-B9B3-ADE3ADB3F0F3", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/0B02F8B6-209E-470E-B9B3-ADE3ADB3F0F3/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676858/how-do-i-account-for-site-in-a-dbrda-while-evaluating-the-effect-of-variables-th", "split": "train", "split_group": "b7a109258c68d4c0ad147c01da06f4600be94b148c00d9e8d67cbc16243ff6b8", "tags": ["r", "vegan", "redundancy-analysis"], "thread_id": "stats:676858", "title": "How do I account for site in a dbRDA while evaluating the effect of variables that are the same across all samples in a site?"}} {"accepted_answer": {"answer_html": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.
\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.
\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:
library(MatchIt); library(cobalt)\n\ndata("lalonde", package = "MatchIt")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\nYou can assess whether many units are assigned to the same subclass by using
\nwith(M1, table(treat, subclass))\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.
In general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.
\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.
\n", "answer_id": 676905, "answer_text": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.\n\n\n\n\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.\n\n\n\n\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:\n\n\n\n\nlibrary(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\n\n\n\n\nYou can assess whether many units are assigned to the same subclass by using\n\n\n\n\nwith(M1, table(treat, subclass))\n\n\n\n\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.\n\n\n\n\nIn general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.\n\n\n\n\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.", "answer_url": "https://stats.stackexchange.com/a/676905", "author": "Noah", "author_url": "https://stats.stackexchange.com/users/116195/noah", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-18T15:26:28+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": 676867, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Noah", "profile_url": "https://stats.stackexchange.com/users/116195/noah", "user_type": "registered"}, "created_at": "2026-08-18T15:26:28+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "CB48996D-4B71-49A4-AD23-E5B278A942D5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB48996D-4B71-49A4-AD23-E5B278A942D5/view-source"}], "score": 3, "updated_at": "2026-08-18T15:26:28+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676905, "sha256": "ab755c77438b83e047bd4f641c2842b48dc9b58095cdba2b3ddf91d1705442ed", "source_url": "https://stats.stackexchange.com/a/676905"}], "other_answers": [], "product": "code_qa", "question": "I was using full matching (using MatchIt, method = \"full\") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.\nI am getting quite high weights in separate groups (maximum of 22 in 1 group and 15 in the other - which as I understand is a way high), as well as relatively low ESS. I tried to apply calipers, which did help to improve the max weights (subgroup 1: 22.4 → 13.2; subgroup 2: 14.8 → 8.0) and ESS (subgroup 1: 74 → 111; subgroup 2: 93 → 156), balance was also mainly improved. It led to discarding 20 out of 275 observations in one subgroup and 6 out of 251 in the other.\nAs I understand the result may not anymore correspond to the ATE. After applying the calipers I am targeting slightly different populations, correct? How reasonable it is then to compare these subgroup estimates in order to draw conclusions about moderation in this case? any additional diagnostics I should try? should I avoid calipers in moderation at all?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676867", "selected_answer": {"answer_html": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.
\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.
\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:
library(MatchIt); library(cobalt)\n\ndata("lalonde", package = "MatchIt")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\nYou can assess whether many units are assigned to the same subclass by using
\nwith(M1, table(treat, subclass))\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.
In general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.
\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.
\n", "answer_id": 676905, "answer_text": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.\n\n\n\n\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.\n\n\n\n\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:\n\n\n\n\nlibrary(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\n\n\n\n\nYou can assess whether many units are assigned to the same subclass by using\n\n\n\n\nwith(M1, table(treat, subclass))\n\n\n\n\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.\n\n\n\n\nIn general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.\n\n\n\n\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.", "answer_url": "https://stats.stackexchange.com/a/676905", "author": "Noah", "author_url": "https://stats.stackexchange.com/users/116195/noah", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-18T15:26:28+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": 676867, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Noah", "profile_url": "https://stats.stackexchange.com/users/116195/noah", "user_type": "registered"}, "created_at": "2026-08-18T15:26:28+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "CB48996D-4B71-49A4-AD23-E5B278A942D5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB48996D-4B71-49A4-AD23-E5B278A942D5/view-source"}], "score": 3, "updated_at": "2026-08-18T15:26:28+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 676905, "answers": [{"answer_html": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.
\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.
\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:
library(MatchIt); library(cobalt)\n\ndata("lalonde", package = "MatchIt")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\nYou can assess whether many units are assigned to the same subclass by using
\nwith(M1, table(treat, subclass))\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.
In general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.
\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.
\n", "answer_id": 676905, "answer_text": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.\n\n\n\n\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.\n\n\n\n\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:\n\n\n\n\nlibrary(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\n\n\n\n\nYou can assess whether many units are assigned to the same subclass by using\n\n\n\n\nwith(M1, table(treat, subclass))\n\n\n\n\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.\n\n\n\n\nIn general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.\n\n\n\n\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.", "answer_url": "https://stats.stackexchange.com/a/676905", "author": "Noah", "author_url": "https://stats.stackexchange.com/users/116195/noah", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-18T15:26:28+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": 676867, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Noah", "profile_url": "https://stats.stackexchange.com/users/116195/noah", "user_type": "registered"}, "created_at": "2026-08-18T15:26:28+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "CB48996D-4B71-49A4-AD23-E5B278A942D5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB48996D-4B71-49A4-AD23-E5B278A942D5/view-source"}], "score": 3, "updated_at": "2026-08-18T15:26:28+00:00"}], "domain": "statistics", "external_links": [], "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": "user31214993", "question_author_url": "https://stats.stackexchange.com/users/490497/user31214993", "question_author_user_type": "registered", "question_created_at": "2026-08-14T14:13:25+00:00", "question_html": "I was using full matching (using MatchIt, method = "full") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.\nI am getting quite high weights in separate groups (maximum of 22 in 1 group and 15 in the other - which as I understand is a way high), as well as relatively low ESS. I tried to apply calipers, which did help to improve the max weights (subgroup 1: 22.4 → 13.2; subgroup 2: 14.8 → 8.0) and ESS (subgroup 1: 74 → 111; subgroup 2: 93 → 156), balance was also mainly improved. It led to discarding 20 out of 275 observations in one subgroup and 6 out of 251 in the other.\nAs I understand the result may not anymore correspond to the ATE. After applying the calipers I am targeting slightly different populations, correct? How reasonable it is then to compare these subgroup estimates in order to draw conclusions about moderation in this case? any additional diagnostics I should try? should I avoid calipers in moderation at all?
\n", "question_id": 676867, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I was using full matching (using MatchIt, method = \"full\") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.\nI am getting quite high weights in separate groups (maximum of 22 in 1 group and 15 in the other - which as I understand is a way high), as well as relatively low ESS. I tried to apply calipers, which did help to improve the max weights (subgroup 1: 22.4 → 13.2; subgroup 2: 14.8 → 8.0) and ESS (subgroup 1: 74 → 111; subgroup 2: 93 → 156), balance was also mainly improved. It led to discarding 20 out of 275 observations in one subgroup and 6 out of 251 in the other.\nAs I understand the result may not anymore correspond to the ATE. After applying the calipers I am targeting slightly different populations, correct? How reasonable it is then to compare these subgroup estimates in order to draw conclusions about moderation in this case? any additional diagnostics I should try? should I avoid calipers in moderation at all?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "user31214993", "profile_url": "https://stats.stackexchange.com/users/490497/user31214993", "user_type": "registered"}, "created_at": "2026-08-14T14:13:25+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "E972484E-5136-4868-B279-F1B4F45BA217", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E972484E-5136-4868-B279-F1B4F45BA217/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676867/can-i-use-caliper-in-moderation-analysis-with-ate-is-the-target-estimand", "split": "train", "split_group": "b48d86f70b30568513b23fc942f009f575dd2790b7c2253380088fa85fbbcec7", "tags": ["interaction", "matching", "treatment-effect"], "thread_id": "stats:676867", "title": "Can I use caliper in moderation analysis with ATE is the target estimand?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676935, "sha256": "31ee3b391b409c5129c104a44ceee4665e4ad79f9da5a4e9871a1a05341ae6ea", "source_url": "https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"}, {"block_index": 1, "code_text": "\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676935, "sha256": "b6b0f012237812aeee60a934ab35cd7d57e130e125fb4b2b6e91c84b7c48ca96", "source_url": "https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"}, {"block_index": 2, "code_text": "# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676935, "sha256": "8cca68dde9586d6ddecb1ac0f5140745338cd3f8b49ea77f06aa4850b3958b9f", "source_url": "https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"}], "other_answers": [], "product": "code_qa", "question": "I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the \"best\" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?\n\n\n\n\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n\n\n\n\n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)\n\n\n\n\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, (\"Full\") one where we actually aren't missing data, (\"Half\") one where we only use $h$ observations, (\"Estimated B\") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and (\"Perfect A\", \"Perfect B\") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:\n\n\n\n\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\n\n\n\n\nAs you can see in the results above, the \"Estimated B\" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points (\"Half Model\"), but it does have a bias.\n\n\n\n\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book (https://stefvanbuuren.name/fimd/sec-simplesolutions.html) and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:\n\n\n\n\n\n\n\n\n\nModel\nMean\nVariance\nBias\nBias_Sq\nMSE\nValid_Runs\n\n\n\n\n\n\n\n\n\tFull Model (N=40)\n\t0.66563\n\t0.02497\n\t-0.00103\n\t0.00000\n\t0.02497\n\t9947\n\n\n\n\n\n\n\tHalf Model (H=20)\n\t0.66289\n\t0.05542\n\t-0.00377\n\t0.00001\n\t0.05543\n\t9947\n\n\n\n\n\n\n\tEstimated B\n\t0.64330\n\t0.05259\n\t-0.02337\n\t0.00055\n\t0.05313\n\t9947\n\n\n\n\n\n\n\tLavaan Pairwise\n\t0.65849\n\t0.07174\n\t-0.00818\n\t0.00007\n\t0.07180\n\t9947\n\n\n\n\n\n\n\n\n\nI am including the code i ran below:\n\n\n\n\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))", "record_id": "Scientific-Code-and-Analysis-QA:stats:676935", "selected_answer": {"answer_html": "\n\nis trying to use all the data a flawed concept to begin with?
\n
No. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are "missing completely at random" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.
\n\n\nis this even a valid approach to begin with...?
\n
Your most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.
\n\n\nwhat is the "best" approach?
\n
For MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.
\nA standard general approach is multiple imputation. Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.
\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.
\nStef van Buuren's Flexible Imputation of Missing Data is a comprehensive guide to the process, which is implemented in his R mice package. Chapter 3 of Regression Modeling Strategies by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms and Hmisc packages.
\n\nDoes the validity depend on the pattern of missing data?
\n
Yes, in two ways.
\nFirst, multiple imputation works correctly if the data are "missing at random" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.
\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.
\nThe references linked above go into much more detail.
\n", "answer_id": 676936, "answer_text": "is trying to use all the data a flawed concept to begin with?\n\n\n\n\n\n\n\nNo. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are \"missing completely at random\" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.\n\n\n\n\n\n\n\nis this even a valid approach to begin with...?\n\n\n\n\n\n\n\nYour most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.\n\n\n\n\n\n\n\nwhat is the \"best\" approach?\n\n\n\n\n\n\n\nFor MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.\n\n\n\n\nA standard general approach is multiple imputation (https://stats.stackexchange.com/tags/multiple-imputation/info). Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.\n\n\n\n\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.\n\n\n\n\nStef van Buuren's Flexible Imputation of Missing Data (https://stefvanbuuren.name/fimd/) is a comprehensive guide to the process, which is implemented in his R mice package (https://cran.r-project.org/package=mice). Chapter 3 of Regression Modeling Strategies (https://hbiostat.org/rmsc/missing) by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms (https://cran.r-project.org/package=rms) and Hmisc (https://cran.r-project.org/package=Hmisc) packages.\n\n\n\n\n\n\n\nDoes the validity depend on the pattern of missing data?\n\n\n\n\n\n\n\nYes, in two ways.\n\n\n\n\nFirst, multiple imputation works correctly if the data are \"missing at random\" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.\n\n\n\n\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.\n\n\n\n\nThe references linked above go into much more detail.", "answer_url": "https://stats.stackexchange.com/a/676936", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-22T20:30:48+00:00", "is_accepted": false, "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": 676935, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-22T20:30:48+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3A662AF2-F298-45A5-889D-7BDCBFDD001E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T17:43:21+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}], "score": 5, "updated_at": "2026-08-23T17:43:21+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "\n\nis trying to use all the data a flawed concept to begin with?
\n
No. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are "missing completely at random" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.
\n\n\nis this even a valid approach to begin with...?
\n
Your most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.
\n\n\nwhat is the "best" approach?
\n
For MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.
\nA standard general approach is multiple imputation. Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.
\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.
\nStef van Buuren's Flexible Imputation of Missing Data is a comprehensive guide to the process, which is implemented in his R mice package. Chapter 3 of Regression Modeling Strategies by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms and Hmisc packages.
\n\nDoes the validity depend on the pattern of missing data?
\n
Yes, in two ways.
\nFirst, multiple imputation works correctly if the data are "missing at random" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.
\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.
\nThe references linked above go into much more detail.
\n", "answer_id": 676936, "answer_text": "is trying to use all the data a flawed concept to begin with?\n\n\n\n\n\n\n\nNo. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are \"missing completely at random\" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.\n\n\n\n\n\n\n\nis this even a valid approach to begin with...?\n\n\n\n\n\n\n\nYour most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.\n\n\n\n\n\n\n\nwhat is the \"best\" approach?\n\n\n\n\n\n\n\nFor MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.\n\n\n\n\nA standard general approach is multiple imputation (https://stats.stackexchange.com/tags/multiple-imputation/info). Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.\n\n\n\n\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.\n\n\n\n\nStef van Buuren's Flexible Imputation of Missing Data (https://stefvanbuuren.name/fimd/) is a comprehensive guide to the process, which is implemented in his R mice package (https://cran.r-project.org/package=mice). Chapter 3 of Regression Modeling Strategies (https://hbiostat.org/rmsc/missing) by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms (https://cran.r-project.org/package=rms) and Hmisc (https://cran.r-project.org/package=Hmisc) packages.\n\n\n\n\n\n\n\nDoes the validity depend on the pattern of missing data?\n\n\n\n\n\n\n\nYes, in two ways.\n\n\n\n\nFirst, multiple imputation works correctly if the data are \"missing at random\" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.\n\n\n\n\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.\n\n\n\n\nThe references linked above go into much more detail.", "answer_url": "https://stats.stackexchange.com/a/676936", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-22T20:30:48+00:00", "is_accepted": false, "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": 676935, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-22T20:30:48+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3A662AF2-F298-45A5-889D-7BDCBFDD001E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T17:43:21+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}], "score": 5, "updated_at": "2026-08-23T17:43:21+00:00"}], "domain": "statistics", "external_links": ["https://cran.r-project.org/package=Hmisc", "https://cran.r-project.org/package=mice", "https://cran.r-project.org/package=rms", "https://hbiostat.org/rmsc/missing", "https://stefvanbuuren.name/fimd/", "https://stefvanbuuren.name/fimd/sec-simplesolutions.html"], "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": "A Friendly Fish", "question_author_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "question_author_user_type": "registered", "question_created_at": "2026-08-22T12:39:55+00:00", "question_html": "I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the "best" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?
\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))["y0h","Pr(>|t|)"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))["r_ly0ONy2_n_h","Pr(>|t|)"]\n}\ncat("Multiple: ", mean(multiple < 0.05), "\\n")\n# Multiple: 0.0529 \ncat(" Stage: ", mean(stage < 0.05), "\\n")\n# Stage: 0.0527 \n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)
\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, ("Full") one where we actually aren't missing data, ("Half") one where we only use $h$ observations, ("Estimated B") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and ("Perfect A", "Perfect B") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:
\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))["y0"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))["y0h"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))["y0rph"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))["y0rph"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))["y0reh"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n "Full Model (sfm)" = sfm,\n "Half Model (shm)" = shm,\n "Perfect A (shpa)" = shpa,\n "Perfect B (shpb)" = shpb,\n "Estimated B (sheb)" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\nAs you can see in the results above, the "Estimated B" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points ("Half Model"), but it does have a bias.
\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:
\n| Model | \nMean | \nVariance | \nBias | \nBias_Sq | \nMSE | \nValid_Runs | \n
|---|---|---|---|---|---|---|
| Full Model (N=40) | \n0.66563 | \n0.02497 | \n-0.00103 | \n0.00000 | \n0.02497 | \n9947 | \n
| Half Model (H=20) | \n0.66289 | \n0.05542 | \n-0.00377 | \n0.00001 | \n0.05543 | \n9947 | \n
| Estimated B | \n0.64330 | \n0.05259 | \n-0.02337 | \n0.00055 | \n0.05313 | \n9947 | \n
| Lavaan Pairwise | \n0.65849 | \n0.07174 | \n-0.00818 | \n0.00007 | \n0.07180 | \n9947 | \n
I am including the code i ran below:
\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages("lavaan")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- "\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n"\n\ncat("Running", num_sims, "simulations. Please wait...\\n")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = "pairwise.complete.obs")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == "y0", "est"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))["y0"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))["y0h"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))["y0reh"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n "Full Model (N=40)" = sfm,\n "Half Model (H=20)" = shm,\n "Estimated B" = sheb,\n "Lavaan Pairwise" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat("\\n--- Simulation Results ---\\n")\nprint(round(results_matrix, 5))\n\n", "question_id": 676935, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the \"best\" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?\n\n\n\n\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n\n\n\n\n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)\n\n\n\n\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, (\"Full\") one where we actually aren't missing data, (\"Half\") one where we only use $h$ observations, (\"Estimated B\") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and (\"Perfect A\", \"Perfect B\") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:\n\n\n\n\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\n\n\n\n\nAs you can see in the results above, the \"Estimated B\" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points (\"Half Model\"), but it does have a bias.\n\n\n\n\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book (https://stefvanbuuren.name/fimd/sec-simplesolutions.html) and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:\n\n\n\n\n\n\n\n\n\nModel\nMean\nVariance\nBias\nBias_Sq\nMSE\nValid_Runs\n\n\n\n\n\n\n\n\n\tFull Model (N=40)\n\t0.66563\n\t0.02497\n\t-0.00103\n\t0.00000\n\t0.02497\n\t9947\n\n\n\n\n\n\n\tHalf Model (H=20)\n\t0.66289\n\t0.05542\n\t-0.00377\n\t0.00001\n\t0.05543\n\t9947\n\n\n\n\n\n\n\tEstimated B\n\t0.64330\n\t0.05259\n\t-0.02337\n\t0.00055\n\t0.05313\n\t9947\n\n\n\n\n\n\n\tLavaan Pairwise\n\t0.65849\n\t0.07174\n\t-0.00818\n\t0.00007\n\t0.07180\n\t9947\n\n\n\n\n\n\n\n\n\nI am including the code i ran below:\n\n\n\n\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-22T12:39:55+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "E204A8FC-AC6E-48BB-AF80-E203CBC8615E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E204A8FC-AC6E-48BB-AF80-E203CBC8615E/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-22T20:46:45+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "18F1A87E-216E-4249-8293-E060F71CC55D", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/18F1A87E-216E-4249-8293-E060F71CC55D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T15:52:35+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "70469448-256D-43B2-80C1-746F337D6247", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/70469448-256D-43B2-80C1-746F337D6247/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T16:01:52+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T16:53:21+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T17:02:49+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "AC468C9B-BCFF-4264-A45F-3229DC6759C1", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AC468C9B-BCFF-4264-A45F-3229DC6759C1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how", "split": "train", "split_group": "0e07c1b9aeb4ed16810975d0835aae0ada37766b2c187a88bd4ee1b79bc9bf36", "tags": ["regression", "multiple-regression", "degrees-of-freedom", "type-i-and-ii-errors", "two-stage-least-squares"], "thread_id": "stats:676935", "title": "missing data: break multiple regression into stages; how?"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "Model <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676937, "sha256": "186bb1fbe667f4f1ab0dc3d65addbccd015f26d2465a66f918a041890744f97c", "source_url": "https://stats.stackexchange.com/questions/676937/treatment-comparisons-in-repeated-measures-mixed-model-ancova-with-a-baseline-co"}], "other_answers": [], "product": "code_qa", "question": "Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals. Because the same individuals were measured repeatedly over time, the repeated-measures structure is also accounted for in the model.The experiment is a block split plot experimental design of forestry experiment.\n\n\n\n\nMy model includes treatment, time, and the baseline covariate, including their interactions. I mean-centered the baseline covariate so that a value of zero represents the average baseline value.\n\n\n\n\nModel <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n\n\n\n\n\nFor post-hoc comparisons, I am using the emmeans package to compare treatments within each time point while setting the centered baseline covariate to zero (my model is box cox transformed). Therefore, these comparisons represent treatment differences for individuals with an average baseline value.\n\n\n\n\nIs this an appropriate way to perform and interpret the ANCOVA? In particular, if the treatment × time × baseline covariate interaction is significant, is it still appropriate to compare treatments within each time point using emmeans at the mean baseline value? My main objective is not related to initial height effect on the performance seedlings growth over time.Thanks", "record_id": "Scientific-Code-and-Analysis-QA:stats:676937", "selected_answer": {"answer_html": "If the treatment × time × baseline covariate interaction is significant, then the association between treatment/time and outcome depends on the value of the baseline covariate. It thus would make sense to evaluate treatment effects within each time point over a range of baseline covariate values. That should be easy to do with emmeans and will document whether the "statistically significant" 3-way interaction has much practical significance.
You should also consider, however, whether your model is mis-specified. Sometimes an apparently significant interaction term arises from a model that doesn't adequately capture the functional form of the association between outcome and predictors, in your case the outcome Height_BC and the baseline covariate H_2007_BC_c. A flexible fit of H_2007_BC_c with a regression spline or other generalized additive model might remove the need for the 3-way interaction.
That would seem to make sense in your application; a tree that is already near some practical maximum height might be expected to have less growth or response to treatment than a short tree would. I don't see how your model linear in H_2007_BC_c would capture that.
If the treatment × time × baseline covariate interaction is significant, then the association between treatment/time and outcome depends on the value of the baseline covariate. It thus would make sense to evaluate treatment effects within each time point over a range of baseline covariate values. That should be easy to do with emmeans and will document whether the "statistically significant" 3-way interaction has much practical significance.
You should also consider, however, whether your model is mis-specified. Sometimes an apparently significant interaction term arises from a model that doesn't adequately capture the functional form of the association between outcome and predictors, in your case the outcome Height_BC and the baseline covariate H_2007_BC_c. A flexible fit of H_2007_BC_c with a regression spline or other generalized additive model might remove the need for the 3-way interaction.
That would seem to make sense in your application; a tree that is already near some practical maximum height might be expected to have less growth or response to treatment than a short tree would. I don't see how your model linear in H_2007_BC_c would capture that.
Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals. Because the same individuals were measured repeatedly over time, the repeated-measures structure is also accounted for in the model.The experiment is a block split plot experimental design of forestry experiment.
\nMy model includes treatment, time, and the baseline covariate, including their interactions. I mean-centered the baseline covariate so that a value of zero represents the average baseline value.
\nModel <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n\nFor post-hoc comparisons, I am using the emmeans package to compare treatments within each time point while setting the centered baseline covariate to zero (my model is box cox transformed). Therefore, these comparisons represent treatment differences for individuals with an average baseline value.
\nIs this an appropriate way to perform and interpret the ANCOVA? In particular, if the treatment × time × baseline covariate interaction is significant, is it still appropriate to compare treatments within each time point using emmeans at the mean baseline value? My main objective is not related to initial height effect on the performance seedlings growth over time.Thanks
\n", "question_id": 676937, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals. Because the same individuals were measured repeatedly over time, the repeated-measures structure is also accounted for in the model.The experiment is a block split plot experimental design of forestry experiment.\n\n\n\n\nMy model includes treatment, time, and the baseline covariate, including their interactions. I mean-centered the baseline covariate so that a value of zero represents the average baseline value.\n\n\n\n\nModel <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n\n\n\n\n\nFor post-hoc comparisons, I am using the emmeans package to compare treatments within each time point while setting the centered baseline covariate to zero (my model is box cox transformed). Therefore, these comparisons represent treatment differences for individuals with an average baseline value.\n\n\n\n\nIs this an appropriate way to perform and interpret the ANCOVA? In particular, if the treatment × time × baseline covariate interaction is significant, is it still appropriate to compare treatments within each time point using emmeans at the mean baseline value? My main objective is not related to initial height effect on the performance seedlings growth over time.Thanks", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-22T22:19:04+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "2B53CAE3-9898-4BAD-A47C-F21FC6D2CDFE", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2B53CAE3-9898-4BAD-A47C-F21FC6D2CDFE/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T02:20:37+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "40D430F5-C4EA-404C-9500-73565E0A45AD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/40D430F5-C4EA-404C-9500-73565E0A45AD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T02:26:05+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "9C8ADAEC-43F3-4E44-8D85-BE8C1ABA317C", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9C8ADAEC-43F3-4E44-8D85-BE8C1ABA317C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T02:31:15+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "F764FBDD-D5CE-4BB8-A654-2117D3C158FC", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F764FBDD-D5CE-4BB8-A654-2117D3C158FC/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T14:48:42+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "A8739EA4-04E9-4855-B47E-7D431C971826", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A8739EA4-04E9-4855-B47E-7D431C971826/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T18:55:33+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "AA29DDF8-382A-4143-9646-FEE4954D97AA", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AA29DDF8-382A-4143-9646-FEE4954D97AA/view-source"}, {"content_license": null, "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T19:00:42+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "15EA9028-E0DB-4270-92D2-951EAA324FC1", "revision_number": 7, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/15EA9028-E0DB-4270-92D2-951EAA324FC1/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-24T15:03:00+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "DBC6C8CE-6537-48D0-B89E-53BB5FA32C91", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/DBC6C8CE-6537-48D0-B89E-53BB5FA32C91/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676937/treatment-comparisons-in-repeated-measures-mixed-model-ancova-with-a-baseline-co", "split": "train", "split_group": "39b688f3328bca92a43e0fb3eaf3d5aa37df78aa89e0d509aecbd58742da06f6", "tags": ["mixed-model", "lme4-nlme", "covariance", "ancova", "lsmeans"], "thread_id": "stats:676937", "title": "Treatment Comparisons in Repeated-Measures mixed model ANCOVA with a Baseline Covariate"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "data(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676959, "sha256": "64967942425141864eb927a2a7cb6a1dc7e759da705a95dcd025ba9c190e166e", "source_url": "https://stats.stackexchange.com/a/676959"}, {"block_index": 3, "code_text": "predict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676959, "sha256": "8d8e20779f4179423d77d243048d7e5f763f42bf264089a5019e3583544c0a46", "source_url": "https://stats.stackexchange.com/a/676959"}, {"block_index": 4, "code_text": "m3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676959, "sha256": "ce7646376cb93ca32ea69ecd574e3065621a1d537fe4b63606bb4d392e01ff13", "source_url": "https://stats.stackexchange.com/a/676959"}], "other_answers": [], "product": "code_qa", "question": "For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.\n\n\n\n\nI suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the response variable was excluded.\n\n\n\n\nWhen scaling data for other models we usually scale the entire dataset so I'm confused why in this instance it's not included.", "record_id": "Scientific-Code-and-Analysis-QA:stats:676958", "selected_answer": {"answer_html": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:
\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):
sd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:
\nsummary(m1)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:
\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.
\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:
\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.
Created on 2026-08-25 with reprex v2.1.1
\n", "answer_id": 676959, "answer_text": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:\n\n\n\n\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\n\n\n\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):\n\n\n\n\nsd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\n\n\n\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:\n\n\n\n\nsummary(m1)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\n\n\n\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:\n\n\n\n\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\n\n\n\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.\n\n\n\n\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:\n\n\n\n\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\n\n\n\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.\n\n\n\n\nCreated on 2026-08-25 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676959", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-25T19:05:50+00:00", "is_accepted": false, "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": 676958, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-08-25T19:05:50+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "572E3B4E-1F43-4F40-91AA-292255EC61E9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/572E3B4E-1F43-4F40-91AA-292255EC61E9/view-source"}], "score": 11, "updated_at": "2026-08-25T19:05:50+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:
\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):
sd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:
\nsummary(m1)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:
\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.
\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:
\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.
Created on 2026-08-25 with reprex v2.1.1
\n", "answer_id": 676959, "answer_text": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:\n\n\n\n\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\n\n\n\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):\n\n\n\n\nsd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\n\n\n\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:\n\n\n\n\nsummary(m1)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\n\n\n\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:\n\n\n\n\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\n\n\n\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.\n\n\n\n\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:\n\n\n\n\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\n\n\n\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.\n\n\n\n\nCreated on 2026-08-25 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676959", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-25T19:05:50+00:00", "is_accepted": false, "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": 676958, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-08-25T19:05:50+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "572E3B4E-1F43-4F40-91AA-292255EC61E9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/572E3B4E-1F43-4F40-91AA-292255EC61E9/view-source"}], "score": 11, "updated_at": "2026-08-25T19:05:50+00:00"}], "domain": "statistics", "external_links": ["https://reprex.tidyverse.org"], "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": "Karl Suh", "question_author_url": "https://stats.stackexchange.com/users/513622/karl-suh", "question_author_user_type": "registered", "question_created_at": "2026-08-25T17:43:52+00:00", "question_html": "For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.
\nI suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the response variable was excluded.
\nWhen scaling data for other models we usually scale the entire dataset so I'm confused why in this instance it's not included.
\n", "question_id": 676958, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.\n\n\n\n\nI suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the response variable was excluded.\n\n\n\n\nWhen scaling data for other models we usually scale the entire dataset so I'm confused why in this instance it's not included.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Karl Suh", "profile_url": "https://stats.stackexchange.com/users/513622/karl-suh", "user_type": "registered"}, "created_at": "2026-08-25T17:43:52+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4082C60D-8D85-46BC-9D47-179A8B66E184", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/4082C60D-8D85-46BC-9D47-179A8B66E184/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-26T01:49:11+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "1BA401BC-F034-41AE-8F89-81E5097845A1", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/1BA401BC-F034-41AE-8F89-81E5097845A1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676958/for-stepwise-regression-when-scaling-the-data-why-not-scale-the-response-and-ca", "split": "train", "split_group": "4fe50e1b22b7e2f9bed9d1b79bf1ec7f398cf2d4491c96672ea2ca7f02f416ed", "tags": ["standardization", "stepwise-regression"], "thread_id": "stats:676958", "title": "For stepwise regression, when scaling the data why not scale the response and categorical variables?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "data(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676997, "sha256": "23b3b5b39bc0cb13c12c87ccd189366e10e7b70ab1d9469fbec0536fc8e68a7f", "source_url": "https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers"}], "other_answers": [], "product": "code_qa", "question": "I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.\n\n\n\n\nHere is an example of how the data is collected:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Woh1NewX.png] (https://i.sstatic.net/Woh1NewX.png)\n\n\n\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.\n\n\n\n\nWhat I did to solve the issue:\n\n\n\n\n\nDuplicated timestamps\n\n\n\n\nDuplicated location points\n\n\n\n\nACC > 50 (Accuracy estimator in metres)\n\n\n\n\n\nThis left me with ~3000 rows of data for each cat.\n\n\n\n\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:\n\n\n\n\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n\n\n\n\n\nHere is the resulting home range plots of 1 cat:\n[image: L: Home range from wAKDE, R: Home range from AKDE ; source: https://i.sstatic.net/kXgSIQb8.png] (https://i.sstatic.net/kXgSIQb8.png)\n\n\n\n\nHere is the summary of wAKDE and AKDE respectively:\n[image: L: wAKDE, R: AKDE; source: https://i.sstatic.net/bZFkYz3U.png] (https://i.sstatic.net/bZFkYz3U.png)\n\n\n\n\nHere is the plot points of 1 cat across the campus (~2.5 months of data):\n[image: Plot points generated from R; source: https://i.sstatic.net/I6TIxhWk.png] (https://i.sstatic.net/I6TIxhWk.png)\n\n\n\n\nThe issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.\n\n\n\n\nMy questions:\n\n\n\n\n\nHow do I thin out my data? Other than removing obvious outliers, I tried to filter the data by creating new cluster points (in R I attempted to create a function to cluster points within a certain stationary threshold, and the centroid of this point would be the new point)\n\n\n\n\nHow do I account for inaccuracies, especially because this technology is quite new and the only accuracy estimator I have is ACC which I am unsure of how to calibrate it so that I can account for it in the ctmm package.\n\n\n\n\nWhy is the home range a circle?\n\n\n\n\nShould I be using AKDE to find home range or BBMM (Brownian bridge movement model)? BBMM which is better equipped to deal with auto-correlated and clustered position data than KDE home range estimator commonly used in wildlife studies. Specifically, BBMM allows estimation of probabilistic space-use, while accounting for position error and the uncertainty about paths taken between consecutive positions.\n\n\n\n\n\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)", "record_id": "Scientific-Code-and-Analysis-QA:stats:676997", "selected_answer": {"answer_html": "Welcome to CV.
\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not "help"...
First, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.
\nNote that the "typical" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.
\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.
Wrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).
\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).
Last, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n
\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?
\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.
\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...
\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?
\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).
\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.
\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).
Welcome to CV.
\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not "help"...
First, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.
\nNote that the "typical" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.
\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.
Wrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).
\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).
Last, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n
\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?
\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.
\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...
\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?
\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).
\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.
\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).
I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.
\nHere is an example of how the data is collected:
\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.
\nWhat I did to solve the issue:
\nThis left me with ~3000 rows of data for each cat.
\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:
\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("weighted OUF AKDE"["C"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("OUF AKDE"["C"]))\n\nHere is the resulting home range plots of 1 cat:\n
Here is the summary of wAKDE and AKDE respectively:\n
Here is the plot points of 1 cat across the campus (~2.5 months of data):\n
The issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.
\nMy questions:
\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)
\n", "question_id": 676997, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.\n\n\n\n\nHere is an example of how the data is collected:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Woh1NewX.png] (https://i.sstatic.net/Woh1NewX.png)\n\n\n\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.\n\n\n\n\nWhat I did to solve the issue:\n\n\n\n\n\nDuplicated timestamps\n\n\n\n\nDuplicated location points\n\n\n\n\nACC > 50 (Accuracy estimator in metres)\n\n\n\n\n\nThis left me with ~3000 rows of data for each cat.\n\n\n\n\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:\n\n\n\n\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n\n\n\n\n\nHere is the resulting home range plots of 1 cat:\n[image: L: Home range from wAKDE, R: Home range from AKDE ; source: https://i.sstatic.net/kXgSIQb8.png] (https://i.sstatic.net/kXgSIQb8.png)\n\n\n\n\nHere is the summary of wAKDE and AKDE respectively:\n[image: L: wAKDE, R: AKDE; source: https://i.sstatic.net/bZFkYz3U.png] (https://i.sstatic.net/bZFkYz3U.png)\n\n\n\n\nHere is the plot points of 1 cat across the campus (~2.5 months of data):\n[image: Plot points generated from R; source: https://i.sstatic.net/I6TIxhWk.png] (https://i.sstatic.net/I6TIxhWk.png)\n\n\n\n\nThe issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.\n\n\n\n\nMy questions:\n\n\n\n\n\nHow do I thin out my data? Other than removing obvious outliers, I tried to filter the data by creating new cluster points (in R I attempted to create a function to cluster points within a certain stationary threshold, and the centroid of this point would be the new point)\n\n\n\n\nHow do I account for inaccuracies, especially because this technology is quite new and the only accuracy estimator I have is ACC which I am unsure of how to calibrate it so that I can account for it in the ctmm package.\n\n\n\n\nWhy is the home range a circle?\n\n\n\n\nShould I be using AKDE to find home range or BBMM (Brownian bridge movement model)? BBMM which is better equipped to deal with auto-correlated and clustered position data than KDE home range estimator commonly used in wildlife studies. Specifically, BBMM allows estimation of probabilistic space-use, while accounting for position error and the uncertainty about paths taken between consecutive positions.\n\n\n\n\n\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "yuen kei", "profile_url": "https://stats.stackexchange.com/users/516045/yuen-kei", "user_type": "registered"}, "created_at": "2026-08-29T12:41:14+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "D14E0134-8761-4D18-9603-809C2EE8BF6C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D14E0134-8761-4D18-9603-809C2EE8BF6C/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-30T03:37:51+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "9EC2BF4F-7493-47E5-9507-BE468E30BE43", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/9EC2BF4F-7493-47E5-9507-BE468E30BE43/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers", "split": "train", "split_group": "e6076ac1bffe41919709726776bef5ec5e60aef3dc627347d256d7ca034cc2d9", "tags": ["r", "distributions", "ecology"], "thread_id": "stats:676997", "title": "Asking for advice on cleaning GPS data from BLE trackers"}} {"accepted_answer": {"answer_html": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.
\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.
\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$
\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$
\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).
\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.
\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.
\nR code for the simulationThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution for suggestions on improving this.
#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = "xy", col = gray(3/4),\n main = "Joint estimates",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = "Red")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = "Black")\n\nhist(log(Sim[1, ]), main = "", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = "", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n\n", "answer_id": 677036, "answer_text": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.\n\n\n\n\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/tCnpe77y.png] (https://i.sstatic.net/tCnpe77y.png)\n\n\n\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$\n\n\n\n\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$\n\n\n\n\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).\n\n\n\n\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.\n\n\n\n\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.\n\n\n\n\n\n\n\nR code for the simulation\n\n\n\n\nThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution (https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2) for suggestions on improving this.\n\n\n\n\n#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))", "answer_url": "https://stats.stackexchange.com/a/677036", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T15:28:17+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": 677021, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-09-01T15:28:17+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "562F742D-E466-46BD-8A9B-E3CC5920C263", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/562F742D-E466-46BD-8A9B-E3CC5920C263/view-source"}], "score": 8, "updated_at": "2026-09-01T15:28:17+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677036, "sha256": "b83ca8136b43e28bbec688e77ef8b88b496efc85ffa2018c2dd15fc9a4ec89cc", "source_url": "https://stats.stackexchange.com/a/677036"}], "other_answers": [], "product": "code_qa", "question": "Suppose $X_1, \\dots, X_n \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha, \\beta)$, and I want to estimate the parameters by maximum likelihood.\n\n\n\n\nI know that:\n$$\\hat\\mu = \\frac{\\hat\\alpha}{\\hat\\alpha + \\hat\\beta}, \\qquad \\hat\\sigma^2 = \\frac{\\hat\\alpha\\hat\\beta}{(\\hat\\alpha+\\hat\\beta)^2(\\hat\\alpha+\\hat\\beta+1)}.$$\n\n\n\n\nIf $\\hat\\alpha$ and $\\hat\\beta$ can only be found numerically, how do we know if $\\hat\\alpha, \\hat\\beta, \\hat\\mu, \\hat\\sigma^2$ are biased or unbiased? (and how large is the bias)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677021", "selected_answer": {"answer_html": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.
\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.
\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$
\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$
\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).
\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.
\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.
\nR code for the simulationThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution for suggestions on improving this.
#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = "xy", col = gray(3/4),\n main = "Joint estimates",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = "Red")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = "Black")\n\nhist(log(Sim[1, ]), main = "", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = "", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n\n", "answer_id": 677036, "answer_text": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.\n\n\n\n\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/tCnpe77y.png] (https://i.sstatic.net/tCnpe77y.png)\n\n\n\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$\n\n\n\n\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$\n\n\n\n\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).\n\n\n\n\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.\n\n\n\n\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.\n\n\n\n\n\n\n\nR code for the simulation\n\n\n\n\nThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution (https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2) for suggestions on improving this.\n\n\n\n\n#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))", "answer_url": "https://stats.stackexchange.com/a/677036", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T15:28:17+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": 677021, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-09-01T15:28:17+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "562F742D-E466-46BD-8A9B-E3CC5920C263", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/562F742D-E466-46BD-8A9B-E3CC5920C263/view-source"}], "score": 8, "updated_at": "2026-09-01T15:28:17+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677036, "answers": [{"answer_html": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.
\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.
\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$
\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$
\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).
\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.
\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.
\nR code for the simulationThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution for suggestions on improving this.
#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = "xy", col = gray(3/4),\n main = "Joint estimates",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = "Red")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = "Black")\n\nhist(log(Sim[1, ]), main = "", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = "", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n\n", "answer_id": 677036, "answer_text": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.\n\n\n\n\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/tCnpe77y.png] (https://i.sstatic.net/tCnpe77y.png)\n\n\n\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$\n\n\n\n\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$\n\n\n\n\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).\n\n\n\n\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.\n\n\n\n\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.\n\n\n\n\n\n\n\nR code for the simulation\n\n\n\n\nThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution (https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2) for suggestions on improving this.\n\n\n\n\n#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))", "answer_url": "https://stats.stackexchange.com/a/677036", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T15:28:17+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": 677021, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-09-01T15:28:17+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "562F742D-E466-46BD-8A9B-E3CC5920C263", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/562F742D-E466-46BD-8A9B-E3CC5920C263/view-source"}], "score": 8, "updated_at": "2026-09-01T15:28:17+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2", "https://i.sstatic.net/tCnpe77y.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-08-31T15:30:58+00:00", "question_html": "Suppose $X_1, \\dots, X_n \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha, \\beta)$, and I want to estimate the parameters by maximum likelihood.
\nI know that:\n$$\\hat\\mu = \\frac{\\hat\\alpha}{\\hat\\alpha + \\hat\\beta}, \\qquad \\hat\\sigma^2 = \\frac{\\hat\\alpha\\hat\\beta}{(\\hat\\alpha+\\hat\\beta)^2(\\hat\\alpha+\\hat\\beta+1)}.$$
\nIf $\\hat\\alpha$ and $\\hat\\beta$ can only be found numerically, how do we know if $\\hat\\alpha, \\hat\\beta, \\hat\\mu, \\hat\\sigma^2$ are biased or unbiased? (and how large is the bias)
\n", "question_id": 677021, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "Suppose $X_1, \\dots, X_n \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha, \\beta)$, and I want to estimate the parameters by maximum likelihood.\n\n\n\n\nI know that:\n$$\\hat\\mu = \\frac{\\hat\\alpha}{\\hat\\alpha + \\hat\\beta}, \\qquad \\hat\\sigma^2 = \\frac{\\hat\\alpha\\hat\\beta}{(\\hat\\alpha+\\hat\\beta)^2(\\hat\\alpha+\\hat\\beta+1)}.$$\n\n\n\n\nIf $\\hat\\alpha$ and $\\hat\\beta$ can only be found numerically, how do we know if $\\hat\\alpha, \\hat\\beta, \\hat\\mu, \\hat\\sigma^2$ are biased or unbiased? (and how large is the bias)", "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-08-31T15:30:58+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "9E0825ED-D3A3-4B9D-A473-EAAC6F1F776C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9E0825ED-D3A3-4B9D-A473-EAAC6F1F776C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-01T15:34:43+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E40FFCDD-0DA9-4AD3-8F2B-156FC54FF70B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E40FFCDD-0DA9-4AD3-8F2B-156FC54FF70B/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-01T15:40:03+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "B40F8A52-F9E0-4EFC-B9EE-1256CB7E1E1B", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/B40F8A52-F9E0-4EFC-B9EE-1256CB7E1E1B/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677021/if-an-mle-can-only-be-solved-numerically-how-do-we-know-if-it-is-biased-or-unbi", "split": "train", "split_group": "e281e2df35e214047c71a76e665e03cfecfa605e1301c0b2625e62afa44ac194", "tags": ["maximum-likelihood"], "thread_id": "stats:677021", "title": "If an MLE can only be solved numerically, how do we know if it is biased or unbiased?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "glm(Y ~ X * Z + C1 + C2, family = binomial)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677023, "sha256": "c4f9bf8f0235bd91571ecb82f9237cf525d1071c10a1c4cd61809e1b52959402", "source_url": "https://stats.stackexchange.com/questions/677023/does-an-interaction-term-affect-the-interpretation-of-the-other-covariates"}], "other_answers": [{"answer_html": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.
\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.
\n", "answer_id": 677028, "answer_text": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.\n\n\n\n\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.", "answer_url": "https://stats.stackexchange.com/a/677028", "author": "Peter Flom", "author_url": "https://stats.stackexchange.com/users/686/peter-flom", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-31T18:43:35+00:00", "is_accepted": false, "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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Peter Flom", "profile_url": "https://stats.stackexchange.com/users/686/peter-flom", "user_type": "registered"}, "created_at": "2026-08-31T18:43:35+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "02A19662-7877-4049-B5F5-406036C72096", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/02A19662-7877-4049-B5F5-406036C72096/view-source"}], "score": 0, "updated_at": "2026-08-31T18:43:35+00:00"}], "product": "code_qa", "question": "Logistic regression:\n\n\n\n\nglm(Y ~ X * Z + C1 + C2, family = binomial)\n\n\n\n\n\nI know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.\n\n\n\n\nDoes this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the ordinary null?\n\n\n\n\nAny textbook or paper that states this explicitly?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677023", "selected_answer": {"answer_html": "The original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example
\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.
\nLet's consider a logistic model with a indicator "exposure" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.
\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:
\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$
\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:
\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$
\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.
\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.
\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.
\n", "answer_id": 677039, "answer_text": "Edit:\n\n\n\n\nThe original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example\n\n\n\n\n\n\n\n\nfrom Whuber: F. Mosteller and J. Tukey, Data Analysis and Regression (https://archive.org/details/dataanalysisregr0000most)\n\n\n\n\nfrom M--: P. Roback and J. Legler: Beyond Multiple Linear Regression (https://bookdown.org/roback/bookdown-BeyondMLR/)\n\n\n\n\nMy picks:\n\n\n\n\n\n\nOrdinary regression, and general issues with GLMS: Weisberg: Applied Linear Regression (https://www.wiley.com/en-br/shop/general-introductory-statistics/applied-linear-regression-4th-edition-p-9781118386088); Fox: Applied Regression Analysis and Generalized Linear Models (https://collegepublishing.sagepub.com/products/applied-regression-analysis-and-generalized-linear-models-3-237254)\n\n\n\n\nSpecific to logistic regression: Hosmer and Lemeshow: Applied Logistic Regression (https://onlinelibrary.wiley.com/doi/book/10.1002/9781118548387)\n\n\n\n\n\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.\n\n\n\n\nLet's consider a logistic model with a indicator \"exposure\" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.\n\n\n\n\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:\n\n\n\n\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$\n\n\n\n\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:\n\n\n\n\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$\n\n\n\n\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.\n\n\n\n\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.\n\n\n\n\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.", "answer_url": "https://stats.stackexchange.com/a/677039", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T18:54:15+00:00", "is_accepted": false, "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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-01T18:54:15+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "1C96DBED-01C4-408D-8ADC-73D384ED5F3D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1C96DBED-01C4-408D-8ADC-73D384ED5F3D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T01:11:13+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB91F46E-AE98-4B27-B146-70EE8551482D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB91F46E-AE98-4B27-B146-70EE8551482D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mastropi", "profile_url": "https://stats.stackexchange.com/users/217355/mastropi", "user_type": "registered"}, "created_at": "2026-09-02T11:36:08+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB25A932-6CB9-4775-9305-5FA8CA11BEE5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB25A932-6CB9-4775-9305-5FA8CA11BEE5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T19:56:28+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "0C25F4DB-255E-4A29-8217-4F07665C4131", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/0C25F4DB-255E-4A29-8217-4F07665C4131/view-source"}], "score": 5, "updated_at": "2026-09-02T19:56:28+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.
\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.
\n", "answer_id": 677028, "answer_text": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.\n\n\n\n\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.", "answer_url": "https://stats.stackexchange.com/a/677028", "author": "Peter Flom", "author_url": "https://stats.stackexchange.com/users/686/peter-flom", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-31T18:43:35+00:00", "is_accepted": false, "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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Peter Flom", "profile_url": "https://stats.stackexchange.com/users/686/peter-flom", "user_type": "registered"}, "created_at": "2026-08-31T18:43:35+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "02A19662-7877-4049-B5F5-406036C72096", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/02A19662-7877-4049-B5F5-406036C72096/view-source"}], "score": 0, "updated_at": "2026-08-31T18:43:35+00:00"}, {"answer_html": "The original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example
\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.
\nLet's consider a logistic model with a indicator "exposure" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.
\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:
\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$
\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:
\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$
\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.
\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.
\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.
\n", "answer_id": 677039, "answer_text": "Edit:\n\n\n\n\nThe original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example\n\n\n\n\n\n\n\n\nfrom Whuber: F. Mosteller and J. Tukey, Data Analysis and Regression (https://archive.org/details/dataanalysisregr0000most)\n\n\n\n\nfrom M--: P. Roback and J. Legler: Beyond Multiple Linear Regression (https://bookdown.org/roback/bookdown-BeyondMLR/)\n\n\n\n\nMy picks:\n\n\n\n\n\n\nOrdinary regression, and general issues with GLMS: Weisberg: Applied Linear Regression (https://www.wiley.com/en-br/shop/general-introductory-statistics/applied-linear-regression-4th-edition-p-9781118386088); Fox: Applied Regression Analysis and Generalized Linear Models (https://collegepublishing.sagepub.com/products/applied-regression-analysis-and-generalized-linear-models-3-237254)\n\n\n\n\nSpecific to logistic regression: Hosmer and Lemeshow: Applied Logistic Regression (https://onlinelibrary.wiley.com/doi/book/10.1002/9781118548387)\n\n\n\n\n\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.\n\n\n\n\nLet's consider a logistic model with a indicator \"exposure\" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.\n\n\n\n\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:\n\n\n\n\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$\n\n\n\n\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:\n\n\n\n\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$\n\n\n\n\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.\n\n\n\n\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.\n\n\n\n\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.", "answer_url": "https://stats.stackexchange.com/a/677039", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T18:54:15+00:00", "is_accepted": false, "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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-01T18:54:15+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "1C96DBED-01C4-408D-8ADC-73D384ED5F3D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1C96DBED-01C4-408D-8ADC-73D384ED5F3D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T01:11:13+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB91F46E-AE98-4B27-B146-70EE8551482D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB91F46E-AE98-4B27-B146-70EE8551482D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mastropi", "profile_url": "https://stats.stackexchange.com/users/217355/mastropi", "user_type": "registered"}, "created_at": "2026-09-02T11:36:08+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB25A932-6CB9-4775-9305-5FA8CA11BEE5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB25A932-6CB9-4775-9305-5FA8CA11BEE5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T19:56:28+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "0C25F4DB-255E-4A29-8217-4F07665C4131", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/0C25F4DB-255E-4A29-8217-4F07665C4131/view-source"}], "score": 5, "updated_at": "2026-09-02T19:56:28+00:00"}], "domain": "statistics", "external_links": ["https://archive.org/details/dataanalysisregr0000most", "https://bookdown.org/roback/bookdown-BeyondMLR/", "https://collegepublishing.sagepub.com/products/applied-regression-analysis-and-generalized-linear-models-3-237254", "https://onlinelibrary.wiley.com/doi/book/10.1002/9781118548387", "https://www.wiley.com/en-br/shop/general-introductory-statistics/applied-linear-regression-4th-edition-p-9781118386088"], "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": "Konstantinos Gkirgkiris", "question_author_url": "https://stats.stackexchange.com/users/466987/konstantinos-gkirgkiris", "question_author_user_type": "registered", "question_created_at": "2026-08-31T16:28:24+00:00", "question_html": "Logistic regression:
\nglm(Y ~ X * Z + C1 + C2, family = binomial)\n\nI know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.
\nDoes this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the ordinary null?
\nAny textbook or paper that states this explicitly?
\n", "question_id": 677023, "question_license": "CC BY-SA 4.0", "question_score": 6, "question_text": "Logistic regression:\n\n\n\n\nglm(Y ~ X * Z + C1 + C2, family = binomial)\n\n\n\n\n\nI know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.\n\n\n\n\nDoes this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the ordinary null?\n\n\n\n\nAny textbook or paper that states this explicitly?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Konstantinos Gkirgkiris", "profile_url": "https://stats.stackexchange.com/users/466987/konstantinos-gkirgkiris", "user_type": "registered"}, "created_at": "2026-08-31T16:28:24+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "625D283B-6E8B-49CC-9D39-A419938D290E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/625D283B-6E8B-49CC-9D39-A419938D290E/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-01T00:39:35+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "7B7DEF62-2D77-4CB5-B284-7203069E17E3", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/7B7DEF62-2D77-4CB5-B284-7203069E17E3/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677023/does-an-interaction-term-affect-the-interpretation-of-the-other-covariates", "split": "train", "split_group": "0a1bcd73d1b98426209a0c28354537686e3002366acc568482c8aa33acc3129f", "tags": ["regression", "r", "interaction"], "thread_id": "stats:677023", "title": "Does an interaction term affect the interpretation of the other covariates?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677058, "sha256": "212e2ceb3c850f513b3e1edb810ceb6144894589560f4942090495af1165b2a0", "source_url": "https://stats.stackexchange.com/questions/677058/instability-of-gap-statistics"}], "other_answers": [], "product": "code_qa", "question": "While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:\n\n\n\n\nlibrary(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n\n\n\n\n\nNote that I have increased the number of initial random configurations (nstart) in kmeans() to 50 in order to remove the randomness from the clustering and I have set d.power=2 as recommended in the documentation of clusGap(). I turns out that the results are quite random and that the true number of clusters is never found:\n\n\n\n\ngs\n 4 5 \n10 10\n\n\n\n\n\nIs this a well-known behavior of the gap statistics? What can be recommended instead that has a less random behavior?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677058", "selected_answer": {"answer_html": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.
\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the "true" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the "parametric bootstrap" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the "Tib2001SEmax" criterion.
\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. "Tib2001SEmax" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that "Tib2001SEmax" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer "globalSEmax" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to "spherical and same within-cluster variation".
\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.
\n", "answer_id": 677059, "answer_text": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.\n\n\n\n\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the \"true\" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the \"parametric bootstrap\" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the \"Tib2001SEmax\" criterion.\n\n\n\n\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. \"Tib2001SEmax\" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that \"Tib2001SEmax\" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer \"globalSEmax\" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to \"spherical and same within-cluster variation\".\n\n\n\n\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.", "answer_url": "https://stats.stackexchange.com/a/677059", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-03T12:08:52+00:00", "is_accepted": false, "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": 677058, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:08:52+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "14E907BD-0137-4FA2-93E2-A5C3763E1F24", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/14E907BD-0137-4FA2-93E2-A5C3763E1F24/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:19:59+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "892FF292-2C1A-4474-9F3F-50E0D978AB75", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/892FF292-2C1A-4474-9F3F-50E0D978AB75/view-source"}], "score": 5, "updated_at": "2026-09-03T12:19:59+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.
\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the "true" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the "parametric bootstrap" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the "Tib2001SEmax" criterion.
\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. "Tib2001SEmax" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that "Tib2001SEmax" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer "globalSEmax" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to "spherical and same within-cluster variation".
\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.
\n", "answer_id": 677059, "answer_text": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.\n\n\n\n\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the \"true\" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the \"parametric bootstrap\" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the \"Tib2001SEmax\" criterion.\n\n\n\n\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. \"Tib2001SEmax\" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that \"Tib2001SEmax\" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer \"globalSEmax\" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to \"spherical and same within-cluster variation\".\n\n\n\n\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.", "answer_url": "https://stats.stackexchange.com/a/677059", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-03T12:08:52+00:00", "is_accepted": false, "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": 677058, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:08:52+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "14E907BD-0137-4FA2-93E2-A5C3763E1F24", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/14E907BD-0137-4FA2-93E2-A5C3763E1F24/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:19:59+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "892FF292-2C1A-4474-9F3F-50E0D978AB75", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/892FF292-2C1A-4474-9F3F-50E0D978AB75/view-source"}], "score": 5, "updated_at": "2026-09-03T12:19:59+00:00"}], "domain": "statistics", "external_links": [], "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": "cdalitz", "question_author_url": "https://stats.stackexchange.com/users/244807/cdalitz", "question_author_user_type": "registered", "question_created_at": "2026-09-03T11:39:13+00:00", "question_html": "While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:
\nlibrary(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,"gap"],res$Tab[,"SE.sim"], method="Tibs2001SEmax")\n}\ntable(gs)\n\nNote that I have increased the number of initial random configurations (nstart) in kmeans() to 50 in order to remove the randomness from the clustering and I have set d.power=2 as recommended in the documentation of clusGap(). I turns out that the results are quite random and that the true number of clusters is never found:
gs\n 4 5 \n10 10\n\nIs this a well-known behavior of the gap statistics? What can be recommended instead that has a less random behavior?
\n", "question_id": 677058, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:\n\n\n\n\nlibrary(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n\n\n\n\n\nNote that I have increased the number of initial random configurations (nstart) in kmeans() to 50 in order to remove the randomness from the clustering and I have set d.power=2 as recommended in the documentation of clusGap(). I turns out that the results are quite random and that the true number of clusters is never found:\n\n\n\n\ngs\n 4 5 \n10 10\n\n\n\n\n\nIs this a well-known behavior of the gap statistics? What can be recommended instead that has a less random behavior?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "cdalitz", "profile_url": "https://stats.stackexchange.com/users/244807/cdalitz", "user_type": "registered"}, "created_at": "2026-09-03T11:39:13+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "3E9F6246-CC0F-4366-81BC-A6A0C78ED5A6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3E9F6246-CC0F-4366-81BC-A6A0C78ED5A6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-09-03T16:10:42+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "59954FB6-BFDE-42B7-830F-F7F99AFF9B21", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/59954FB6-BFDE-42B7-830F-F7F99AFF9B21/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-03T19:42:12+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "BF52DD34-5A10-4522-BC49-DDE61AD72E0C", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/BF52DD34-5A10-4522-BC49-DDE61AD72E0C/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677058/instability-of-gap-statistics", "split": "train", "split_group": "9571fdd41c91a5063c5d50dd6546728a0beeeb9ea033a144996338e69417909e", "tags": ["clustering"], "thread_id": "stats:677058", "title": "Instability of gap statistics"}} {"accepted_answer": {"answer_html": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:
library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv("https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = "re"),\n data = shiny_toad,\n method = "REML",\n family = nb(link = "log"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat("--- Temporal Autocorrelation Test for Season:", season, "---\\n")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste("Season:", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n
#> --- Temporal Autocorrelation Test for Season: WET ---\n\n
This is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.
\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):
\nHow to account for temporal autocorrelation in logistic regression with longitudinal data?
\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data?
\nCreated on 2026-09-03 with reprex v2.1.1
\n", "answer_id": 677064, "answer_text": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:\n\n\n\n\nlibrary(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\n\n\n\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/6r3XH8BM.png]\n\n\n\n\n#> --- Temporal Autocorrelation Test for Season: WET ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/LfmXWxdr.png]\n\n\n\n\nThis is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.\n\n\n\n\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):\n\n\n\n\n\n\n\nHow to account for temporal autocorrelation in logistic regression with longitudinal data? (https://stats.stackexchange.com/q/395445)\n\n\n\n\n\n\n\n\n\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data? (https://stats.stackexchange.com/q/664160)\n\n\n\n\n\n\n\n\nCreated on 2026-09-03 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677064", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-04T03:00:41+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": 677062, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-09-04T03:00:41+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "33E2BC86-F580-4F03-B6B5-57A2E864905B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/33E2BC86-F580-4F03-B6B5-57A2E864905B/view-source"}], "score": 2, "updated_at": "2026-09-04T03:00:41+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) + \n s(DO, bs=\"ts\", k=5) +\n \n s(ave_sav, by = fDiet_presence) +\n fDiet_presence + \n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n##################\n\ndf <- sort(diff(sort(as.Date(shiny_toad$Date))), decreasing = TRUE)\n\n# 1. Generate the base simulated residuals once\nres <- simulateResiduals(by)\n\n# 2. Loop through each Season safely by manually subsetting the DHARMa object\nfor (Season in unique(shiny_toad$fSeason)) {\n \n cat(\"\\n--- Temporal Autocorrelation Test for Season:\", Season, \"---\\n\")\n \n # Create a logical index for the current Season\n Season_idx <- shiny_toad$fSeason == Season\n \n # Copy the base DHARMa object structure\n res_Season <- res\n \n # Manually slice all internal arrays to match only this Season's rows\n res_Season$scaledResiduals <- res$scaledResiduals[Season_idx]\n res_Season$simulatedResponse <- res$simulatedResponse[Season_idx, , drop = FALSE]\n res_Season$observedResponse <- res$observedResponse[Season_idx]\n res_Season$fittedPredictedResponse <- res$fittedPredictedResponse[Season_idx]\n res_Season$nObs <- sum(Season_idx)\n \n # Group the Season's residuals by CYR\n res_grouped <- recalculateResiduals(res_Season, group = shiny_toad$CYR[Season_idx])\n \n # Open a new plot window so they don't overwrite each other\n dev.new() \n \n # Run the test and plot\n testTemporalAutocorrelation(res_grouped, time = unique(shiny_toad$CYR[Season_idx]))\n \n # Add a title to the plot window to identify the Season\n mtext(paste(\"Season:\", Season), side = 3, line = -2, outer = TRUE, font = 2, cex = 1.2)\n}\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677062, "sha256": "6edeefd4ab605c4f39a1340c1da8a710ffcf2e5591146a18e6b1a6c23f6c035b", "source_url": "https://stats.stackexchange.com/questions/677062/how-to-check-for-temporal-auto-correlation-for-each-time-series-separately"}, {"block_index": 0, "code_text": "library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677064, "sha256": "9324af2a552b94568ef3ddb3edf3d4c556edf3bd4e0e44c525a685c1d49c936a", "source_url": "https://stats.stackexchange.com/a/677064"}, {"block_index": 1, "code_text": "fit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677064, "sha256": "ca23f80d15ba30c2d8cd5925020be422e07caf3b2ca9846a157a7530fe46c00b", "source_url": "https://stats.stackexchange.com/a/677064"}, {"block_index": 2, "code_text": "#> --- Temporal Autocorrelation Test for Season: WET ---\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677064, "sha256": "155479bd97793ff820e887b9df16a410ad412de6fcdae2902b1ee6bb854a35f7", "source_url": "https://stats.stackexchange.com/a/677064"}], "other_answers": [], "product": "code_qa", "question": "I have 2 time series in abundance that I'm modeling by a 2-level factor in mgcv , by \"fSeason\" (wet/dry), and following advice here (https://stackoverflow.com/questions/78182559/autocorrelation-in-gam-r), I should be splitting a test for auto-correlation by each factor level. I'm just not sure how to do that. Apologies for posting ChatGPT code, but I've been unsuccessful in my search everywhere else. DHARMa does have a test, but I was told it's only for a single time series. I don't think I can use the traditional AR(1) as the data are irregularly-spaced and I've never taken Bayesian statistics. Anyway, for now I'm just asking if the code AI generated is correctly identifying that I do have some, albeit weak, but significant temporal auto-correlation in the wet season. Any general advice is also welcome!\n\n\n\n\nData here (https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv).\n\n\n\n\nlibrary(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) + \n s(DO, bs=\"ts\", k=5) +\n \n s(ave_sav, by = fDiet_presence) +\n fDiet_presence + \n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n##################\n\ndf <- sort(diff(sort(as.Date(shiny_toad$Date))), decreasing = TRUE)\n\n# 1. Generate the base simulated residuals once\nres <- simulateResiduals(by)\n\n# 2. Loop through each Season safely by manually subsetting the DHARMa object\nfor (Season in unique(shiny_toad$fSeason)) {\n \n cat(\"\\n--- Temporal Autocorrelation Test for Season:\", Season, \"---\\n\")\n \n # Create a logical index for the current Season\n Season_idx <- shiny_toad$fSeason == Season\n \n # Copy the base DHARMa object structure\n res_Season <- res\n \n # Manually slice all internal arrays to match only this Season's rows\n res_Season$scaledResiduals <- res$scaledResiduals[Season_idx]\n res_Season$simulatedResponse <- res$simulatedResponse[Season_idx, , drop = FALSE]\n res_Season$observedResponse <- res$observedResponse[Season_idx]\n res_Season$fittedPredictedResponse <- res$fittedPredictedResponse[Season_idx]\n res_Season$nObs <- sum(Season_idx)\n \n # Group the Season's residuals by CYR\n res_grouped <- recalculateResiduals(res_Season, group = shiny_toad$CYR[Season_idx])\n \n # Open a new plot window so they don't overwrite each other\n dev.new() \n \n # Run the test and plot\n testTemporalAutocorrelation(res_grouped, time = unique(shiny_toad$CYR[Season_idx]))\n \n # Add a title to the plot window to identify the Season\n mtext(paste(\"Season:\", Season), side = 3, line = -2, outer = TRUE, font = 2, cex = 1.2)\n}\n\n\n\n\n\n\nSite locations were haphazardly chosen (before my time) to monitor changes in fish abundance due to the construction of new canals (data posted here not collected with this statistical model/set of hypotheses in mind - its just available). Timing of surveys is based on tide level (need at least 60 cm/2 ft of water to survey near shore during the day (during reg. working hours). It takes about 4-7 days to survey every site start-to-finish. Timing is also weather dependant. Also it takes 4-5 months to sort, ID, weigh and measure everything we catch. March/Sept is just avoid swimming in really cold water and give time between sample processesing of new data.\n\n\n\n\n[image: ChatGPT result; source: https://i.sstatic.net/XIgn1m2c.png]", "record_id": "Scientific-Code-and-Analysis-QA:stats:677062", "selected_answer": {"answer_html": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:
library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv("https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = "re"),\n data = shiny_toad,\n method = "REML",\n family = nb(link = "log"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat("--- Temporal Autocorrelation Test for Season:", season, "---\\n")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste("Season:", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n
#> --- Temporal Autocorrelation Test for Season: WET ---\n\n
This is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.
\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):
\nHow to account for temporal autocorrelation in logistic regression with longitudinal data?
\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data?
\nCreated on 2026-09-03 with reprex v2.1.1
\n", "answer_id": 677064, "answer_text": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:\n\n\n\n\nlibrary(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\n\n\n\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/6r3XH8BM.png]\n\n\n\n\n#> --- Temporal Autocorrelation Test for Season: WET ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/LfmXWxdr.png]\n\n\n\n\nThis is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.\n\n\n\n\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):\n\n\n\n\n\n\n\nHow to account for temporal autocorrelation in logistic regression with longitudinal data? (https://stats.stackexchange.com/q/395445)\n\n\n\n\n\n\n\n\n\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data? (https://stats.stackexchange.com/q/664160)\n\n\n\n\n\n\n\n\nCreated on 2026-09-03 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677064", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-04T03:00:41+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": 677062, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-09-04T03:00:41+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "33E2BC86-F580-4F03-B6B5-57A2E864905B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/33E2BC86-F580-4F03-B6B5-57A2E864905B/view-source"}], "score": 2, "updated_at": "2026-09-04T03:00:41+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677064, "answers": [{"answer_html": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:
library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv("https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = "re"),\n data = shiny_toad,\n method = "REML",\n family = nb(link = "log"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat("--- Temporal Autocorrelation Test for Season:", season, "---\\n")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste("Season:", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n
#> --- Temporal Autocorrelation Test for Season: WET ---\n\n
This is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.
\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):
\nHow to account for temporal autocorrelation in logistic regression with longitudinal data?
\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data?
\nCreated on 2026-09-03 with reprex v2.1.1
\n", "answer_id": 677064, "answer_text": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:\n\n\n\n\nlibrary(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\n\n\n\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/6r3XH8BM.png]\n\n\n\n\n#> --- Temporal Autocorrelation Test for Season: WET ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/LfmXWxdr.png]\n\n\n\n\nThis is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.\n\n\n\n\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):\n\n\n\n\n\n\n\nHow to account for temporal autocorrelation in logistic regression with longitudinal data? (https://stats.stackexchange.com/q/395445)\n\n\n\n\n\n\n\n\n\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data? (https://stats.stackexchange.com/q/664160)\n\n\n\n\n\n\n\n\nCreated on 2026-09-03 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677064", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-04T03:00:41+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": 677062, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-09-04T03:00:41+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "33E2BC86-F580-4F03-B6B5-57A2E864905B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/33E2BC86-F580-4F03-B6B5-57A2E864905B/view-source"}], "score": 2, "updated_at": "2026-09-04T03:00:41+00:00"}], "domain": "statistics", "external_links": ["https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv", "https://i.sstatic.net/6r3XH8BM.png", "https://i.sstatic.net/LfmXWxdr.png", "https://i.sstatic.net/XIgn1m2c.png", "https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv", "https://reprex.tidyverse.org"], "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": "Nate", "question_author_url": "https://stats.stackexchange.com/users/337106/nate", "question_author_user_type": "registered", "question_created_at": "2026-09-03T14:57:31+00:00", "question_html": "I have 2 time series in abundance that I'm modeling by a 2-level factor in mgcv , by "fSeason" (wet/dry), and following advice here, I should be splitting a test for auto-correlation by each factor level. I'm just not sure how to do that. Apologies for posting ChatGPT code, but I've been unsuccessful in my search everywhere else. DHARMa does have a test, but I was told it's only for a single time series. I don't think I can use the traditional AR(1) as the data are irregularly-spaced and I've never taken Bayesian statistics. Anyway, for now I'm just asking if the code AI generated is correctly identifying that I do have some, albeit weak, but significant temporal auto-correlation in the wet season. Any general advice is also welcome!
Data here.
\nlibrary(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs="ts", k=5) + \n s(DO, bs="ts", k=5) +\n \n s(ave_sav, by = fDiet_presence) +\n fDiet_presence + \n \n s(fSite, bs="re"),\n \n data = shiny_toad,\n method = "REML", \n family = nb(link = "log"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n##################\n\ndf <- sort(diff(sort(as.Date(shiny_toad$Date))), decreasing = TRUE)\n\n# 1. Generate the base simulated residuals once\nres <- simulateResiduals(by)\n\n# 2. Loop through each Season safely by manually subsetting the DHARMa object\nfor (Season in unique(shiny_toad$fSeason)) {\n \n cat("\\n--- Temporal Autocorrelation Test for Season:", Season, "---\\n")\n \n # Create a logical index for the current Season\n Season_idx <- shiny_toad$fSeason == Season\n \n # Copy the base DHARMa object structure\n res_Season <- res\n \n # Manually slice all internal arrays to match only this Season's rows\n res_Season$scaledResiduals <- res$scaledResiduals[Season_idx]\n res_Season$simulatedResponse <- res$simulatedResponse[Season_idx, , drop = FALSE]\n res_Season$observedResponse <- res$observedResponse[Season_idx]\n res_Season$fittedPredictedResponse <- res$fittedPredictedResponse[Season_idx]\n res_Season$nObs <- sum(Season_idx)\n \n # Group the Season's residuals by CYR\n res_grouped <- recalculateResiduals(res_Season, group = shiny_toad$CYR[Season_idx])\n \n # Open a new plot window so they don't overwrite each other\n dev.new() \n \n # Run the test and plot\n testTemporalAutocorrelation(res_grouped, time = unique(shiny_toad$CYR[Season_idx]))\n \n # Add a title to the plot window to identify the Season\n mtext(paste("Season:", Season), side = 3, line = -2, outer = TRUE, font = 2, cex = 1.2)\n}\n\n\nSite locations were haphazardly chosen (before my time) to monitor changes in fish abundance due to the construction of new canals (data posted here not collected with this statistical model/set of hypotheses in mind - its just available). Timing of surveys is based on tide level (need at least 60 cm/2 ft of water to survey near shore during the day (during reg. working hours). It takes about 4-7 days to survey every site start-to-finish. Timing is also weather dependant. Also it takes 4-5 months to sort, ID, weigh and measure everything we catch. March/Sept is just avoid swimming in really cold water and give time between sample processesing of new data.
\n
I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n", "answer_id": 677089, "answer_text": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n", "answer_id": 677089, "answer_text": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n", "answer_id": 677089, "answer_text": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.
Data here
\nshiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = "no food")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs="ts", k=5) +\n s(DO, bs="ts", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs="re"),\n \n data = shiny_toad,\n method = "REML", \n family = nb(link = "log"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n\n\n", "question_id": 677079, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.\n\n\n\n\nData here (https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv)\n\n\n\n\nshiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = \"no food\")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) +\n s(DO, bs=\"ts\", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/JpiINT52.png] (https://i.sstatic.net/JpiINT52.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-05T17:50:46+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "62485478-1E70-4507-A25A-EFD7CF98BE71", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/62485478-1E70-4507-A25A-EFD7CF98BE71/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-05T18:00:15+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "20C1E059-9409-4237-A047-3AC90CDF12F1", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/20C1E059-9409-4237-A047-3AC90CDF12F1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-06T11:10:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "218741D1-87E1-45D3-9356-2175B506F115", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/218741D1-87E1-45D3-9356-2175B506F115/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-06T16:02:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "68679B7E-46AA-465C-8DEB-E7300F26A45C", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/68679B7E-46AA-465C-8DEB-E7300F26A45C/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-06T16:44:53+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "FCE33A0B-2FF0-443A-AAE5-C039C64F1D4A", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/FCE33A0B-2FF0-443A-AAE5-C039C64F1D4A/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677079/dharma-are-long-tails-in-dispersion-plot-a-problem", "split": "train", "split_group": "04a77f3456ebfb67020241072d2e6012e18b8e493f7d3df8ca4d468735284bb3", "tags": ["overfitting", "mgcv", "overdispersion", "dharma"], "thread_id": "stats:677079", "title": "DHARMa: Are long tails in dispersion plot a problem?"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "modules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677095, "sha256": "1d618fa130fbed5952b989d4c334bd6f29b52043ec44b220abbe1a7348e72701", "source_url": "https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult"}], "other_answers": [], "product": "code_qa", "question": "I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.\n\n\n\n\nI have individual student data, but some aggregated dummy data would be:\n\n\n\n\nmodules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\n\n\n\n\nAnd the questions I would like to ask are\n\n\n\n\n\nIs the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?\n\n\n\n\nIs the proportion of students who get an F grade in FR202 the same as the proportion of students who get an F grade in other xx200 level courses?\n\n\n\n\n\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science (https://moderndive.com/8-confidence-intervals.html) started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).\n\n\n\n\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, (https://www.allendowney.com/blog/2024/10/15/bootstrapping-a-proportion/) Bootstrap intervals for the single proportion – corp.ling.stats (https://corplingstats.wordpress.com/2024/12/12/bootstrap-intervals/)) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.\n\n\n\n\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.\n\n\n\n\n\nAre Wilson intervals the right approach for these sorts of questions?\n\n\n\n\nGiven that I sometimes have small numbers (<30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (Correcting for continuity – corp.ling.stats (https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/)), is that right?\n\n\n\n\nAny pointers on how to adjust for multiple comparisons, given that I’ll be calculating two CIs each (prop A and prop F) for multiple courses (e.g. each of 7 MA courses against the other 6 MA courses)?\n\n\n\n\n\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.\n\n\n\n\nThank you.", "record_id": "Scientific-Code-and-Analysis-QA:stats:677095", "selected_answer": {"answer_html": "Welcome to CV!
\nSo you want to compare 2 proportions; e.g. “Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?”.
\nWell, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (aka crosstab). And the “canonical” tests are either a chi-square test, or a Fisher-exact test (aka Fisher-0Irwin test).
\nNow, using binomial CI’s will not really answer your 2 questions, unless the answer is obvious” if the 2 CI’s do not overlap, you have a significant difference. And if they overlap to a large extent, you do not have a significant difference. But in between, you can not simply eyeball the CI’s.
\nNow, given that you are dealing with (very?) low proportions or counts (how many F’s in a given class? Maybe 2-3?), the chi-square test is not recommended (it is based on a normal approximation, which is not warranted for such low proportions/counts). Nor for that matter are CI’s based on normal approximations, a group the Wilson CI belongs to. And forget about continuity corrections, they do not work properly with very small proportions.
\nSo you are left with the Fisher-exact test, or some newer versions of it (which are less “conservative, while remaining “exact”, that is based on exactly the binomial distribution), such as the Blaker test.
But there is a subtlety in what you are trying to compare. On one hand, you have the proportion of A’s in one class: easy. On the other hand you have the proportion of A’s in all other MA courses (the scenario is the same for the other question, so I will only address the first). How do you express that 2nd proportion?
\nOne option is to simply take the count of all A grades in all other MA courses, and the count of all students enrolled in all other MA classes. And then you can/should indeed use a Fisher-exact (or a Blaker-exact) test. But this will weight each student equally, but not each class (the classes with a large enrollment are more heavily weighted than the classes with a low enrollment). That may be what you want (as it reflects the experience of all students enrolled in all other MA classes), but it may not.\nAn alternative would be to look at all the proportions in all other MA classes, and take the average of these proportions. This weights all classes equally (but not all students). In that case, your test can be done with a single CI. You compute an binomial CI (again using an exact method given your possibly low proportions/counts), and simply see if the average proportion in included in that CI. If it is not, you have established a significant difference (at what ever significance level you chose for the CI).
Last, you ask about multiple comparisons. The fact that you compute multiple CI’s is not relevant; multiple comparisons only occur when you are making a comparison to a significance level (or checking if a CI contains 0, or 1).. And since you seem to only have 2 questions, then you are only making 2 comparisons.
\nThe cautious thing to do would be to use a multiple comparison correction (MCC). Given only 2 comparisons, just use Bonferroni, and halve your significance level.
\nBut bolder statisticians could argue that your 2 hypotheses are different, and independent. And therefore, a MCC is not warranted... (should a researcher correct for all the various hypotheses he/she will test in their career?). So depending on your ultimate goal (why only these 2 questions? what are you really trying to show), you may be able to dispense with a MCC.
Welcome to CV!
\nSo you want to compare 2 proportions; e.g. “Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?”.
\nWell, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (aka crosstab). And the “canonical” tests are either a chi-square test, or a Fisher-exact test (aka Fisher-0Irwin test).
\nNow, using binomial CI’s will not really answer your 2 questions, unless the answer is obvious” if the 2 CI’s do not overlap, you have a significant difference. And if they overlap to a large extent, you do not have a significant difference. But in between, you can not simply eyeball the CI’s.
\nNow, given that you are dealing with (very?) low proportions or counts (how many F’s in a given class? Maybe 2-3?), the chi-square test is not recommended (it is based on a normal approximation, which is not warranted for such low proportions/counts). Nor for that matter are CI’s based on normal approximations, a group the Wilson CI belongs to. And forget about continuity corrections, they do not work properly with very small proportions.
\nSo you are left with the Fisher-exact test, or some newer versions of it (which are less “conservative, while remaining “exact”, that is based on exactly the binomial distribution), such as the Blaker test.
But there is a subtlety in what you are trying to compare. On one hand, you have the proportion of A’s in one class: easy. On the other hand you have the proportion of A’s in all other MA courses (the scenario is the same for the other question, so I will only address the first). How do you express that 2nd proportion?
\nOne option is to simply take the count of all A grades in all other MA courses, and the count of all students enrolled in all other MA classes. And then you can/should indeed use a Fisher-exact (or a Blaker-exact) test. But this will weight each student equally, but not each class (the classes with a large enrollment are more heavily weighted than the classes with a low enrollment). That may be what you want (as it reflects the experience of all students enrolled in all other MA classes), but it may not.\nAn alternative would be to look at all the proportions in all other MA classes, and take the average of these proportions. This weights all classes equally (but not all students). In that case, your test can be done with a single CI. You compute an binomial CI (again using an exact method given your possibly low proportions/counts), and simply see if the average proportion in included in that CI. If it is not, you have established a significant difference (at what ever significance level you chose for the CI).
Last, you ask about multiple comparisons. The fact that you compute multiple CI’s is not relevant; multiple comparisons only occur when you are making a comparison to a significance level (or checking if a CI contains 0, or 1).. And since you seem to only have 2 questions, then you are only making 2 comparisons.
\nThe cautious thing to do would be to use a multiple comparison correction (MCC). Given only 2 comparisons, just use Bonferroni, and halve your significance level.
\nBut bolder statisticians could argue that your 2 hypotheses are different, and independent. And therefore, a MCC is not warranted... (should a researcher correct for all the various hypotheses he/she will test in their career?). So depending on your ultimate goal (why only these 2 questions? what are you really trying to show), you may be able to dispense with a MCC.
I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.
\nI have individual student data, but some aggregated dummy data would be:
\nmodules <- c(\n "MA101","MA102","MA103","MA201","MA202","MA301","MA302",\n "FR101","FR102","FR104","FR201","FR202","FR203","FR301",\n "EN101","EN102","EN201","EN202","EN203","EN301","EN302"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\nAnd the questions I would like to ask are
\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).
\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, Bootstrap intervals for the single proportion – corp.ling.stats) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.
\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.
\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.
\nThank you.
\n", "question_id": 677095, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.\n\n\n\n\nI have individual student data, but some aggregated dummy data would be:\n\n\n\n\nmodules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\n\n\n\n\nAnd the questions I would like to ask are\n\n\n\n\n\nIs the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?\n\n\n\n\nIs the proportion of students who get an F grade in FR202 the same as the proportion of students who get an F grade in other xx200 level courses?\n\n\n\n\n\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science (https://moderndive.com/8-confidence-intervals.html) started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).\n\n\n\n\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, (https://www.allendowney.com/blog/2024/10/15/bootstrapping-a-proportion/) Bootstrap intervals for the single proportion – corp.ling.stats (https://corplingstats.wordpress.com/2024/12/12/bootstrap-intervals/)) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.\n\n\n\n\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.\n\n\n\n\n\nAre Wilson intervals the right approach for these sorts of questions?\n\n\n\n\nGiven that I sometimes have small numbers (<30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (Correcting for continuity – corp.ling.stats (https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/)), is that right?\n\n\n\n\nAny pointers on how to adjust for multiple comparisons, given that I’ll be calculating two CIs each (prop A and prop F) for multiple courses (e.g. each of 7 MA courses against the other 6 MA courses)?\n\n\n\n\n\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.\n\n\n\n\nThank you.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "LST", "profile_url": "https://stats.stackexchange.com/users/516373/lst", "user_type": "registered"}, "created_at": "2026-09-07T16:47:08+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "77370A41-A452-40D5-9FE9-E2D1C2A53F6B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/77370A41-A452-40D5-9FE9-E2D1C2A53F6B/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult", "split": "train", "split_group": "539d92a20e4941595f8fd87a1112f78fb0bb6db32af014f84a6cccc0e55d9727", "tags": ["confidence-interval", "proportion"], "thread_id": "stats:677095", "title": "Testing differences in proportions - Wilson CIs, continuity corrections and multiple comparisons"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677129, "sha256": "2709c370d4eb7a49f17b14941e5fe040beff65d0a68e6bd750cb444b39496f9e", "source_url": "https://stats.stackexchange.com/questions/677129/what-mixed-model-do-i-need-to-use-for-my-analysis"}], "other_answers": [], "product": "code_qa", "question": "I have been working on analysing ecological data for different countries (within each country there are two groups (grazed/ungrazed) and plots (5 per group) which contain subplots (pseudoreplicates)\n\n\n\n\nMy sample size: 9 countries with each 2 groups of 5 plots with 4 subplots, so 20 measurepoints per group, 40 measure points per country\n\n\n\n\nI want to know what the effect of grazers are for each measurement at each study site (country). And have decided to go for a mixed model, since I have pseudoreplicates to account for.\n\n\n\n\nI started with a Linear Mixed Model, but the residuals were not normally distributed. I have now log transformed my data.\n\n\n\n\nlibrary(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n\n\n\n\n\nI made a qqnorm plot for the residuals and it looked a lot better, but the shapiro.test gave a p-value of 0.01.\n\n\n\n\nsd_depth = standard deviation values (I calculated soil depth for 50 steps, each step a separate measurement, and calculated the standard deviation per subplot of these measurements).\n\n\n\n\nMy question is:\n\n\n\n\n\nIs that p-value enough to fit the Linear mixed model anyway?\n\n\n\n\nDo I need to use another model, for example GLMM? Which distribution do I need to choose then? And do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)\n\n\n\n\nWhat are the considerations for choosing families for distribution models (because I have other data that I need to analyse in a similar way), tips for websites/articles that explain this in a clear way are welcome too!", "record_id": "Scientific-Code-and-Analysis-QA:stats:677129", "selected_answer": {"answer_html": "Putting together the comments:
\n\n\nIs that p-value enough to fit the Linear mixed model anyway?
\n
Don't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get "statistically significant" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the "statistical significance" criterion. See this page.
\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.
\n\n\nDo I need to use another model, for example GLMM? ...
\n
Standard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.
\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions, while the standard deviation estimates have chi distributions. Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.
\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?
\n
The type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer succinctly summarizes major possibilities.
\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family.
\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)
\n
Checking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package provides useful tools for that, based on simulations from the model and the observed data.
*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.
\n", "answer_id": 677144, "answer_text": "Putting together the comments:\n\n\n\n\n\n\n\nIs that p-value enough to fit the Linear mixed model anyway?\n\n\n\n\n\n\n\nDon't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get \"statistically significant\" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the \"statistical significance\" criterion. See this page (https://stats.stackexchange.com/q/2492/28500).\n\n\n\n\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.\n\n\n\n\n\n\n\nDo I need to use another model, for example GLMM? ...\n\n\n\n\n\n\n\nStandard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.\n\n\n\n\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions (https://en.wikipedia.org/wiki/Chi-squared_distribution#Occurrence_and_applications), while the standard deviation estimates have chi distributions (https://en.wikipedia.org/wiki/Chi_distribution#). Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation (https://en.wikipedia.org/wiki/Chi-squared_distribution#Asymptotic_properties) to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.\n\n\n\n\n\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?\n\n\n\n\n\n\n\nThe type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer (https://stats.stackexchange.com/a/303592/28500) succinctly summarizes major possibilities.\n\n\n\n\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family (https://en.wikipedia.org/wiki/Gamma_distribution#General).\n\n\n\n\n\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)\n\n\n\n\n\n\n\nChecking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package (https://cran.r-project.org/package=DHARMa) provides useful tools for that, based on simulations from the model and the observed data.\n\n\n\n\n\n\n\n*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.", "answer_url": "https://stats.stackexchange.com/a/677144", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T15:41:29+00:00", "is_accepted": false, "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": 677129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T15:41:29+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "75DAD87A-C4FD-4864-A9E0-3DDADD861A78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/75DAD87A-C4FD-4864-A9E0-3DDADD861A78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T16:40:36+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "9AD56685-4998-4F06-A9D3-E7CA7A2C653C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9AD56685-4998-4F06-A9D3-E7CA7A2C653C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T17:27:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "1778ADB3-A83B-49CF-BDE1-AD32AC57C294", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1778ADB3-A83B-49CF-BDE1-AD32AC57C294/view-source"}], "score": 2, "updated_at": "2026-09-11T17:27:30+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Putting together the comments:
\n\n\nIs that p-value enough to fit the Linear mixed model anyway?
\n
Don't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get "statistically significant" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the "statistical significance" criterion. See this page.
\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.
\n\n\nDo I need to use another model, for example GLMM? ...
\n
Standard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.
\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions, while the standard deviation estimates have chi distributions. Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.
\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?
\n
The type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer succinctly summarizes major possibilities.
\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family.
\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)
\n
Checking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package provides useful tools for that, based on simulations from the model and the observed data.
*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.
\n", "answer_id": 677144, "answer_text": "Putting together the comments:\n\n\n\n\n\n\n\nIs that p-value enough to fit the Linear mixed model anyway?\n\n\n\n\n\n\n\nDon't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get \"statistically significant\" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the \"statistical significance\" criterion. See this page (https://stats.stackexchange.com/q/2492/28500).\n\n\n\n\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.\n\n\n\n\n\n\n\nDo I need to use another model, for example GLMM? ...\n\n\n\n\n\n\n\nStandard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.\n\n\n\n\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions (https://en.wikipedia.org/wiki/Chi-squared_distribution#Occurrence_and_applications), while the standard deviation estimates have chi distributions (https://en.wikipedia.org/wiki/Chi_distribution#). Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation (https://en.wikipedia.org/wiki/Chi-squared_distribution#Asymptotic_properties) to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.\n\n\n\n\n\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?\n\n\n\n\n\n\n\nThe type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer (https://stats.stackexchange.com/a/303592/28500) succinctly summarizes major possibilities.\n\n\n\n\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family (https://en.wikipedia.org/wiki/Gamma_distribution#General).\n\n\n\n\n\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)\n\n\n\n\n\n\n\nChecking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package (https://cran.r-project.org/package=DHARMa) provides useful tools for that, based on simulations from the model and the observed data.\n\n\n\n\n\n\n\n*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.", "answer_url": "https://stats.stackexchange.com/a/677144", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T15:41:29+00:00", "is_accepted": false, "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": 677129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T15:41:29+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "75DAD87A-C4FD-4864-A9E0-3DDADD861A78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/75DAD87A-C4FD-4864-A9E0-3DDADD861A78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T16:40:36+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "9AD56685-4998-4F06-A9D3-E7CA7A2C653C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9AD56685-4998-4F06-A9D3-E7CA7A2C653C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T17:27:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "1778ADB3-A83B-49CF-BDE1-AD32AC57C294", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1778ADB3-A83B-49CF-BDE1-AD32AC57C294/view-source"}], "score": 2, "updated_at": "2026-09-11T17:27:30+00:00"}], "domain": "statistics", "external_links": ["https://cran.r-project.org/package=DHARMa", "https://en.wikipedia.org/wiki/Chi-squared_distribution#Asymptotic_properties", "https://en.wikipedia.org/wiki/Chi-squared_distribution#Occurrence_and_applications", "https://en.wikipedia.org/wiki/Chi_distribution#", "https://en.wikipedia.org/wiki/Gamma_distribution#General"], "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": "S.E123", "question_author_url": "https://stats.stackexchange.com/users/516500/s-e123", "question_author_user_type": "unregistered", "question_created_at": "2026-09-10T14:34:54+00:00", "question_html": "I have been working on analysing ecological data for different countries (within each country there are two groups (grazed/ungrazed) and plots (5 per group) which contain subplots (pseudoreplicates)
\nMy sample size: 9 countries with each 2 groups of 5 plots with 4 subplots, so 20 measurepoints per group, 40 measure points per country
\nI want to know what the effect of grazers are for each measurement at each study site (country). And have decided to go for a mixed model, since I have pseudoreplicates to account for.
\nI started with a Linear Mixed Model, but the residuals were not normally distributed. I have now log transformed my data.
\nlibrary(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n\nI made a qqnorm plot for the residuals and it looked a lot better, but the shapiro.test gave a p-value of 0.01.
\nsd_depth = standard deviation values (I calculated soil depth for 50 steps, each step a separate measurement, and calculated the standard deviation per subplot of these measurements).
\nMy question is:
\nYou are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n", "answer_id": 677139, "answer_text": "You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).", "answer_url": "https://stats.stackexchange.com/a/677139", "author": "J-J-J", "author_url": "https://stats.stackexchange.com/users/164936/j-j-j", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T07:32:22+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T07:32:22+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "23216BD3-49D3-422F-8020-02B7D9CD2B5A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T08:09:51+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "CB4779A0-4EA1-4BB0-99F8-7FFB266F646D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}], "score": 16, "updated_at": "2026-09-11T08:09:51+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677135, "sha256": "d5c814c461b4b9343809a17c4edd3fbbe1bc940093edcb02ae766c0fbd63e802", "source_url": "https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test"}, {"block_index": 1, "code_text": "\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677135, "sha256": "62c4ef27f6977021d1af60c7700550f89ea035d044d29b3bff4641ab21fc10e6", "source_url": "https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test"}, {"block_index": 0, "code_text": "df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677136, "sha256": "496b05ec45239bb68abbf4de00ba9a79c421d6cd74f3703e914e45742d127983", "source_url": "https://stats.stackexchange.com/a/677136"}, {"block_index": 1, "code_text": "(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677136, "sha256": "3b004d026d68a8f11c9c562e695ca7fb83bb343024bf0b626d348d5f77c4bb42", "source_url": "https://stats.stackexchange.com/a/677136"}], "other_answers": [{"answer_html": "Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
Can you provide a {reprex}? I'm getting a warning when I run your code
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\nCreated on 2026-09-10 with reprex v2.1.1
\nEDIT: I was using an old version of R. Here is the reprex from using 4.6
\n(R.version.string)\n#> [1] "R version 4.6.0 (2026-04-24)"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nCreated on 2026-09-11 with reprex v2.1.1
\nNote, no warning. See J-J-J's comment for an explanation.
\n", "answer_id": 677136, "answer_text": "Can you provide a {reprex} (https://reprex.tidyverse.org/)? I'm getting a warning when I run your code\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\n\n\n\n\nCreated on 2026-09-10 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nEDIT: I was using an old version of R. Here is the reprex from using 4.6\n\n\n\n\n(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\n\n\n\n\nCreated on 2026-09-11 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nNote, no warning. See J-J-J's comment for an explanation.", "answer_url": "https://stats.stackexchange.com/a/677136", "author": "Demetri Pananos", "author_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T01:34:59+00:00", "is_accepted": false, "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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-11T01:34:59+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "3461E410-C604-4E94-BBD3-042259374DDF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-11T17:41:38+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "C692081B-A074-4F0B-985E-9AECEBE88DE5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}], "score": 5, "updated_at": "2026-09-11T17:41:38+00:00"}, {"answer_html": "This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.
\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.
\n\nHere we range from evident to speculative:
\nInteger scores, so ties are more likely than otherwise.
\nIs there an upper limit of 32?
\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.
\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?
\n", "answer_id": 677141, "answer_text": "This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.\n\n\n\n\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/7o9W87he.png] (https://i.sstatic.net/7o9W87he.png)\n\n\n\n\nHere we range from evident to speculative:\n\n\n\n\n\n\n\nInteger scores, so ties are more likely than otherwise.\n\n\n\n\n\n\n\n\n\nIs there an upper limit of 32?\n\n\n\n\n\n\n\n\n\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.\n\n\n\n\n\n\n\n\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?", "answer_url": "https://stats.stackexchange.com/a/677141", "author": "Nick Cox", "author_url": "https://stats.stackexchange.com/users/22047/nick-cox", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T08:47:46+00:00", "is_accepted": false, "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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T08:47:46+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "F5E781A6-F63A-4F3B-897E-03303213674F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T09:20:25+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "2F24FDA3-AB03-426F-84C2-A097A0D37730", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}], "score": 7, "updated_at": "2026-09-11T09:20:25+00:00"}], "product": "code_qa", "question": "I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n\n\n\n\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?\n\n\n\n\nHere is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.\n\n\n\n\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```", "record_id": "Scientific-Code-and-Analysis-QA:stats:677135", "selected_answer": {"answer_html": "You are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n", "answer_id": 677139, "answer_text": "You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).", "answer_url": "https://stats.stackexchange.com/a/677139", "author": "J-J-J", "author_url": "https://stats.stackexchange.com/users/164936/j-j-j", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T07:32:22+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T07:32:22+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "23216BD3-49D3-422F-8020-02B7D9CD2B5A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T08:09:51+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "CB4779A0-4EA1-4BB0-99F8-7FFB266F646D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}], "score": 16, "updated_at": "2026-09-11T08:09:51+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677139, "answers": [{"answer_html": "Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
Can you provide a {reprex}? I'm getting a warning when I run your code
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\nCreated on 2026-09-10 with reprex v2.1.1
\nEDIT: I was using an old version of R. Here is the reprex from using 4.6
\n(R.version.string)\n#> [1] "R version 4.6.0 (2026-04-24)"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nCreated on 2026-09-11 with reprex v2.1.1
\nNote, no warning. See J-J-J's comment for an explanation.
\n", "answer_id": 677136, "answer_text": "Can you provide a {reprex} (https://reprex.tidyverse.org/)? I'm getting a warning when I run your code\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\n\n\n\n\nCreated on 2026-09-10 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nEDIT: I was using an old version of R. Here is the reprex from using 4.6\n\n\n\n\n(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\n\n\n\n\nCreated on 2026-09-11 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nNote, no warning. See J-J-J's comment for an explanation.", "answer_url": "https://stats.stackexchange.com/a/677136", "author": "Demetri Pananos", "author_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T01:34:59+00:00", "is_accepted": false, "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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-11T01:34:59+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "3461E410-C604-4E94-BBD3-042259374DDF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-11T17:41:38+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "C692081B-A074-4F0B-985E-9AECEBE88DE5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}], "score": 5, "updated_at": "2026-09-11T17:41:38+00:00"}, {"answer_html": "You are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n", "answer_id": 677139, "answer_text": "You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).", "answer_url": "https://stats.stackexchange.com/a/677139", "author": "J-J-J", "author_url": "https://stats.stackexchange.com/users/164936/j-j-j", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T07:32:22+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T07:32:22+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "23216BD3-49D3-422F-8020-02B7D9CD2B5A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T08:09:51+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "CB4779A0-4EA1-4BB0-99F8-7FFB266F646D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}], "score": 16, "updated_at": "2026-09-11T08:09:51+00:00"}, {"answer_html": "Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.
\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.
\n\nHere we range from evident to speculative:
\nInteger scores, so ties are more likely than otherwise.
\nIs there an upper limit of 32?
\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.
\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?
\n", "answer_id": 677141, "answer_text": "This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.\n\n\n\n\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/7o9W87he.png] (https://i.sstatic.net/7o9W87he.png)\n\n\n\n\nHere we range from evident to speculative:\n\n\n\n\n\n\n\nInteger scores, so ties are more likely than otherwise.\n\n\n\n\n\n\n\n\n\nIs there an upper limit of 32?\n\n\n\n\n\n\n\n\n\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.\n\n\n\n\n\n\n\n\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?", "answer_url": "https://stats.stackexchange.com/a/677141", "author": "Nick Cox", "author_url": "https://stats.stackexchange.com/users/22047/nick-cox", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T08:47:46+00:00", "is_accepted": false, "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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T08:47:46+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "F5E781A6-F63A-4F3B-897E-03303213674F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T09:20:25+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "2F24FDA3-AB03-426F-84C2-A097A0D37730", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}], "score": 7, "updated_at": "2026-09-11T09:20:25+00:00"}], "domain": "statistics", "external_links": ["https://cran.r-project.org/doc/manuals/r-release/NEWS.html", "https://i.sstatic.net/7o9W87he.png", "https://reprex.tidyverse.org", "https://reprex.tidyverse.org/", "https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/"], "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": "DAVID PAUL CAPELLE", "question_author_url": "https://stats.stackexchange.com/users/386267/david-paul-capelle", "question_author_user_type": "registered", "question_created_at": "2026-09-11T01:14:02+00:00", "question_html": "I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n"tbl", "data.frame"))\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?
Here is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.
\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c("tbl_df", "tbl", "data.frame")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```\n\n", "question_id": 677135, "question_license": "CC BY-SA 4.0", "question_score": 10, "question_text": "I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n\n\n\n\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?\n\n\n\n\nHere is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.\n\n\n\n\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DAVID PAUL CAPELLE", "profile_url": "https://stats.stackexchange.com/users/386267/david-paul-capelle", "user_type": "registered"}, "created_at": "2026-09-11T01:14:02+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "93652C25-9FE3-4C77-B0E9-CF7DD58DC50A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/93652C25-9FE3-4C77-B0E9-CF7DD58DC50A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DAVID PAUL CAPELLE", "profile_url": "https://stats.stackexchange.com/users/386267/david-paul-capelle", "user_type": "registered"}, "created_at": "2026-09-11T06:13:00+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "C7E16D39-DC10-460F-B943-B7547B90F63D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C7E16D39-DC10-460F-B943-B7547B90F63D/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-11T09:18:50+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "BC7129B7-4E28-49C0-8308-97D09DE31CA9", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/BC7129B7-4E28-49C0-8308-97D09DE31CA9/view-source"}, {"content_license": null, "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-09-13T11:06:51+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "052E2710-AD21-4AFE-992F-D9FB54C17A14", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/052E2710-AD21-4AFE-992F-D9FB54C17A14/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test", "split": "train", "split_group": "fb4920dde6ede8f339350f0d34d985d9c1dcf8eb8ac2beea3857cb378c76b04b", "tags": ["r", "ties"], "thread_id": "stats:677135", "title": "Why does R not warn about ties in wilcox.test()"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677137, "sha256": "625d3a6019c48761839d6530ecc3c3e86fbd3239c15c955f72192c54f6da8e62", "source_url": "https://stats.stackexchange.com/questions/677137/why-does-a-cubic-b-spline-basis-matrix-contain-so-many-zero-columns"}, {"block_index": 0, "code_text": "library(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = \"l\") ## cosmetic\nmatplot(x_all, basis_matrix, type = \"l\", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677164, "sha256": "889db05ba0b28d8f0e24540e9c3d031ee80a767e206ebb68a5f169c03c9841db", "source_url": "https://stats.stackexchange.com/a/677164"}], "other_answers": [{"answer_html": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:
\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = "l") ## cosmetic\nmatplot(x_all, basis_matrix, type = "l", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)\n\n", "answer_id": 677164, "answer_text": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:\n\n\n\n\n[image: plot of the basis elements of a spline, with the elements that are non-zero at x=1.5 highlighted (solid, thick lines); source: https://i.sstatic.net/7o5ja3We.png] (https://i.sstatic.net/7o5ja3We.png)\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = \"l\") ## cosmetic\nmatplot(x_all, basis_matrix, type = \"l\", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)", "answer_url": "https://stats.stackexchange.com/a/677164", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T20:32:49+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-13T20:32:49+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "EBF57CF7-0E40-482E-A05C-136F42F17A79", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EBF57CF7-0E40-482E-A05C-136F42F17A79/view-source"}], "score": 6, "updated_at": "2026-09-13T20:32:49+00:00"}], "product": "code_qa", "question": "I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.\n\n\n\n\nThe worked example in Ken Koon Wong's blog post \"Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm\", reproduced below:\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n\n\n\n\n\nResult:\n\n\n\n\n## 1 2 3 4 5 6 7 8 9 10 11\n## [1,] 0 0 0 0.02083333 0.4791667 0.4791667 0.02083333 0 0 0 0\n## attr(,\"degree\")\n## [1] 3\n## attr(,\"knots\")\n## [1] -2 -1 0 1 2 3 4 5\n## attr(,\"Boundary.knots\")\n## [1] -3 6\n## attr(,\"intercept\")\n## [1] FALSE\n## attr(,\"class\")\n## [1] \"bs\" \"basis\" \"matrix\"\n\n\n\n\n\nWong explained:\n\n\n\n\n\n\n\nAwesome!!! We have very similar numbers !!! But why are there so many columns? And they’re filled with zeros, reminds me almost like padding. Apparently this is mainly to ensure no issues when x is very close to boundary knots is my understanding. And the way they add these padding depends on degrees + 1 if you use degree = 3, add 1 to it and that would be how many repeats of the numbers of your boundary knots.\n\n\n\n\n\n\n\nBut why are the number of leading and trailing zeros different?\n\n\n\n\nFrom wiki of De Boor's algorithm,\n\n\n\n\n\n\n\nIt follows from i≥0 that k≥p. Similarly, we see in the recursion that the highest queried knot location is at index k+1+p. This means that any knot interval [tk,tk+1) which is actually used must have at least p additional knots before and after. In a computer program, this is typically achieved by repeating the first and last used knot location p times. For example, for p=3 and real knot locations (0,1,2), one would pad the knot vector to (0,0,0,0,1,2,2,2,2).\n\n\n\n\n\n\n\n{which is actually used must have at least p additional knots before and after}<- Then the number of leading and trailing zeros should be the same? i.e. 3+1 = 4\n\n\n\n\n\n\n\nUpdate:\nAccording to the calculation by Ken Koon Wong,\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/v4LeyMo7.png] (https://i.sstatic.net/v4LeyMo7.png)\n\n\n\n\nThe position of knots should be c(-3,-3,-3,-3,-2, -1, 0, 1, 2,2,2,2)?\nAm I correct?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677137", "selected_answer": {"answer_html": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).
\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.
\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.
\n", "answer_id": 677156, "answer_text": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).\n\n\n\n\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.\n\n\n\n\n\n\n\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.", "answer_url": "https://stats.stackexchange.com/a/677156", "author": "Glen_b", "author_url": "https://stats.stackexchange.com/users/805/glen-b", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T02:41:43+00:00", "is_accepted": false, "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": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T02:41:43+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "F103E6FE-AD3D-4F47-A179-708950A92E6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F103E6FE-AD3D-4F47-A179-708950A92E6A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T03:16:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "323EB6A5-54C4-485A-910C-C896C850F031", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/323EB6A5-54C4-485A-910C-C896C850F031/view-source"}], "score": 10, "updated_at": "2026-09-13T03:16:34+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).
\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.
\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.
\n", "answer_id": 677156, "answer_text": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).\n\n\n\n\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.\n\n\n\n\n\n\n\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.", "answer_url": "https://stats.stackexchange.com/a/677156", "author": "Glen_b", "author_url": "https://stats.stackexchange.com/users/805/glen-b", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T02:41:43+00:00", "is_accepted": false, "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": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T02:41:43+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "F103E6FE-AD3D-4F47-A179-708950A92E6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F103E6FE-AD3D-4F47-A179-708950A92E6A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T03:16:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "323EB6A5-54C4-485A-910C-C896C850F031", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/323EB6A5-54C4-485A-910C-C896C850F031/view-source"}], "score": 10, "updated_at": "2026-09-13T03:16:34+00:00"}, {"answer_html": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:
\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = "l") ## cosmetic\nmatplot(x_all, basis_matrix, type = "l", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)\n\n", "answer_id": 677164, "answer_text": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:\n\n\n\n\n[image: plot of the basis elements of a spline, with the elements that are non-zero at x=1.5 highlighted (solid, thick lines); source: https://i.sstatic.net/7o5ja3We.png] (https://i.sstatic.net/7o5ja3We.png)\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = \"l\") ## cosmetic\nmatplot(x_all, basis_matrix, type = \"l\", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)", "answer_url": "https://stats.stackexchange.com/a/677164", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T20:32:49+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-13T20:32:49+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "EBF57CF7-0E40-482E-A05C-136F42F17A79", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EBF57CF7-0E40-482E-A05C-136F42F17A79/view-source"}], "score": 6, "updated_at": "2026-09-13T20:32:49+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/7o5ja3We.png", "https://i.sstatic.net/v4LeyMo7.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": "doraemon", "question_author_url": "https://stats.stackexchange.com/users/368723/doraemon", "question_author_user_type": "registered", "question_created_at": "2026-09-11T07:17:25+00:00", "question_html": "I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.
\nThe worked example in Ken Koon Wong's blog post "Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm", reproduced below:
\nlibrary(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n\nResult:
\n## 1 2 3 4 5 6 7 8 9 10 11\n## [1,] 0 0 0 0.02083333 0.4791667 0.4791667 0.02083333 0 0 0 0\n## attr(,"degree")\n## [1] 3\n## attr(,"knots")\n## [1] -2 -1 0 1 2 3 4 5\n## attr(,"Boundary.knots")\n## [1] -3 6\n## attr(,"intercept")\n## [1] FALSE\n## attr(,"class")\n## [1] "bs" "basis" "matrix"\n\nWong explained:
\n\n\nAwesome!!! We have very similar numbers !!! But why are there so many columns? And they’re filled with zeros, reminds me almost like padding. Apparently this is mainly to ensure no issues when x is very close to boundary knots is my understanding. And the way they add these padding depends on degrees + 1 if you use degree = 3, add 1 to it and that would be how many repeats of the numbers of your boundary knots.
\n
But why are the number of leading and trailing zeros different?
\nFrom wiki of De Boor's algorithm,
\n\n\nIt follows from i≥0 that k≥p. Similarly, we see in the recursion that the highest queried knot location is at index k+1+p. This means that any knot interval [tk,tk+1) which is actually used must have at least p additional knots before and after. In a computer program, this is typically achieved by repeating the first and last used knot location p times. For example, for p=3 and real knot locations (0,1,2), one would pad the knot vector to (0,0,0,0,1,2,2,2,2).
\n
{which is actually used must have at least p additional knots before and after}<- Then the number of leading and trailing zeros should be the same? i.e. 3+1 = 4
\nUpdate:\nAccording to the calculation by Ken Koon Wong,
\n\nThe position of knots should be c(-3,-3,-3,-3,-2, -1, 0, 1, 2,2,2,2)?\nAm I correct?
\n", "question_id": 677137, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.\n\n\n\n\nThe worked example in Ken Koon Wong's blog post \"Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm\", reproduced below:\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n\n\n\n\n\nResult:\n\n\n\n\n## 1 2 3 4 5 6 7 8 9 10 11\n## [1,] 0 0 0 0.02083333 0.4791667 0.4791667 0.02083333 0 0 0 0\n## attr(,\"degree\")\n## [1] 3\n## attr(,\"knots\")\n## [1] -2 -1 0 1 2 3 4 5\n## attr(,\"Boundary.knots\")\n## [1] -3 6\n## attr(,\"intercept\")\n## [1] FALSE\n## attr(,\"class\")\n## [1] \"bs\" \"basis\" \"matrix\"\n\n\n\n\n\nWong explained:\n\n\n\n\n\n\n\nAwesome!!! We have very similar numbers !!! But why are there so many columns? And they’re filled with zeros, reminds me almost like padding. Apparently this is mainly to ensure no issues when x is very close to boundary knots is my understanding. And the way they add these padding depends on degrees + 1 if you use degree = 3, add 1 to it and that would be how many repeats of the numbers of your boundary knots.\n\n\n\n\n\n\n\nBut why are the number of leading and trailing zeros different?\n\n\n\n\nFrom wiki of De Boor's algorithm,\n\n\n\n\n\n\n\nIt follows from i≥0 that k≥p. Similarly, we see in the recursion that the highest queried knot location is at index k+1+p. This means that any knot interval [tk,tk+1) which is actually used must have at least p additional knots before and after. In a computer program, this is typically achieved by repeating the first and last used knot location p times. For example, for p=3 and real knot locations (0,1,2), one would pad the knot vector to (0,0,0,0,1,2,2,2,2).\n\n\n\n\n\n\n\n{which is actually used must have at least p additional knots before and after}<- Then the number of leading and trailing zeros should be the same? i.e. 3+1 = 4\n\n\n\n\n\n\n\nUpdate:\nAccording to the calculation by Ken Koon Wong,\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/v4LeyMo7.png] (https://i.sstatic.net/v4LeyMo7.png)\n\n\n\n\nThe position of knots should be c(-3,-3,-3,-3,-2, -1, 0, 1, 2,2,2,2)?\nAm I correct?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "doraemon", "profile_url": "https://stats.stackexchange.com/users/368723/doraemon", "user_type": "registered"}, "created_at": "2026-09-11T07:17:25+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "44C9B612-E48F-45D8-A87E-134A15427F2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/44C9B612-E48F-45D8-A87E-134A15427F2A/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-13T06:50:29+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "7FDC6F64-699C-45D6-AD65-42C2EB6E9601", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/7FDC6F64-699C-45D6-AD65-42C2EB6E9601/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-09-15T03:24:20+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "26A7DFFA-3772-4615-A75D-4773FFF3DA34", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/26A7DFFA-3772-4615-A75D-4773FFF3DA34/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "doraemon", "profile_url": "https://stats.stackexchange.com/users/368723/doraemon", "user_type": "registered"}, "created_at": "2026-09-18T09:00:22+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "DF8093CD-0CC4-47CA-A76A-429E20D88E33", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/DF8093CD-0CC4-47CA-A76A-429E20D88E33/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677137/why-does-a-cubic-b-spline-basis-matrix-contain-so-many-zero-columns", "split": "train", "split_group": "a3b9bc15521973baeed3260891b4d75567f430c5afd7368e49e8db8c587dd1a5", "tags": ["r", "splines", "mgcv", "gamlss"], "thread_id": "stats:677137", "title": "Why does a cubic B-spline basis matrix contain so many zero columns?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "modelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677183, "sha256": "d2e0b087137c58a9d017d1f4cb6ac63b0c3aa386a664b23e5b642e53fe18932f", "source_url": "https://stats.stackexchange.com/questions/677183/ordinal-mixed-effect-model-with-3-factors-and-interactions-beginner-help"}], "other_answers": [], "product": "code_qa", "question": "I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the results I got, nor how to visualize it in a easy, straighforward manner.\nHere is the model I'm using in R:\n\n\n\n\nmodelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n\n\n\n\n\nRating_Resp is 5 levels; WordCat, Session and Group are all categorical with 2 levels, with Session being within group factor. Participant and word/item are random intercepts.\nI then used summary(modelOrdinalWordCat) to look at the model in a more \"ANOVA\" like manner, and got this print out.\n\n\n\n\n Estimate Std. Error z value Pr(>|z|) \nWordCat[S.NonWord] -0.38012 0.04136 -9.190 < 2e-16 ***\nGroupL2 Exposure -0.17397 0.08151 -2.134 0.03282 *\nSession2 -0.05367 0.03627 -1.480 0.13896 \nWordCat[S.NonWord]:GroupL2 Exposure 0.04777 0.03412 1.400 0.16141 \nWordCat[S.NonWord]:Session2 0.05404 0.03623 1.492 0.13579 \nGroupL2 Exposure:Session2 0.13310 0.04820 2.761 0.00576 ** \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 -0.10393 0.04815 -2.159 0.03089 * \n\n\n\n\n\nUsing just the default print out, I get this:\n\n\n\n\nWordCat[S.NonWord] GroupL2 Exposure \n-0.38012 -0.17397 \nSession2 WordCat[S.NonWord]:GroupL2 Exposure \n-0.05367 0.04777 \nWordCat[S.NonWord]:Session2 GroupL2 Exposure:Session2 \n0.05404 0.13310 \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 \n-0.10393 \n\n\n\n\n\nI can't make heads of tails of this table.\nHow do I report the results of this? Is it just : Word Type x Session x Group: estimate = -0.10, SE = 0.048, z value = -2.16, p = .031\nThanks in advance!\n(If I am completely wrong, let me have it!)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677183", "selected_answer": {"answer_html": "Ordinal models pose (at least) two difficulties in interpretation beyond standard linear models.
\nFirst, the coefficients are in log-odds scales, which can be hard to think about even in logistic regression. A log-odds coefficient in ordinal regression is for the change of one outcome level per change in a predictor or interaction.
\nYou should show the model summary, but visualization of model predictions and their confidence intervals or standard errors is more useful for your audience (and probably for yourself). As you used the standard R treatment coding of the factors, each coefficient thus represents the difference in log-odds associated with a predictor or interaction term, beyond what would be predicted from lower-level intercepts or single-predictor coefficients or interactions.
\nSecond, instead of having a single intercept as in logistic regression, there is a separate intercept for each transition between outcome levels. To get model predictions, it's simplest to use post-modeling tools like those in the emmeans package recommended by @Sointu in a comment.
Your 3-way interaction is thus the difference in log-odds for changing one outcome level between the situation with none of the 3 factors at reference levels and the situation with only 1 of them at the reference level. The coefficient of -0.10393 in log-odds scale represents odds of about 0.9. Whether its statistical significance is important in practice depends on your understanding of the subject matter.
This site has several entries that provide more detail and links, including Interpretation of ordinal logistic regression and How to understand output from R's polr function (ordered logistic regression)?. UCLA Advanced Research Computing has pages on Ordinal Logistic Regression | R Data Analysis Examples and How Do I Interpret the Coefficients in an Ordinal Logistic Regression in R?. Frank Harrell provides extensive Resources for Ordinal Regression Models, recommending their widespread use even with data that would often be considered continuous.
\nOne additional warning: there are two different ways to set up the ordinal regression. Read the documentation to know which is being used. One models the probability of having an outcome less than or equal to a specified outcome level. That seems to be used in most R implementations. The other, used in Frank Harrell's rms package, models the probability of having an outcome greater than or equal to a specified outcome level. You'll find differences in signs of intercepts depending on which is used. The emmeans package can work with either to get model predictions.
Ordinal models pose (at least) two difficulties in interpretation beyond standard linear models.
\nFirst, the coefficients are in log-odds scales, which can be hard to think about even in logistic regression. A log-odds coefficient in ordinal regression is for the change of one outcome level per change in a predictor or interaction.
\nYou should show the model summary, but visualization of model predictions and their confidence intervals or standard errors is more useful for your audience (and probably for yourself). As you used the standard R treatment coding of the factors, each coefficient thus represents the difference in log-odds associated with a predictor or interaction term, beyond what would be predicted from lower-level intercepts or single-predictor coefficients or interactions.
\nSecond, instead of having a single intercept as in logistic regression, there is a separate intercept for each transition between outcome levels. To get model predictions, it's simplest to use post-modeling tools like those in the emmeans package recommended by @Sointu in a comment.
Your 3-way interaction is thus the difference in log-odds for changing one outcome level between the situation with none of the 3 factors at reference levels and the situation with only 1 of them at the reference level. The coefficient of -0.10393 in log-odds scale represents odds of about 0.9. Whether its statistical significance is important in practice depends on your understanding of the subject matter.
This site has several entries that provide more detail and links, including Interpretation of ordinal logistic regression and How to understand output from R's polr function (ordered logistic regression)?. UCLA Advanced Research Computing has pages on Ordinal Logistic Regression | R Data Analysis Examples and How Do I Interpret the Coefficients in an Ordinal Logistic Regression in R?. Frank Harrell provides extensive Resources for Ordinal Regression Models, recommending their widespread use even with data that would often be considered continuous.
\nOne additional warning: there are two different ways to set up the ordinal regression. Read the documentation to know which is being used. One models the probability of having an outcome less than or equal to a specified outcome level. That seems to be used in most R implementations. The other, used in Frank Harrell's rms package, models the probability of having an outcome greater than or equal to a specified outcome level. You'll find differences in signs of intercepts depending on which is used. The emmeans package can work with either to get model predictions.
I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the results I got, nor how to visualize it in a easy, straighforward manner.\nHere is the model I'm using in R:
\nmodelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = "logit")\n\nRating_Resp is 5 levels; WordCat, Session and Group are all categorical with 2 levels, with Session being within group factor. Participant and word/item are random intercepts.\nI then used summary(modelOrdinalWordCat) to look at the model in a more "ANOVA" like manner, and got this print out.
\n Estimate Std. Error z value Pr(>|z|) \nWordCat[S.NonWord] -0.38012 0.04136 -9.190 < 2e-16 ***\nGroupL2 Exposure -0.17397 0.08151 -2.134 0.03282 *\nSession2 -0.05367 0.03627 -1.480 0.13896 \nWordCat[S.NonWord]:GroupL2 Exposure 0.04777 0.03412 1.400 0.16141 \nWordCat[S.NonWord]:Session2 0.05404 0.03623 1.492 0.13579 \nGroupL2 Exposure:Session2 0.13310 0.04820 2.761 0.00576 ** \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 -0.10393 0.04815 -2.159 0.03089 * \n\nUsing just the default print out, I get this:
\nWordCat[S.NonWord] GroupL2 Exposure \n-0.38012 -0.17397 \nSession2 WordCat[S.NonWord]:GroupL2 Exposure \n-0.05367 0.04777 \nWordCat[S.NonWord]:Session2 GroupL2 Exposure:Session2 \n0.05404 0.13310 \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 \n-0.10393 \n\nI can't make heads of tails of this table.\nHow do I report the results of this? Is it just : Word Type x Session x Group: estimate = -0.10, SE = 0.048, z value = -2.16, p = .031\nThanks in advance!\n(If I am completely wrong, let me have it!)
\n", "question_id": 677183, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the results I got, nor how to visualize it in a easy, straighforward manner.\nHere is the model I'm using in R:\n\n\n\n\nmodelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n\n\n\n\n\nRating_Resp is 5 levels; WordCat, Session and Group are all categorical with 2 levels, with Session being within group factor. Participant and word/item are random intercepts.\nI then used summary(modelOrdinalWordCat) to look at the model in a more \"ANOVA\" like manner, and got this print out.\n\n\n\n\n Estimate Std. Error z value Pr(>|z|) \nWordCat[S.NonWord] -0.38012 0.04136 -9.190 < 2e-16 ***\nGroupL2 Exposure -0.17397 0.08151 -2.134 0.03282 *\nSession2 -0.05367 0.03627 -1.480 0.13896 \nWordCat[S.NonWord]:GroupL2 Exposure 0.04777 0.03412 1.400 0.16141 \nWordCat[S.NonWord]:Session2 0.05404 0.03623 1.492 0.13579 \nGroupL2 Exposure:Session2 0.13310 0.04820 2.761 0.00576 ** \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 -0.10393 0.04815 -2.159 0.03089 * \n\n\n\n\n\nUsing just the default print out, I get this:\n\n\n\n\nWordCat[S.NonWord] GroupL2 Exposure \n-0.38012 -0.17397 \nSession2 WordCat[S.NonWord]:GroupL2 Exposure \n-0.05367 0.04777 \nWordCat[S.NonWord]:Session2 GroupL2 Exposure:Session2 \n0.05404 0.13310 \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 \n-0.10393 \n\n\n\n\n\nI can't make heads of tails of this table.\nHow do I report the results of this? Is it just : Word Type x Session x Group: estimate = -0.10, SE = 0.048, z value = -2.16, p = .031\nThanks in advance!\n(If I am completely wrong, let me have it!)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rae", "profile_url": "https://stats.stackexchange.com/users/516706/rae", "user_type": "registered"}, "created_at": "2026-09-15T18:48:16+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "54C1911F-DE57-4D25-88F0-822250BA5283", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/54C1911F-DE57-4D25-88F0-822250BA5283/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677183/ordinal-mixed-effect-model-with-3-factors-and-interactions-beginner-help", "split": "train", "split_group": "4e9596eab227a4c8203ea12055e6a18f2307cdda74a5c355bfd04e5dbaa03ae6", "tags": ["ordinal-data", "ordered-logit", "ordinal-logistic-regression"], "thread_id": "stats:677183", "title": "Ordinal Mixed Effect Model with 3 factors and Interactions - Beginner Help"}} {"accepted_answer": {"answer_html": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.
\nHere's a plot in R:
\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\n\n\n", "answer_id": 677231, "answer_text": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution (https://en.wikipedia.org/wiki/Beta-binomial_distribution)). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.\n\n\n\n\nHere's a plot in R:\n\n\n\n\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n\n\n\n\n\n[image: plot k = 10 from R-Code, one extrem being just 0.4 at 0 and 0.6 at 10, the other fits the binomial; source: https://i.sstatic.net/cWGh2esg.png] (https://i.sstatic.net/cWGh2esg.png)\n[image: plot k = 1 from R-Code, just the same line from 0.4 to 0.6; source: https://i.sstatic.net/BHmL9Quz.png] (https://i.sstatic.net/BHmL9Quz.png)", "answer_url": "https://stats.stackexchange.com/a/677231", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-21T21:48:52+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-21T21:48:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "315A6811-DCF0-437C-A1D7-8721F8646961", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/315A6811-DCF0-437C-A1D7-8721F8646961/view-source"}], "score": 2, "updated_at": "2026-09-21T21:48:52+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "set.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677226, "sha256": "f6cd15195d5d74c89d7431b12ba7c0aac4d3e4e33b3ff40949960b1f791bcb23", "source_url": "https://stats.stackexchange.com/questions/677226/is-variance-still-estimable-when-you-observe-a-single-observation-per-subject"}, {"block_index": 0, "code_text": "library(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677231, "sha256": "f4d4b00c54ed85f483126ced360cf9820be997c762fbd027eda1b32c6af6f67e", "source_url": "https://stats.stackexchange.com/a/677231"}], "other_answers": [{"answer_html": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.
\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.
\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:
\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$
\nTo marginalize the distribution:
\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$
\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$
\nThe iid assumption makes it easy to extend this to $n$ machines:
\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$
\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$
\nNext, we can see $\\bar y$ is unbiased:
\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$
\nNow for the variance:
\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$
\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$
\nFor variance of the mean (0 covariance):
\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$
\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.
\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$
\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$
\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$
\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$
\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.
\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.
\n", "answer_id": 677265, "answer_text": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.\n\n\n\n\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.\n\n\n\n\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:\n\n\n\n\n\n$\\mu = E[\\theta_i]$ — population mean (the target) and is $\\mu = \\frac{\\alpha}{\\alpha+\\beta}$\n\n\n\n\n\n\n$\\tau^2 = \\operatorname{Var}(\\theta_i)$ — population variance and is = $\\tau^2 = \\frac{\\mu(1-\\mu)}{\\alpha+\\beta+1}$\n\n\n\n\n\n\n$\\sigma_y^2 = \\operatorname{Var}(y_i)$\n\n\n\n\n\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$\n\n\n\n\nTo marginalize the distribution:\n\n\n\n\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$\n\n\n\n\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$\n\n\n\n\nThe iid assumption makes it easy to extend this to $n$ machines:\n\n\n\n\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$\n\n\n\n\nNext, we can see $\\bar y$ is unbiased:\n\n\n\n\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$\n\n\n\n\nNow for the variance:\n\n\n\n\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$\n\n\n\n\nFor variance of the mean (0 covariance):\n\n\n\n\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$\n\n\n\n\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.\n\n\n\n\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$\n\n\n\n\n\n$\\bar y = \\frac1n\\sum_i y_i$ means $\\sum_i y_i = n\\bar y$.\n\n\n\n\nA constant $\\mu$ summed $n$ times is $n\\mu$.\n\n\n\n\n\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$\n\n\n\n\n\n$y_i - \\bar y = (y_i-\\mu) - (\\bar y-\\mu)$:\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 \\;-\\; 2(\\bar y-\\mu)\\underbrace{\\sum_i (y_i-\\mu)}_{=\\,n(\\bar y-\\mu)} \\;+\\; n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$E[(y_i-\\mu)^2] = \\sigma_y^2$\n\n\n\n\n$E[(\\bar y-\\mu)^2] = \\text{Var}(\\bar y) = \\sigma_y^2/n$\n\n\n\n\n\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$\n\n\n\n\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.\n\n\n\n\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.", "answer_url": "https://stats.stackexchange.com/a/677265", "author": "adamkostanov", "author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T17:44:30+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677226, "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-25T17:44:30+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "A2509D36-CE80-4C0F-BA28-5077E22D040B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A2509D36-CE80-4C0F-BA28-5077E22D040B/view-source"}], "score": 0, "updated_at": "2026-09-25T17:44:30+00:00"}], "product": "code_qa", "question": "Here is a hierarchical data generating process:\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\nThere are two cases - Case 1 is where you sample 1 observation per subject and Case 2 where you sample multiple observations per subject:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/wine4qeY.png] (https://i.sstatic.net/wine4qeY.png)\n\n\n\n\nI am only interested in estimating the population level mean and variance. Can this still be done in Case 1?\n\n\n\n\nI am guessing that there will be no problems doing this for Case 2. For Case 1, I am guessing there won't be any problems for estimating the population level mean, but I am not sure if the population level variance can still be estimated since we do not observe variation at the individual level (regardless of whether moments are used or MLE).\n\n\n\n\n\n\n\nset.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677226", "selected_answer": {"answer_html": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.
\nHere's a plot in R:
\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\n\n\n", "answer_id": 677231, "answer_text": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution (https://en.wikipedia.org/wiki/Beta-binomial_distribution)). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.\n\n\n\n\nHere's a plot in R:\n\n\n\n\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n\n\n\n\n\n[image: plot k = 10 from R-Code, one extrem being just 0.4 at 0 and 0.6 at 10, the other fits the binomial; source: https://i.sstatic.net/cWGh2esg.png] (https://i.sstatic.net/cWGh2esg.png)\n[image: plot k = 1 from R-Code, just the same line from 0.4 to 0.6; source: https://i.sstatic.net/BHmL9Quz.png] (https://i.sstatic.net/BHmL9Quz.png)", "answer_url": "https://stats.stackexchange.com/a/677231", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-21T21:48:52+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-21T21:48:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "315A6811-DCF0-437C-A1D7-8721F8646961", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/315A6811-DCF0-437C-A1D7-8721F8646961/view-source"}], "score": 2, "updated_at": "2026-09-21T21:48:52+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677231, "answers": [{"answer_html": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.
\nHere's a plot in R:
\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\n\n\n", "answer_id": 677231, "answer_text": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution (https://en.wikipedia.org/wiki/Beta-binomial_distribution)). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.\n\n\n\n\nHere's a plot in R:\n\n\n\n\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n\n\n\n\n\n[image: plot k = 10 from R-Code, one extrem being just 0.4 at 0 and 0.6 at 10, the other fits the binomial; source: https://i.sstatic.net/cWGh2esg.png] (https://i.sstatic.net/cWGh2esg.png)\n[image: plot k = 1 from R-Code, just the same line from 0.4 to 0.6; source: https://i.sstatic.net/BHmL9Quz.png] (https://i.sstatic.net/BHmL9Quz.png)", "answer_url": "https://stats.stackexchange.com/a/677231", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-21T21:48:52+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-21T21:48:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "315A6811-DCF0-437C-A1D7-8721F8646961", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/315A6811-DCF0-437C-A1D7-8721F8646961/view-source"}], "score": 2, "updated_at": "2026-09-21T21:48:52+00:00"}, {"answer_html": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.
\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.
\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:
\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$
\nTo marginalize the distribution:
\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$
\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$
\nThe iid assumption makes it easy to extend this to $n$ machines:
\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$
\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$
\nNext, we can see $\\bar y$ is unbiased:
\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$
\nNow for the variance:
\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$
\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$
\nFor variance of the mean (0 covariance):
\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$
\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.
\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$
\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$
\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$
\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$
\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.
\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.
\n", "answer_id": 677265, "answer_text": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.\n\n\n\n\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.\n\n\n\n\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:\n\n\n\n\n\n$\\mu = E[\\theta_i]$ — population mean (the target) and is $\\mu = \\frac{\\alpha}{\\alpha+\\beta}$\n\n\n\n\n\n\n$\\tau^2 = \\operatorname{Var}(\\theta_i)$ — population variance and is = $\\tau^2 = \\frac{\\mu(1-\\mu)}{\\alpha+\\beta+1}$\n\n\n\n\n\n\n$\\sigma_y^2 = \\operatorname{Var}(y_i)$\n\n\n\n\n\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$\n\n\n\n\nTo marginalize the distribution:\n\n\n\n\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$\n\n\n\n\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$\n\n\n\n\nThe iid assumption makes it easy to extend this to $n$ machines:\n\n\n\n\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$\n\n\n\n\nNext, we can see $\\bar y$ is unbiased:\n\n\n\n\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$\n\n\n\n\nNow for the variance:\n\n\n\n\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$\n\n\n\n\nFor variance of the mean (0 covariance):\n\n\n\n\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$\n\n\n\n\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.\n\n\n\n\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$\n\n\n\n\n\n$\\bar y = \\frac1n\\sum_i y_i$ means $\\sum_i y_i = n\\bar y$.\n\n\n\n\nA constant $\\mu$ summed $n$ times is $n\\mu$.\n\n\n\n\n\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$\n\n\n\n\n\n$y_i - \\bar y = (y_i-\\mu) - (\\bar y-\\mu)$:\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 \\;-\\; 2(\\bar y-\\mu)\\underbrace{\\sum_i (y_i-\\mu)}_{=\\,n(\\bar y-\\mu)} \\;+\\; n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$E[(y_i-\\mu)^2] = \\sigma_y^2$\n\n\n\n\n$E[(\\bar y-\\mu)^2] = \\text{Var}(\\bar y) = \\sigma_y^2/n$\n\n\n\n\n\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$\n\n\n\n\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.\n\n\n\n\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.", "answer_url": "https://stats.stackexchange.com/a/677265", "author": "adamkostanov", "author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T17:44:30+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677226, "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-25T17:44:30+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "A2509D36-CE80-4C0F-BA28-5077E22D040B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A2509D36-CE80-4C0F-BA28-5077E22D040B/view-source"}], "score": 0, "updated_at": "2026-09-25T17:44:30+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Beta-binomial_distribution", "https://i.sstatic.net/BHmL9Quz.png", "https://i.sstatic.net/cWGh2esg.png", "https://i.sstatic.net/wine4qeY.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-21T00:41:19+00:00", "question_html": "Here is a hierarchical data generating process:
\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$
\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$
\n
There are two cases - Case 1 is where you sample 1 observation per subject and Case 2 where you sample multiple observations per subject:
\n\nI am only interested in estimating the population level mean and variance. Can this still be done in Case 1?
\nI am guessing that there will be no problems doing this for Case 2. For Case 1, I am guessing there won't be any problems for estimating the population level mean, but I am not sure if the population level variance can still be estimated since we do not observe variation at the individual level (regardless of whether moments are used or MLE).
\nset.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste("Subject", 1:n), levels = paste("Subject", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)\n\n", "question_id": 677226, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "Here is a hierarchical data generating process:\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\nThere are two cases - Case 1 is where you sample 1 observation per subject and Case 2 where you sample multiple observations per subject:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/wine4qeY.png] (https://i.sstatic.net/wine4qeY.png)\n\n\n\n\nI am only interested in estimating the population level mean and variance. Can this still be done in Case 1?\n\n\n\n\nI am guessing that there will be no problems doing this for Case 2. For Case 1, I am guessing there won't be any problems for estimating the population level mean, but I am not sure if the population level variance can still be estimated since we do not observe variation at the individual level (regardless of whether moments are used or MLE).\n\n\n\n\n\n\n\nset.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)", "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-21T00:41:19+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C1F4E2FF-471E-47A5-928D-F6B0A4681FF3", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C1F4E2FF-471E-47A5-928D-F6B0A4681FF3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-09-21T04:23:57+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "19D572A4-437C-42C9-8FEE-FD0F08D0BE8B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/19D572A4-437C-42C9-8FEE-FD0F08D0BE8B/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-21T04:41:49+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD8437EA-1725-4DAB-8174-F56009F767F0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD8437EA-1725-4DAB-8174-F56009F767F0/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-22T01:12:54+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "75227B37-0244-4E58-846B-06B8FB1C54FF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/75227B37-0244-4E58-846B-06B8FB1C54FF/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677226/is-variance-still-estimable-when-you-observe-a-single-observation-per-subject", "split": "train", "split_group": "9dd25a7f286d352daa4453c364e35088a292dc3acf798487781b158dd5e6996b", "tags": ["probability", "sampling", "estimation", "mean"], "thread_id": "stats:677226", "title": "Is variance still estimable when you observe a single observation per subject?"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "dat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677242, "sha256": "578bb120659315b5f683555f2dd22808cb76a10c82324e2ddfd65df2d0aeea9e", "source_url": "https://stats.stackexchange.com/questions/677242/modeling-within-day-and-across-day-correlations-using-car1-with-repeated-measu"}, {"block_index": 1, "code_text": "model <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677242, "sha256": "2f3492ec43226c6b22fc018d5bd673083aa32387dc5110cb28418f8f9cd7695f", "source_url": "https://stats.stackexchange.com/questions/677242/modeling-within-day-and-across-day-correlations-using-car1-with-repeated-measu"}], "other_answers": [], "product": "code_qa", "question": "I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).\n\n\n\n\nThe data collection protocol is as follows:\n\n\n\n\n• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.\n\n\n\n\n• At each time point, BP is measured twice, exactly 1 minute apart.\n\n\n\n\nData structure\n\n\n\n\n\n\n\n\n\nday\ntime\nrep\ndatetime\nSBP\n\n\n\n\n\n\n\n\n\t1\n\t12:00\n\t1\n\t2026-01-01 12:00\n\t122\n\n\n\n\n\n\n\t1\n\t12:00\n\t2\n\t2026-01-01 12:01\n\t121\n\n\n\n\n\n\n\t1\n\t20:00\n\t1\n\t2026-01-01 20:00\n\t128\n\n\n\n\n\n\n\t1\n\t20:00\n\t2\n\t2026-01-01 20:01\n\t127\n\n\n\n\n\n\n\t2\n\t12:00\n\t1\n\t2026-01-02 12:00\n\t120\n\n\n\n\n\n\n\t2\n\t12:00\n\t2\n\t2026-01-02 12:01\n\t119\n\n\n\n\n\n\n\t2\n\t20:00\n\t1\n\t2026-01-02 20:00\n\t130\n\n\n\n\n\n\n\t2\n\t20:00\n\t2\n\t2026-01-02 20:01\n\t129\n\n\n\n\n\n\n\n\n\nI then calculate elapsed time from the first observation:\n\n\n\n\ndat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n\n\n\n\n\ngives approximately:\n0, 0.00069, 0.3333, 0.3340,\n1, 1.00069, 1.3333, 1.3340, ...\ni.e., the actual elapsed time between observations, expressed in days.\n\n\n\n\nI was considering the following model:\n\n\n\n\nmodel <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n\n\n\n\n\nQuestions\n\n\n\n\n\nIs calculating t_elapsed an appropriate way to specify the time variable for corCAR1()?\n\n\n\n\nMore generally, is CAR(1) an appropriate correlation structure for these data, given that I have both very closely spaced repeated measurements (1 minute apart) and measurements separated by approximately 8 or 16 hours?\n\n\n\n\nWould you recommend an alternative correlation structure or modeling strategy for this design?\n\n\n\n\n\nThank you!", "record_id": "Scientific-Code-and-Analysis-QA:stats:677242", "selected_answer": {"answer_html": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.
If day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.
The model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.
I don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.
I suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.
\nChapter 7 of Frank Harrell's Regression Modeling Strategies covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.
\n", "answer_id": 677249, "answer_text": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.\n\n\n\n\nIf day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.\n\n\n\n\nThe model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.\n\n\n\n\nI don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.\n\n\n\n\nI suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.\n\n\n\n\nChapter 7 of Frank Harrell's Regression Modeling Strategies (https://hbiostat.org/rmsc/long) covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.", "answer_url": "https://stats.stackexchange.com/a/677249", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-23T20:10:25+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677242, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-23T20:10:25+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "49CEC78F-CB41-47B6-A537-4E122B99B13A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49CEC78F-CB41-47B6-A537-4E122B99B13A/view-source"}], "score": 3, "updated_at": "2026-09-23T20:10:25+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.
If day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.
The model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.
I don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.
I suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.
\nChapter 7 of Frank Harrell's Regression Modeling Strategies covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.
\n", "answer_id": 677249, "answer_text": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.\n\n\n\n\nIf day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.\n\n\n\n\nThe model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.\n\n\n\n\nI don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.\n\n\n\n\nI suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.\n\n\n\n\nChapter 7 of Frank Harrell's Regression Modeling Strategies (https://hbiostat.org/rmsc/long) covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.", "answer_url": "https://stats.stackexchange.com/a/677249", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-23T20:10:25+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677242, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-23T20:10:25+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "49CEC78F-CB41-47B6-A537-4E122B99B13A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49CEC78F-CB41-47B6-A537-4E122B99B13A/view-source"}], "score": 3, "updated_at": "2026-09-23T20:10:25+00:00"}], "domain": "statistics", "external_links": ["https://hbiostat.org/rmsc/long"], "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": "jtjtjtjt", "question_author_url": "https://stats.stackexchange.com/users/393112/jtjtjtjt", "question_author_user_type": "registered", "question_created_at": "2026-09-23T09:07:44+00:00", "question_html": "I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).
\nThe data collection protocol is as follows:
\n• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.
\n• At each time point, BP is measured twice, exactly 1 minute apart.
\nData structure
\n| day | \ntime | \nrep | \ndatetime | \nSBP | \n
|---|---|---|---|---|
| 1 | \n12:00 | \n1 | \n2026-01-01 12:00 | \n122 | \n
| 1 | \n12:00 | \n2 | \n2026-01-01 12:01 | \n121 | \n
| 1 | \n20:00 | \n1 | \n2026-01-01 20:00 | \n128 | \n
| 1 | \n20:00 | \n2 | \n2026-01-01 20:01 | \n127 | \n
| 2 | \n12:00 | \n1 | \n2026-01-02 12:00 | \n120 | \n
| 2 | \n12:00 | \n2 | \n2026-01-02 12:01 | \n119 | \n
| 2 | \n20:00 | \n1 | \n2026-01-02 20:00 | \n130 | \n
| 2 | \n20:00 | \n2 | \n2026-01-02 20:01 | \n129 | \n
I then calculate elapsed time from the first observation:
\ndat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = "days")\n)\nThis\n\ngives approximately:\n0, 0.00069, 0.3333, 0.3340,\n1, 1.00069, 1.3333, 1.3340, ...\ni.e., the actual elapsed time between observations, expressed in days.
\nI was considering the following model:
\nmodel <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n\nQuestions
\nThank you!
\n", "question_id": 677242, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).\n\n\n\n\nThe data collection protocol is as follows:\n\n\n\n\n• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.\n\n\n\n\n• At each time point, BP is measured twice, exactly 1 minute apart.\n\n\n\n\nData structure\n\n\n\n\n\n\n\n\n\nday\ntime\nrep\ndatetime\nSBP\n\n\n\n\n\n\n\n\n\t1\n\t12:00\n\t1\n\t2026-01-01 12:00\n\t122\n\n\n\n\n\n\n\t1\n\t12:00\n\t2\n\t2026-01-01 12:01\n\t121\n\n\n\n\n\n\n\t1\n\t20:00\n\t1\n\t2026-01-01 20:00\n\t128\n\n\n\n\n\n\n\t1\n\t20:00\n\t2\n\t2026-01-01 20:01\n\t127\n\n\n\n\n\n\n\t2\n\t12:00\n\t1\n\t2026-01-02 12:00\n\t120\n\n\n\n\n\n\n\t2\n\t12:00\n\t2\n\t2026-01-02 12:01\n\t119\n\n\n\n\n\n\n\t2\n\t20:00\n\t1\n\t2026-01-02 20:00\n\t130\n\n\n\n\n\n\n\t2\n\t20:00\n\t2\n\t2026-01-02 20:01\n\t129\n\n\n\n\n\n\n\n\n\nI then calculate elapsed time from the first observation:\n\n\n\n\ndat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n\n\n\n\n\ngives approximately:\n0, 0.00069, 0.3333, 0.3340,\n1, 1.00069, 1.3333, 1.3340, ...\ni.e., the actual elapsed time between observations, expressed in days.\n\n\n\n\nI was considering the following model:\n\n\n\n\nmodel <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n\n\n\n\n\nQuestions\n\n\n\n\n\nIs calculating t_elapsed an appropriate way to specify the time variable for corCAR1()?\n\n\n\n\nMore generally, is CAR(1) an appropriate correlation structure for these data, given that I have both very closely spaced repeated measurements (1 minute apart) and measurements separated by approximately 8 or 16 hours?\n\n\n\n\nWould you recommend an alternative correlation structure or modeling strategy for this design?\n\n\n\n\n\nThank you!", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jtjtjtjt", "profile_url": "https://stats.stackexchange.com/users/393112/jtjtjtjt", "user_type": "registered"}, "created_at": "2026-09-23T09:07:44+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "F6683031-BCCB-4D54-BBE3-456E3642AC0F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F6683031-BCCB-4D54-BBE3-456E3642AC0F/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-24T01:29:33+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "4E6C2681-2FA3-4F04-87F3-25F3A9004AFC", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/4E6C2681-2FA3-4F04-87F3-25F3A9004AFC/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677242/modeling-within-day-and-across-day-correlations-using-car1-with-repeated-measu", "split": "train", "split_group": "f33a429b362ffdcdd327a936bb1a7b486e9a3a3e1d3c84d34deb198a0b0393f5", "tags": ["lme4-nlme", "autoregressive", "generalized-least-squares"], "thread_id": "stats:677242", "title": "Modeling within-day and across-day correlations using CAR(1) with repeated measurements"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "ratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = \"REML\",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = \"r\"),\n pearson = residuals(model, type = \"p\"),\n norm_res_R = residuals(model, type = \"n\"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "d16b7b9cab3fd8d94d48e1eab2bd8bc38880d968e38079852a04a215d3fdf1f5", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 1, "code_text": "#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- \"Normalized residuals\"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[[\"Xy\"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[[\"Xy\"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, \"maxCov\")),\n logLik = double(1))[c(\"Xy\", \"logLik\")]\n conLin[[\"Xy\"]][] <- val[[\"Xy\"]]\n conLin[[\"logLik\"]] <- conLin[[\"logLik\"]] + val[[\"logLik\"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "1176928f21235d5581ed36d45020fcbdc07f6bf1c471d16d1c4e04a0f4b28e3b", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 2, "code_text": "# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "9a21afd8ff3f46329eca76d130ff8d31f81d0bf73f64afa0c0ad11aaefecf166", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 3, "code_text": "plot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals stata\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals R\")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals stata (reverse Cholesky)\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals R (standard Cholesky)\")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "ffcbbb7f5fc811690de3c48395eef18d329c348bdd513fae9603d1b7608a1d66", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 4, "code_text": ". \n. \n. import delim \"ratlong.csv\", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "0f6814892fd518ccfd66b2d3fd3de7c87972a02e8f1df59501a03bf1183f280b", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 5, "code_text": "rat <- RatWeight\nnames(rat) <- c(\"Group\", \"Weight0\", \"Weight1\", \"Weight2\", \"Weight3\", \"Weight4\")\nrat$Group <- factor(rat$Group, levels = c(\"Control\", \"Thyroxin\", \"Thiouracil\"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != \"Thyroxin\")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c(\"W\", \"time\"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, \"ratlong.csv\", row.names = FALSE)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "9dddb99f3d3715c6346e0e01f423d9f82af2ef2dd8581704ce4880f0b9c95c48", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 6, "code_text": "library(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "97a4d9fb1290b82e7755049d7380fb4023cc7c2389da957bef743e9596f48059", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 0, "code_text": "library(gridExtra)\nlibrary(nlme)\nlibrary(\"mvtnorm\")\nlibrary(\"ggplot2\")\nlibrary(\"dplyr\")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that \"method 1\" is standard Cholesky, \"method 2\" is reverse Cholesky and \"method 3\" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (true Sigma)\")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (true Sigma)\")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (Sigma-hat)\")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (true Sigma)\")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (true Sigma)\")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (Sigma-hat)\")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (Sigma-hat)\")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (true Sigma)\")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (true Sigma)\")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (Sigma-hat)\")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (true Sigma)\")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (true Sigma)\")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (Sigma-hat)\")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (Sigma-hat)\")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677304, "sha256": "ff271d0ac3f1e3f33771e65ded38aff998c5350246f083984483c766cf60b19d", "source_url": "https://stats.stackexchange.com/a/677304"}], "other_answers": [], "product": "code_qa", "question": "I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).\n\n\n\n\nWhat I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals\n\n\n\n\nThis is based on the works of José C. Pinheiro and Douglas M. Bates. The nlme package in R references their book \"Mixed effects models in S and S-PLUS\" (2000), while Stata references their article \"Computational Methods for Multilevel Modelling\" (1998) (see page 575 of \"STATA MULTILEVEL MIXED-EFFECTS REFERENCE MANUAL RELEASE 19 (https://www.stata.com/manuals/me.pdf). The terminology is a bit confusing, as 'normalized' residuals in R are called 'standardized' residuals in stata, which is not to be confused with 'Pearson' residuals, which is what R considers 'standardized').\n\n\n\n\nHowever, the way the matrix square root is computed is different between the two programs. The result can have a rather significant impact on whether or not the normalized residuals actually seem to follow a normal distribution.\n\n\n\n\nThe way R computes the matrix square root is through the Cholesky decomposition A = L*L^T (using the chol function from FORTRAN77). I cannot access the source code for Stata, but it seems like Stata uses Cholesky decomposition as well, however using a Cholesky decomposition algorithm starting at \"the bottom right\" of the matrix instead of \"the top left\" such that A = L^T * L. Using these two methods for Cholesky decomposition, I have been able to recreate the normalised residuals from R and Stata respectively.\n\n\n\n\nWhen using QQ-plots on the normalized residuals calculated with R and those calculated with Stata, the two results plots imply different conclusions about the normality of the residuals.\n\n\n\n\nIn principle, could one not use several different methods for Cholesky decomposition to compute a matrix square root and therefore come to significantly different conclusions? Would it therefore not be preferable to use eigenvalue decomposition to compute a matrix square root as opposed to Cholesky decomposition? One reason I believe EVD would be better is that it does not require transposing one \"square root\", i.e. we have directly that A^(1/2) * A^(1/2) = A.\n\n\n\n\nHere, I have added an example:\n\n\n\n\nratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = \"REML\",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = \"r\"),\n pearson = residuals(model, type = \"p\"),\n norm_res_R = residuals(model, type = \"n\"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n\n\n\n\n\nAccording to the nmle package (retrieved from github (https://github.com/cran/nlme)), the residuals are computed as such:\n\n\n\n\n#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- \"Normalized residuals\"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[[\"Xy\"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[[\"Xy\"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, \"maxCov\")),\n logLik = double(1))[c(\"Xy\", \"logLik\")]\n conLin[[\"Xy\"]][] <- val[[\"Xy\"]]\n conLin[[\"logLik\"]] <- conLin[[\"logLik\"]] + val[[\"logLik\"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n\n\n\n\n\nI then manually computed the normalized residuals in R, through a regular Cholesky decomposition (same as t(chol) in R), through a \"reverse\" Cholesky decomposition and through EVD.\n\n\n\n\n# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n\n\n\n\n\nThe results on the rat-example imply a left or a right-skew (Stata and R respecitvely) when compared to the standard normal, i.e. they may lead to different conlclusions about the model fit (I have an example, wherein the difference is more pronounced, but I do not want to break GDPR rules. Maybe someone can find a better example?). Using EVD, there does not seem to be as much of a skew to one side or the other.\n\n\n\n\n[image: QQ-plot of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/65PG6zuB.png] (https://i.sstatic.net/65PG6zuB.png)\n\n\n\n\n[image: Histogram of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/XWUljnac.png] (https://i.sstatic.net/XWUljnac.png)\n\n\n\n\nThe figures are created via:\n\n\n\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals stata\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals R\")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals stata (reverse Cholesky)\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals R (standard Cholesky)\")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\n\n\n\n\nThe log from the Stata-code is given here:\n\n\n\n\n. \n. \n. import delim \"ratlong.csv\", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n\n\n\n\n\nI found out the data example I was working with was RatWeight from package heplots, although I was given simply given the \"ratlong.csv\"-file, which is a heavily manipulated and reordered version of RatWeight, so if you want to reproduce it, here is how (I hope you will bear with me):\n\n\n\n\nrat <- RatWeight\nnames(rat) <- c(\"Group\", \"Weight0\", \"Weight1\", \"Weight2\", \"Weight3\", \"Weight4\")\nrat$Group <- factor(rat$Group, levels = c(\"Control\", \"Thyroxin\", \"Thiouracil\"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != \"Thyroxin\")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c(\"W\", \"time\"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, \"ratlong.csv\", row.names = FALSE)\n\n\n\n\n\nPackages used in general:\n\n\n\n\nlibrary(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677243", "selected_answer": {"answer_html": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.
\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.
\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary("mvtnorm")\nlibrary("ggplot2")\nlibrary("dplyr")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that "method 1" is standard Cholesky, "method 2" is reverse Cholesky and "method 3" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (true Sigma)")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (true Sigma)")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (Sigma-hat)")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (Sigma-hat)")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (true Sigma)")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (true Sigma)")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (Sigma-hat)")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (Sigma-hat)")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (true Sigma)")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (true Sigma)")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (Sigma-hat)")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (Sigma-hat)")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (true Sigma)")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (true Sigma)")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (Sigma-hat)")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (Sigma-hat)")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)\n\n", "answer_id": 677304, "answer_text": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.\n\n\n\n\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.\n\n\n\n\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary(\"mvtnorm\")\nlibrary(\"ggplot2\")\nlibrary(\"dplyr\")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that \"method 1\" is standard Cholesky, \"method 2\" is reverse Cholesky and \"method 3\" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (true Sigma)\")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (true Sigma)\")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (Sigma-hat)\")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (true Sigma)\")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (true Sigma)\")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (Sigma-hat)\")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (Sigma-hat)\")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (true Sigma)\")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (true Sigma)\")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (Sigma-hat)\")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (true Sigma)\")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (true Sigma)\")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (Sigma-hat)\")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (Sigma-hat)\")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)", "answer_url": "https://stats.stackexchange.com/a/677304", "author": "Michael", "author_url": "https://stats.stackexchange.com/users/517013/michael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T10:48:26+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677243, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:48:26+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "26D2264C-CE23-455D-B111-D7C569BDFF44", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/26D2264C-CE23-455D-B111-D7C569BDFF44/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:53:50+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "77058962-D9B4-4D5E-BA55-FC2DD80B5B36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/77058962-D9B4-4D5E-BA55-FC2DD80B5B36/view-source"}], "score": 2, "updated_at": "2026-09-30T10:53:50+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.
\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.
\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary("mvtnorm")\nlibrary("ggplot2")\nlibrary("dplyr")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that "method 1" is standard Cholesky, "method 2" is reverse Cholesky and "method 3" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (true Sigma)")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (true Sigma)")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (Sigma-hat)")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (Sigma-hat)")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (true Sigma)")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (true Sigma)")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (Sigma-hat)")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (Sigma-hat)")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (true Sigma)")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (true Sigma)")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (Sigma-hat)")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (Sigma-hat)")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (true Sigma)")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (true Sigma)")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (Sigma-hat)")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (Sigma-hat)")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)\n\n", "answer_id": 677304, "answer_text": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.\n\n\n\n\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.\n\n\n\n\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary(\"mvtnorm\")\nlibrary(\"ggplot2\")\nlibrary(\"dplyr\")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that \"method 1\" is standard Cholesky, \"method 2\" is reverse Cholesky and \"method 3\" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (true Sigma)\")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (true Sigma)\")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (Sigma-hat)\")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (true Sigma)\")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (true Sigma)\")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (Sigma-hat)\")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (Sigma-hat)\")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (true Sigma)\")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (true Sigma)\")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (Sigma-hat)\")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (true Sigma)\")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (true Sigma)\")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (Sigma-hat)\")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (Sigma-hat)\")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)", "answer_url": "https://stats.stackexchange.com/a/677304", "author": "Michael", "author_url": "https://stats.stackexchange.com/users/517013/michael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T10:48:26+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677243, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:48:26+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "26D2264C-CE23-455D-B111-D7C569BDFF44", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/26D2264C-CE23-455D-B111-D7C569BDFF44/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:53:50+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "77058962-D9B4-4D5E-BA55-FC2DD80B5B36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/77058962-D9B4-4D5E-BA55-FC2DD80B5B36/view-source"}], "score": 2, "updated_at": "2026-09-30T10:53:50+00:00"}], "domain": "statistics", "external_links": ["https://github.com/cran/nlme", "https://i.sstatic.net/65PG6zuB.png", "https://i.sstatic.net/XWUljnac.png", "https://www.stata.com/manuals/me.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": "Michael", "question_author_url": "https://stats.stackexchange.com/users/517013/michael", "question_author_user_type": "registered", "question_created_at": "2026-09-23T09:39:51+00:00", "question_html": "I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).
What I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals
\nThis is based on the works of José C. Pinheiro and Douglas M. Bates. The nlme package in R references their book "Mixed effects models in S and S-PLUS" (2000), while Stata references their article "Computational Methods for Multilevel Modelling" (1998) (see page 575 of "STATA MULTILEVEL MIXED-EFFECTS REFERENCE MANUAL RELEASE 19. The terminology is a bit confusing, as 'normalized' residuals in R are called 'standardized' residuals in stata, which is not to be confused with 'Pearson' residuals, which is what R considers 'standardized').
However, the way the matrix square root is computed is different between the two programs. The result can have a rather significant impact on whether or not the normalized residuals actually seem to follow a normal distribution.
\nThe way R computes the matrix square root is through the Cholesky decomposition A = L*L^T (using the chol function from FORTRAN77). I cannot access the source code for Stata, but it seems like Stata uses Cholesky decomposition as well, however using a Cholesky decomposition algorithm starting at "the bottom right" of the matrix instead of "the top left" such that A = L^T * L. Using these two methods for Cholesky decomposition, I have been able to recreate the normalised residuals from R and Stata respectively.
When using QQ-plots on the normalized residuals calculated with R and those calculated with Stata, the two results plots imply different conclusions about the normality of the residuals.
\nIn principle, could one not use several different methods for Cholesky decomposition to compute a matrix square root and therefore come to significantly different conclusions? Would it therefore not be preferable to use eigenvalue decomposition to compute a matrix square root as opposed to Cholesky decomposition? One reason I believe EVD would be better is that it does not require transposing one "square root", i.e. we have directly that A^(1/2) * A^(1/2) = A.
\nHere, I have added an example:
\nratlong <- read.csv("ratlong.csv") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = "REML",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = "r"),\n pearson = residuals(model, type = "p"),\n norm_res_R = residuals(model, type = "n"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n\nAccording to the nmle package (retrieved from github), the residuals are computed as such:
#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- "Normalized residuals"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[["Xy"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[["Xy"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, "maxCov")),\n logLik = double(1))[c("Xy", "logLik")]\n conLin[["Xy"]][] <- val[["Xy"]]\n conLin[["logLik"]] <- conLin[["logLik"]] + val[["logLik"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n\nI then manually computed the normalized residuals in R, through a regular Cholesky decomposition (same as t(chol) in R), through a "reverse" Cholesky decomposition and through EVD.
# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n\nThe results on the rat-example imply a left or a right-skew (Stata and R respecitvely) when compared to the standard normal, i.e. they may lead to different conlclusions about the model fit (I have an example, wherein the difference is more pronounced, but I do not want to break GDPR rules. Maybe someone can find a better example?). Using EVD, there does not seem to be as much of a skew to one side or the other.
\n\n\nThe figures are created via:
\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = "normalized residuals stata")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = "normalized residuals R")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = "normalized residuals EVD")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = "black", fill = "white") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = "normalised residuals stata (reverse Cholesky)")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = "black", fill = "white") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = "normalised residuals R (standard Cholesky)")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = "black", fill = "white") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = "normalised residuals EVD")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nThe log from the Stata-code is given here:
\n. \n. \n. import delim "ratlong.csv", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n\nI found out the data example I was working with was RatWeight from package heplots, although I was given simply given the "ratlong.csv"-file, which is a heavily manipulated and reordered version of RatWeight, so if you want to reproduce it, here is how (I hope you will bear with me):
rat <- RatWeight\nnames(rat) <- c("Group", "Weight0", "Weight1", "Weight2", "Weight3", "Weight4")\nrat$Group <- factor(rat$Group, levels = c("Control", "Thyroxin", "Thiouracil"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != "Thyroxin")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c("W", "time"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, "ratlong.csv", row.names = FALSE)\n\nPackages used in general:
\nlibrary(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)\n\n", "question_id": 677243, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).\n\n\n\n\nWhat I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals\n\n\n\n\nThis is based on the works of José C. Pinheiro and Douglas M. Bates. The nlme package in R references their book \"Mixed effects models in S and S-PLUS\" (2000), while Stata references their article \"Computational Methods for Multilevel Modelling\" (1998) (see page 575 of \"STATA MULTILEVEL MIXED-EFFECTS REFERENCE MANUAL RELEASE 19 (https://www.stata.com/manuals/me.pdf). The terminology is a bit confusing, as 'normalized' residuals in R are called 'standardized' residuals in stata, which is not to be confused with 'Pearson' residuals, which is what R considers 'standardized').\n\n\n\n\nHowever, the way the matrix square root is computed is different between the two programs. The result can have a rather significant impact on whether or not the normalized residuals actually seem to follow a normal distribution.\n\n\n\n\nThe way R computes the matrix square root is through the Cholesky decomposition A = L*L^T (using the chol function from FORTRAN77). I cannot access the source code for Stata, but it seems like Stata uses Cholesky decomposition as well, however using a Cholesky decomposition algorithm starting at \"the bottom right\" of the matrix instead of \"the top left\" such that A = L^T * L. Using these two methods for Cholesky decomposition, I have been able to recreate the normalised residuals from R and Stata respectively.\n\n\n\n\nWhen using QQ-plots on the normalized residuals calculated with R and those calculated with Stata, the two results plots imply different conclusions about the normality of the residuals.\n\n\n\n\nIn principle, could one not use several different methods for Cholesky decomposition to compute a matrix square root and therefore come to significantly different conclusions? Would it therefore not be preferable to use eigenvalue decomposition to compute a matrix square root as opposed to Cholesky decomposition? One reason I believe EVD would be better is that it does not require transposing one \"square root\", i.e. we have directly that A^(1/2) * A^(1/2) = A.\n\n\n\n\nHere, I have added an example:\n\n\n\n\nratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = \"REML\",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = \"r\"),\n pearson = residuals(model, type = \"p\"),\n norm_res_R = residuals(model, type = \"n\"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n\n\n\n\n\nAccording to the nmle package (retrieved from github (https://github.com/cran/nlme)), the residuals are computed as such:\n\n\n\n\n#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- \"Normalized residuals\"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[[\"Xy\"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[[\"Xy\"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, \"maxCov\")),\n logLik = double(1))[c(\"Xy\", \"logLik\")]\n conLin[[\"Xy\"]][] <- val[[\"Xy\"]]\n conLin[[\"logLik\"]] <- conLin[[\"logLik\"]] + val[[\"logLik\"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n\n\n\n\n\nI then manually computed the normalized residuals in R, through a regular Cholesky decomposition (same as t(chol) in R), through a \"reverse\" Cholesky decomposition and through EVD.\n\n\n\n\n# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n\n\n\n\n\nThe results on the rat-example imply a left or a right-skew (Stata and R respecitvely) when compared to the standard normal, i.e. they may lead to different conlclusions about the model fit (I have an example, wherein the difference is more pronounced, but I do not want to break GDPR rules. Maybe someone can find a better example?). Using EVD, there does not seem to be as much of a skew to one side or the other.\n\n\n\n\n[image: QQ-plot of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/65PG6zuB.png] (https://i.sstatic.net/65PG6zuB.png)\n\n\n\n\n[image: Histogram of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/XWUljnac.png] (https://i.sstatic.net/XWUljnac.png)\n\n\n\n\nThe figures are created via:\n\n\n\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals stata\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals R\")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals stata (reverse Cholesky)\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals R (standard Cholesky)\")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\n\n\n\n\nThe log from the Stata-code is given here:\n\n\n\n\n. \n. \n. import delim \"ratlong.csv\", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n\n\n\n\n\nI found out the data example I was working with was RatWeight from package heplots, although I was given simply given the \"ratlong.csv\"-file, which is a heavily manipulated and reordered version of RatWeight, so if you want to reproduce it, here is how (I hope you will bear with me):\n\n\n\n\nrat <- RatWeight\nnames(rat) <- c(\"Group\", \"Weight0\", \"Weight1\", \"Weight2\", \"Weight3\", \"Weight4\")\nrat$Group <- factor(rat$Group, levels = c(\"Control\", \"Thyroxin\", \"Thiouracil\"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != \"Thyroxin\")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c(\"W\", \"time\"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, \"ratlong.csv\", row.names = FALSE)\n\n\n\n\n\nPackages used in general:\n\n\n\n\nlibrary(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T09:39:51+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "7BC8F667-EB32-47A1-A802-2154A3633C12", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7BC8F667-EB32-47A1-A802-2154A3633C12/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T17:05:33+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "2EFBF184-EFA4-4618-B902-9EB0CF6CDAD1", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2EFBF184-EFA4-4618-B902-9EB0CF6CDAD1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-23T18:51:05+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "CFD9707D-EF4E-4CBF-A2FA-FC17B82ADC40", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CFD9707D-EF4E-4CBF-A2FA-FC17B82ADC40/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:15:18+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "DDCD4DF6-217B-4BCA-B9AB-A089EF38A03D", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/DDCD4DF6-217B-4BCA-B9AB-A089EF38A03D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:24:18+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "3E87BF4C-CB4D-492F-89AD-9AAEF44DF12F", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3E87BF4C-CB4D-492F-89AD-9AAEF44DF12F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:36:28+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "2160C566-F067-48AE-8E37-5DC1331F1A3F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2160C566-F067-48AE-8E37-5DC1331F1A3F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:51:58+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "30322FB2-132C-405E-8E54-9D57208C3C4C", "revision_number": 7, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/30322FB2-132C-405E-8E54-9D57208C3C4C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-09-24T00:39:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "A600B7A7-BD08-4855-A958-0D2321246CA5", "revision_number": 8, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A600B7A7-BD08-4855-A958-0D2321246CA5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-25T07:33:22+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "F655028C-4705-4B3D-BB65-71C57A6831E2", "revision_number": 9, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F655028C-4705-4B3D-BB65-71C57A6831E2/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-25T10:01:55+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "7549E095-451B-4062-AE3C-66AA61B7671C", "revision_number": 10, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7549E095-451B-4062-AE3C-66AA61B7671C/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata", "split": "train", "split_group": "598fe845d8f6ec9dfd2ba93f72b05bd7499c42da4f6a46494a772e71b8f59550", "tags": ["r", "mixed-model", "residuals", "stata", "normalization"], "thread_id": "stats:677243", "title": "Normalized residuals in mixed models, R (nlme) vs Stata"}}
{"accepted_answer": {"answer_html": "I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.
\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.
\nAs usual, @whuber has provided an excellent answer to this question. Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:
\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.
\n
I wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:
## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.
Now, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.
\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting. My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!
\n", "answer_id": 677263, "answer_text": "UPDATE\n\n\n\n\nI realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.\n\n\n\n\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.\n\n\n\n\n\n\n\nAs usual, @whuber has provided an excellent answer to this question (https://stats.stackexchange.com/a/159203/97844). Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:\n\n\n\n\n\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.\n\n\n\n\n\n\n\nI wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:\n\n\n\n\n## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\n\n\n\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.\n\n\n\n\nNow, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.\n\n\n\n\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting (https://stats.stackexchange.com/a/45764/97844). My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!", "answer_url": "https://stats.stackexchange.com/a/677263", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T13:44:43+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:44:43+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D364CE58-9CC7-407D-B6A6-CA7B48039B16", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D364CE58-9CC7-407D-B6A6-CA7B48039B16/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:54:35+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "311A980C-8FF9-4553-B91E-EB438CA49CF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/311A980C-8FF9-4553-B91E-EB438CA49CF5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T15:56:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "63585334-0D98-4386-B087-8A28FC121807", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/63585334-0D98-4386-B087-8A28FC121807/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T17:46:48+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D32B7BD3-C3DC-4992-8803-1AE622335BD6", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D32B7BD3-C3DC-4992-8803-1AE622335BD6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T19:02:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "FEC7CF2B-92E8-41E2-A10B-658E5657A289", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEC7CF2B-92E8-41E2-A10B-658E5657A289/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-27T15:15:15+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64ED3E27-F5FD-4A41-AA22-C4265D46E82F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64ED3E27-F5FD-4A41-AA22-C4265D46E82F/view-source"}], "score": 7, "updated_at": "2026-09-27T15:15:15+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677263, "sha256": "f3ee2830cd1580e0244d6f7f0f251ec8fa978cc823ab30ab52e174bd98dee53d", "source_url": "https://stats.stackexchange.com/a/677263"}], "other_answers": [], "product": "code_qa", "question": "I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite strong to cut through the noise.\n\n\n\n\nI asked stats support who wanted me to \"find some exact version of the ROC analysis, some analogue to Fisher's exact test\", but I can't really find anything like that in the literature. Generative AI tends to point me towards Mann-Whitney U-tests, exact logistic regression and/or Firth regression, but cannot point me towards any supporting literature.\n\n\n\n\nIntuitively that's not a bad idea. I might test if the FM width is normally distributed with Shapiro-Wilk, then test for differences with t-test/U-test depending on distribution and only then proceed towards ROC-analyses/logistic regression if an interesting pattern emerges.\n\n\n\n\nBut I will have to motivate the chosen approach formally. Is there an actual recommended approach? Is there any literature discussing the pros and cons of different strategies given this particular dilemma?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677262", "selected_answer": {"answer_html": "I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.
\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.
\nAs usual, @whuber has provided an excellent answer to this question. Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:
\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.
\n
I wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:
## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.
Now, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.
\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting. My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!
\n", "answer_id": 677263, "answer_text": "UPDATE\n\n\n\n\nI realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.\n\n\n\n\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.\n\n\n\n\n\n\n\nAs usual, @whuber has provided an excellent answer to this question (https://stats.stackexchange.com/a/159203/97844). Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:\n\n\n\n\n\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.\n\n\n\n\n\n\n\nI wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:\n\n\n\n\n## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\n\n\n\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.\n\n\n\n\nNow, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.\n\n\n\n\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting (https://stats.stackexchange.com/a/45764/97844). My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!", "answer_url": "https://stats.stackexchange.com/a/677263", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T13:44:43+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:44:43+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D364CE58-9CC7-407D-B6A6-CA7B48039B16", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D364CE58-9CC7-407D-B6A6-CA7B48039B16/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:54:35+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "311A980C-8FF9-4553-B91E-EB438CA49CF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/311A980C-8FF9-4553-B91E-EB438CA49CF5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T15:56:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "63585334-0D98-4386-B087-8A28FC121807", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/63585334-0D98-4386-B087-8A28FC121807/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T17:46:48+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D32B7BD3-C3DC-4992-8803-1AE622335BD6", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D32B7BD3-C3DC-4992-8803-1AE622335BD6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T19:02:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "FEC7CF2B-92E8-41E2-A10B-658E5657A289", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEC7CF2B-92E8-41E2-A10B-658E5657A289/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-27T15:15:15+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64ED3E27-F5FD-4A41-AA22-C4265D46E82F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64ED3E27-F5FD-4A41-AA22-C4265D46E82F/view-source"}], "score": 7, "updated_at": "2026-09-27T15:15:15+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677263, "answers": [{"answer_html": "I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.
\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.
\nAs usual, @whuber has provided an excellent answer to this question. Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:
\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.
\n
I wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:
## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.
Now, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.
\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting. My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!
\n", "answer_id": 677263, "answer_text": "UPDATE\n\n\n\n\nI realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.\n\n\n\n\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.\n\n\n\n\n\n\n\nAs usual, @whuber has provided an excellent answer to this question (https://stats.stackexchange.com/a/159203/97844). Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:\n\n\n\n\n\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.\n\n\n\n\n\n\n\nI wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:\n\n\n\n\n## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\n\n\n\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.\n\n\n\n\nNow, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.\n\n\n\n\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting (https://stats.stackexchange.com/a/45764/97844). My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!", "answer_url": "https://stats.stackexchange.com/a/677263", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T13:44:43+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:44:43+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D364CE58-9CC7-407D-B6A6-CA7B48039B16", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D364CE58-9CC7-407D-B6A6-CA7B48039B16/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:54:35+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "311A980C-8FF9-4553-B91E-EB438CA49CF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/311A980C-8FF9-4553-B91E-EB438CA49CF5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T15:56:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "63585334-0D98-4386-B087-8A28FC121807", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/63585334-0D98-4386-B087-8A28FC121807/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T17:46:48+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D32B7BD3-C3DC-4992-8803-1AE622335BD6", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D32B7BD3-C3DC-4992-8803-1AE622335BD6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T19:02:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "FEC7CF2B-92E8-41E2-A10B-658E5657A289", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEC7CF2B-92E8-41E2-A10B-658E5657A289/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-27T15:15:15+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64ED3E27-F5FD-4A41-AA22-C4265D46E82F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64ED3E27-F5FD-4A41-AA22-C4265D46E82F/view-source"}], "score": 7, "updated_at": "2026-09-27T15:15:15+00:00"}], "domain": "statistics", "external_links": [], "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": "Magnus", "question_author_url": "https://stats.stackexchange.com/users/91971/magnus", "question_author_user_type": "registered", "question_created_at": "2026-09-25T12:51:07+00:00", "question_html": "I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite strong to cut through the noise.
\nI asked stats support who wanted me to "find some exact version of the ROC analysis, some analogue to Fisher's exact test", but I can't really find anything like that in the literature. Generative AI tends to point me towards Mann-Whitney U-tests, exact logistic regression and/or Firth regression, but cannot point me towards any supporting literature.
\nIntuitively that's not a bad idea. I might test if the FM width is normally distributed with Shapiro-Wilk, then test for differences with t-test/U-test depending on distribution and only then proceed towards ROC-analyses/logistic regression if an interesting pattern emerges.
\nBut I will have to motivate the chosen approach formally. Is there an actual recommended approach? Is there any literature discussing the pros and cons of different strategies given this particular dilemma?
\n", "question_id": 677262, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite strong to cut through the noise.\n\n\n\n\nI asked stats support who wanted me to \"find some exact version of the ROC analysis, some analogue to Fisher's exact test\", but I can't really find anything like that in the literature. Generative AI tends to point me towards Mann-Whitney U-tests, exact logistic regression and/or Firth regression, but cannot point me towards any supporting literature.\n\n\n\n\nIntuitively that's not a bad idea. I might test if the FM width is normally distributed with Shapiro-Wilk, then test for differences with t-test/U-test depending on distribution and only then proceed towards ROC-analyses/logistic regression if an interesting pattern emerges.\n\n\n\n\nBut I will have to motivate the chosen approach formally. Is there an actual recommended approach? Is there any literature discussing the pros and cons of different strategies given this particular dilemma?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Magnus", "profile_url": "https://stats.stackexchange.com/users/91971/magnus", "user_type": "registered"}, "created_at": "2026-09-25T12:51:07+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "1AFA5A57-BDDE-474E-91DC-1D2E2378AE47", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1AFA5A57-BDDE-474E-91DC-1D2E2378AE47/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-25T12:59:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64F69FAD-C7B9-4C46-B108-F7598EB068D1", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64F69FAD-C7B9-4C46-B108-F7598EB068D1/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-25T21:01:14+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C4BCF8DD-9A97-4832-BA8D-BAF89A4AF37C", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/C4BCF8DD-9A97-4832-BA8D-BAF89A4AF37C/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677262/binary-response-variable-with-one-continuous-independent-variable-in-small-sampl", "split": "train", "split_group": "1e66b45b615abb7305245529ef0b62a715e6d164ab6bdac80764f20b0da6fe64", "tags": ["binary-data", "small-sample"], "thread_id": "stats:677262", "title": "Binary response variable with one continuous independent variable in small sample?"}} {"accepted_answer": {"answer_html": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$
\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$
\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.
\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.
\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$
\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n\n", "answer_id": 677268, "answer_text": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$\n\n\n\n\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$\n\n\n\n\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question (https://stats.stackexchange.com/q/677226/2958), having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.\n\n\n\n\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.\n\n\n\n\n\n\n\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$\n\n\n\n\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667", "answer_url": "https://stats.stackexchange.com/a/677268", "author": "Henry", "author_url": "https://stats.stackexchange.com/users/2958/henry", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T14:10:23+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Henry", "profile_url": "https://stats.stackexchange.com/users/2958/henry", "user_type": "registered"}, "created_at": "2026-09-26T14:10:23+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C96EACA9-97B0-4929-B972-DA5D20ED4759", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C96EACA9-97B0-4929-B972-DA5D20ED4759/view-source"}], "score": 4, "updated_at": "2026-09-26T14:10:23+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "set.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf(\"Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n\",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677266, "sha256": "b4b2cb661ed207973b568adb7f146f26de7721bf9d233fab67817288d6cbac29", "source_url": "https://stats.stackexchange.com/questions/677266/how-to-set-up-a-simulation-study"}, {"block_index": 0, "code_text": "yhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677268, "sha256": "1f520efb478c1a41ff425811f24e74461aaaf2f6cd8ba7834ea50d039660d1c6", "source_url": "https://stats.stackexchange.com/a/677268"}], "other_answers": [{"answer_html": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.
\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:
\nOptimise jointly $u,v$ (maximum likelihood).
\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).
\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable
\n", "answer_id": 677267, "answer_text": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.\n\n\n\n\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:\n\n\n\n\n\nHave variables $u$, $v$, and take $\\frac{\\alpha}{\\alpha+\\beta}=expit\\left(u\\right)=\\frac{1}{1+\\exp\\left(-u\\right)}$, $\\alpha=softplus(v)=\\log\\left(1+\\exp(v)\\right)$\n\n\n\n\n$\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$\n\n\n\n\n\nOptimise jointly $u,v$ (maximum likelihood).\n\n\n\n\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).\n\n\n\n\n\n\n\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable", "answer_url": "https://stats.stackexchange.com/a/677267", "author": "Cryo", "author_url": "https://stats.stackexchange.com/users/275239/cryo", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T12:24:08+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:24:08+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:33:54+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "24348886-EE3F-4779-9F2E-6DF7895E9D85", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/24348886-EE3F-4779-9F2E-6DF7895E9D85/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-09-26T13:34:16+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "57B9D992-5586-4BC1-9973-DD3482A5AA98", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/57B9D992-5586-4BC1-9973-DD3482A5AA98/view-source"}], "score": 5, "updated_at": "2026-09-26T13:34:16+00:00"}], "product": "code_qa", "question": "Here is a hierarchical data generating process (DGP):\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\n$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$\n\n\n\n\nUsing a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of $n$ and $k$ I should select to get good results (I know this hugely subjective) such that $nk$ is minimized (assume that increasing $n$ by 1 costs the same as increase $k$ by 1).\n\n\n\n\nAfter doing some research, it seems the best way to handle this question is by a simulation study. Assuming $\\alpha,\\ \\beta$ are known, I could sample from the DGP for different combinations of $n$ and $k$ and record the average length of the confidence intervals and average coverage rate at each combination. Since the mean estimator is unbiased regardless of the choice in $n$ or $k$, I could use average CI length and average coverage rate to make sure I am not getting a misleadingly good coverage rate at the expense of a large CI.\n\n\n\n\nHere is how I plan to do this in R (I wrote the code to focus on readability instead of speed - I use a moment based estimator and consider different true combinations of parameters):\n\n\n\n\nset.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf(\"Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n\",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n\n\n\n\n\nWhen visualized, the results look like this (direct upload was not working - however it seems to show that when $n$ and $k$ are both large, for many cases, we get high coverage and smaller CI lengths on average): https://imgur.com/a/tgHbtLz (https://imgur.com/a/tgHbtLz)\n\n\n\n\nThe tricky part now is to try and guess what the true value of $\\alpha,\\ \\beta$ might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what $n,k$ to use if I want average CI length and average coverage rate to be within certain ranges.\n\n\n\n\nI am looking for feedback on my methodology. Should I have done this a different way?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677266", "selected_answer": {"answer_html": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$
\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$
\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.
\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.
\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$
\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n\n", "answer_id": 677268, "answer_text": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$\n\n\n\n\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$\n\n\n\n\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question (https://stats.stackexchange.com/q/677226/2958), having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.\n\n\n\n\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.\n\n\n\n\n\n\n\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$\n\n\n\n\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667", "answer_url": "https://stats.stackexchange.com/a/677268", "author": "Henry", "author_url": "https://stats.stackexchange.com/users/2958/henry", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T14:10:23+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Henry", "profile_url": "https://stats.stackexchange.com/users/2958/henry", "user_type": "registered"}, "created_at": "2026-09-26T14:10:23+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C96EACA9-97B0-4929-B972-DA5D20ED4759", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C96EACA9-97B0-4929-B972-DA5D20ED4759/view-source"}], "score": 4, "updated_at": "2026-09-26T14:10:23+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677268, "answers": [{"answer_html": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.
\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:
\nOptimise jointly $u,v$ (maximum likelihood).
\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).
\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable
\n", "answer_id": 677267, "answer_text": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.\n\n\n\n\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:\n\n\n\n\n\nHave variables $u$, $v$, and take $\\frac{\\alpha}{\\alpha+\\beta}=expit\\left(u\\right)=\\frac{1}{1+\\exp\\left(-u\\right)}$, $\\alpha=softplus(v)=\\log\\left(1+\\exp(v)\\right)$\n\n\n\n\n$\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$\n\n\n\n\n\nOptimise jointly $u,v$ (maximum likelihood).\n\n\n\n\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).\n\n\n\n\n\n\n\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable", "answer_url": "https://stats.stackexchange.com/a/677267", "author": "Cryo", "author_url": "https://stats.stackexchange.com/users/275239/cryo", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T12:24:08+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:24:08+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:33:54+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "24348886-EE3F-4779-9F2E-6DF7895E9D85", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/24348886-EE3F-4779-9F2E-6DF7895E9D85/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-09-26T13:34:16+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "57B9D992-5586-4BC1-9973-DD3482A5AA98", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/57B9D992-5586-4BC1-9973-DD3482A5AA98/view-source"}], "score": 5, "updated_at": "2026-09-26T13:34:16+00:00"}, {"answer_html": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$
\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$
\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.
\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.
\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$
\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n\n", "answer_id": 677268, "answer_text": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$\n\n\n\n\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$\n\n\n\n\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question (https://stats.stackexchange.com/q/677226/2958), having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.\n\n\n\n\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.\n\n\n\n\n\n\n\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$\n\n\n\n\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667", "answer_url": "https://stats.stackexchange.com/a/677268", "author": "Henry", "author_url": "https://stats.stackexchange.com/users/2958/henry", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T14:10:23+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Henry", "profile_url": "https://stats.stackexchange.com/users/2958/henry", "user_type": "registered"}, "created_at": "2026-09-26T14:10:23+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C96EACA9-97B0-4929-B972-DA5D20ED4759", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C96EACA9-97B0-4929-B972-DA5D20ED4759/view-source"}], "score": 4, "updated_at": "2026-09-26T14:10:23+00:00"}], "domain": "statistics", "external_links": ["https://imgur.com/a/tgHbtLz"], "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-25T19:59:10+00:00", "question_html": "Here is a hierarchical data generating process (DGP):
\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$
\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$
\n
$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$
\nUsing a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of $n$ and $k$ I should select to get good results (I know this hugely subjective) such that $nk$ is minimized (assume that increasing $n$ by 1 costs the same as increase $k$ by 1).
\nAfter doing some research, it seems the best way to handle this question is by a simulation study. Assuming $\\alpha,\\ \\beta$ are known, I could sample from the DGP for different combinations of $n$ and $k$ and record the average length of the confidence intervals and average coverage rate at each combination. Since the mean estimator is unbiased regardless of the choice in $n$ or $k$, I could use average CI length and average coverage rate to make sure I am not getting a misleadingly good coverage rate at the expense of a large CI.
\nHere is how I plan to do this in R (I wrote the code to focus on readability instead of speed - I use a moment based estimator and consider different true combinations of parameters):
\nset.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf("Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n\nWhen visualized, the results look like this (direct upload was not working - however it seems to show that when $n$ and $k$ are both large, for many cases, we get high coverage and smaller CI lengths on average): https://imgur.com/a/tgHbtLz
\nThe tricky part now is to try and guess what the true value of $\\alpha,\\ \\beta$ might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what $n,k$ to use if I want average CI length and average coverage rate to be within certain ranges.
\nI am looking for feedback on my methodology. Should I have done this a different way?
\n", "question_id": 677266, "question_license": "CC BY-SA 4.0", "question_score": 6, "question_text": "Here is a hierarchical data generating process (DGP):\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\n$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$\n\n\n\n\nUsing a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of $n$ and $k$ I should select to get good results (I know this hugely subjective) such that $nk$ is minimized (assume that increasing $n$ by 1 costs the same as increase $k$ by 1).\n\n\n\n\nAfter doing some research, it seems the best way to handle this question is by a simulation study. Assuming $\\alpha,\\ \\beta$ are known, I could sample from the DGP for different combinations of $n$ and $k$ and record the average length of the confidence intervals and average coverage rate at each combination. Since the mean estimator is unbiased regardless of the choice in $n$ or $k$, I could use average CI length and average coverage rate to make sure I am not getting a misleadingly good coverage rate at the expense of a large CI.\n\n\n\n\nHere is how I plan to do this in R (I wrote the code to focus on readability instead of speed - I use a moment based estimator and consider different true combinations of parameters):\n\n\n\n\nset.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf(\"Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n\",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n\n\n\n\n\nWhen visualized, the results look like this (direct upload was not working - however it seems to show that when $n$ and $k$ are both large, for many cases, we get high coverage and smaller CI lengths on average): https://imgur.com/a/tgHbtLz (https://imgur.com/a/tgHbtLz)\n\n\n\n\nThe tricky part now is to try and guess what the true value of $\\alpha,\\ \\beta$ might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what $n,k$ to use if I want average CI length and average coverage rate to be within certain ranges.\n\n\n\n\nI am looking for feedback on my methodology. Should I have done this a different way?", "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-25T19:59:10+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "BDACA524-F3A6-491A-880E-A6871C920AE2", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/BDACA524-F3A6-491A-880E-A6871C920AE2/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-25T20:06:02+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD0D55CA-D20D-43CE-AF14-F3B414CC07CC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD0D55CA-D20D-43CE-AF14-F3B414CC07CC/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-26T14:16:51+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "33D7D8BE-907F-442F-B2B0-F7C572555835", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/33D7D8BE-907F-442F-B2B0-F7C572555835/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-26T17:38:27+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "CAC7EE3C-CE9C-4299-BF6B-07246FC0E1C1", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CAC7EE3C-CE9C-4299-BF6B-07246FC0E1C1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677266/how-to-set-up-a-simulation-study", "split": "train", "split_group": "21d3364431200c413f5adef6742bd9555e0cb33cda58781dfab79e3d31d1b7fb", "tags": ["r", "sampling", "estimation"], "thread_id": "stats:677266", "title": "How to set up a simulation study?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c(\"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \n \"yes\", \"yes\", \"yes\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \n \"yes\", \"yes\", \"yes\"), plant_trait_b = c(\"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = \"data.frame\")\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "0d4c015350ac6e446deed395928107c80f7a47277dbc4f431608021b6d63ad2f", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}, {"block_index": 1, "code_text": "library(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "21c4e8e4e0ff8e7c76472b5d9535727acc2468c51f9a428547eae7bec6bfcf35", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}, {"block_index": 2, "code_text": "beetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "96123ee4548f527a2d06370f07e0b7bca8e69441c77e97e0528da1a32687db42", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}, {"block_index": 3, "code_text": "beetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "3286f8f7a09d30d949cc01f68d5acdb326946b1d7ea1d1a42bef267b312e121a", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}], "other_answers": [], "product": "code_qa", "question": "I'm trying to decide which GLMM distribution is best for my data.\n\n\n\n\nI want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.\n\n\n\n\nThere were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, each treatment group had 5. Each plant genotype was planted 3 times, in 3 different planting_blocks.\n\n\n\n\nWe collected 56-100 seeds per plot (plot=planting_blockxplant_genotype combination); most had 100 seeds, but 4 plots had less than 100 seeds available. I then counted the number of beetle damaged seeds (seeds_beetle_damaged) in each sample.\n\n\n\n\n#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c(\"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \n \"yes\", \"yes\", \"yes\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \n \"yes\", \"yes\", \"yes\"), plant_trait_b = c(\"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = \"data.frame\")\n\n\n\n\n\n\n1. Binomial GLMM\n\n\n\n\nI first ran a binomial model with the glmmtmb package in R. My y variable was modeled as a binomial outcome that represented the number of beetle damaged seeds per plot. My fixed effects were plant_trait_a and plant_trait_b and I set planting_block as a random effect.\n\n\n\n\nUsing the DHARMa package I checked the residuals plots then tested for overdispersion and zero-inflation. I found that there was significant overdispersion (dispersion = 1.9633, p-value < 2.2e-16) and zero-inflation (ratioObsSim = 8.2305, p-value < 2.2e-16).\n\n\n\n\nlibrary(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n\n\n\n\n\n2. Zero-inflated beta binomial\n\n\n\n\nNext I ran a zero-inflated beta binomial model using the same fixed and random effects. I read online that the beta binomial distribution can address overdispersion in binomial models. Compared to the binomial model, the left side residuals plot (QQ plot) looked better - no longer S-shaped, data points were closer to red diagonal line. The p-value from the dispersion test was nonsignificant (dispersion = 1.3461, p-value = 0.096).\n\n\n\n\nbeetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n\n\n\n\n\n3.Zero-inflated beta\n\n\n\n\nI shared the results from the zero-inflated beta binomal model with a stats consultant at my university who uses SAS and has mostly worked with binomial GLMs. He said he's only seen one textbook mention the beta binomial distribution, and that since it's not as common as other distributions he is skeptical of the results.\n\n\n\n\nSo I decided to try running a model with a zero-inflated beta distribution. This seems somewhat more common than the beta binomial. I used the same fixed and random effects, but the y variable was changed to the proportion of beetle damaged seeds per sample (prop_beetle_damaged). The residuals plots looked good and the dispersion value was nonsignificant (dispersion = 1.3836, p-value = 0.056)\n\n\n\n\nbeetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n\n\n\n\n\nWhich model seems most appropriate for my data? I've read that when deciding between models with different distributions, the one with the lowest AIC value is the best fit. So should I go with the zero-inflated beta model?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677298", "selected_answer": {"answer_html": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...
\n", "answer_id": 677305, "answer_text": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...", "answer_url": "https://stats.stackexchange.com/a/677305", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T16:30:37+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677298, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-30T16:30:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD4B46E9-D946-4A17-BABC-04F3EE32D07E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD4B46E9-D946-4A17-BABC-04F3EE32D07E/view-source"}], "score": 1, "updated_at": "2026-09-30T16:30:37+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...
\n", "answer_id": 677305, "answer_text": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...", "answer_url": "https://stats.stackexchange.com/a/677305", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T16:30:37+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "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=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677298, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-30T16:30:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD4B46E9-D946-4A17-BABC-04F3EE32D07E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD4B46E9-D946-4A17-BABC-04F3EE32D07E/view-source"}], "score": 1, "updated_at": "2026-09-30T16:30:37+00:00"}], "domain": "statistics", "external_links": [], "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": "glew", "question_author_url": "https://stats.stackexchange.com/users/517245/glew", "question_author_user_type": "registered", "question_created_at": "2026-09-29T20:13:50+00:00", "question_html": "I'm trying to decide which GLMM distribution is best for my data.
\nI want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.
There were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, each treatment group had 5. Each plant genotype was planted 3 times, in 3 different planting_blocks.
We collected 56-100 seeds per plot (plot=planting_blockxplant_genotype combination); most had 100 seeds, but 4 plots had less than 100 seeds available. I then counted the number of beetle damaged seeds (seeds_beetle_damaged) in each sample.
#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c("yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "no", "no", "no", "no", "no", "yes", \n "yes", "yes", "yes", "no", "no", "no", "no", "no", "yes", "yes", \n "yes", "yes", "yes"), plant_trait_b = c("short", "short", "short", \n "short", "short", "short", "short", "short", "short", "short", \n "long", "long", "long", "long", "long", "long", "long", "long", \n "long", "long", "short", "short", "short", "short", "short", \n "short", "short", "short", "short", "short", "long", "long", \n "long", "long", "long", "long", "long", "long", "long", "long", \n "long", "long", "long", "long", "long", "long", "long", "long", \n "long", "short", "short", "short", "short", "short", "short", \n "short", "short", "short", "short"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = "data.frame")\n\n\n1. Binomial GLMM
\nI first ran a binomial model with the glmmtmb package in R. My y variable was modeled as a binomial outcome that represented the number of beetle damaged seeds per plot. My fixed effects were plant_trait_a and plant_trait_b and I set planting_block as a random effect.
Using the DHARMa package I checked the residuals plots then tested for overdispersion and zero-inflation. I found that there was significant overdispersion (dispersion = 1.9633, p-value < 2.2e-16) and zero-inflation (ratioObsSim = 8.2305, p-value < 2.2e-16).
\nlibrary(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n\n2. Zero-inflated beta binomial
\nNext I ran a zero-inflated beta binomial model using the same fixed and random effects. I read online that the beta binomial distribution can address overdispersion in binomial models. Compared to the binomial model, the left side residuals plot (QQ plot) looked better - no longer S-shaped, data points were closer to red diagonal line. The p-value from the dispersion test was nonsignificant (dispersion = 1.3461, p-value = 0.096).
\nbeetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n\n3.Zero-inflated beta
\nI shared the results from the zero-inflated beta binomal model with a stats consultant at my university who uses SAS and has mostly worked with binomial GLMs. He said he's only seen one textbook mention the beta binomial distribution, and that since it's not as common as other distributions he is skeptical of the results.
\nSo I decided to try running a model with a zero-inflated beta distribution. This seems somewhat more common than the beta binomial. I used the same fixed and random effects, but the y variable was changed to the proportion of beetle damaged seeds per sample (prop_beetle_damaged). The residuals plots looked good and the dispersion value was nonsignificant (dispersion = 1.3836, p-value = 0.056)
beetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n\nWhich model seems most appropriate for my data? I've read that when deciding between models with different distributions, the one with the lowest AIC value is the best fit. So should I go with the zero-inflated beta model?
\n", "question_id": 677298, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "I'm trying to decide which GLMM distribution is best for my data.\n\n\n\n\nI want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.\n\n\n\n\nThere were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, each treatment group had 5. Each plant genotype was planted 3 times, in 3 different planting_blocks.\n\n\n\n\nWe collected 56-100 seeds per plot (plot=planting_blockxplant_genotype combination); most had 100 seeds, but 4 plots had less than 100 seeds available. I then counted the number of beetle damaged seeds (seeds_beetle_damaged) in each sample.\n\n\n\n\n#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c(\"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \n \"yes\", \"yes\", \"yes\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \n \"yes\", \"yes\", \"yes\"), plant_trait_b = c(\"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = \"data.frame\")\n\n\n\n\n\n\n1. Binomial GLMM\n\n\n\n\nI first ran a binomial model with the glmmtmb package in R. My y variable was modeled as a binomial outcome that represented the number of beetle damaged seeds per plot. My fixed effects were plant_trait_a and plant_trait_b and I set planting_block as a random effect.\n\n\n\n\nUsing the DHARMa package I checked the residuals plots then tested for overdispersion and zero-inflation. I found that there was significant overdispersion (dispersion = 1.9633, p-value < 2.2e-16) and zero-inflation (ratioObsSim = 8.2305, p-value < 2.2e-16).\n\n\n\n\nlibrary(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n\n\n\n\n\n2. Zero-inflated beta binomial\n\n\n\n\nNext I ran a zero-inflated beta binomial model using the same fixed and random effects. I read online that the beta binomial distribution can address overdispersion in binomial models. Compared to the binomial model, the left side residuals plot (QQ plot) looked better - no longer S-shaped, data points were closer to red diagonal line. The p-value from the dispersion test was nonsignificant (dispersion = 1.3461, p-value = 0.096).\n\n\n\n\nbeetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n\n\n\n\n\n3.Zero-inflated beta\n\n\n\n\nI shared the results from the zero-inflated beta binomal model with a stats consultant at my university who uses SAS and has mostly worked with binomial GLMs. He said he's only seen one textbook mention the beta binomial distribution, and that since it's not as common as other distributions he is skeptical of the results.\n\n\n\n\nSo I decided to try running a model with a zero-inflated beta distribution. This seems somewhat more common than the beta binomial. I used the same fixed and random effects, but the y variable was changed to the proportion of beetle damaged seeds per sample (prop_beetle_damaged). The residuals plots looked good and the dispersion value was nonsignificant (dispersion = 1.3836, p-value = 0.056)\n\n\n\n\nbeetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n\n\n\n\n\nWhich model seems most appropriate for my data? I've read that when deciding between models with different distributions, the one with the lowest AIC value is the best fit. So should I go with the zero-inflated beta model?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "glew", "profile_url": "https://stats.stackexchange.com/users/517245/glew", "user_type": "registered"}, "created_at": "2026-09-29T20:13:50+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D8B5E82E-0E38-4027-9C48-93E1F5E3D662", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D8B5E82E-0E38-4027-9C48-93E1F5E3D662/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "glew", "profile_url": "https://stats.stackexchange.com/users/517245/glew", "user_type": "registered"}, "created_at": "2026-09-30T15:18:51+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C946D7BE-B64A-4585-AC40-0C1885066383", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C946D7BE-B64A-4585-AC40-0C1885066383/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom", "split": "train", "split_group": "3123c426022f04d2481edd65d05980cf35eac64127fe7532f97efe75c659bca6", "tags": ["binomial-distribution", "glmm", "beta-distribution", "glmmtmb", "beta-binomial-distribution"], "thread_id": "stats:677298", "title": "Need help deciding what zero-inflated GLMM to use: beta, binomial, or beta binomial"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45100, "sha256": "c2c40b470711cdaff8fdd07d388ca7dbff1238a76bfd60220b44fdb4267ddeeb", "source_url": "https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent"}], "other_answers": [], "product": "code_qa", "question": "I have this Exercise in my Numerical Optimization class and here it is:\n\n\n\n\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:\n\n\n\n\n\nthe underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$\n\n\n\n\nthe measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$\n\n\n\n\nthe observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$\n\n\n\n\n\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:\n\n\n\n\n\nGradient descent\n\n\n\n\nAccelerated gradient descent\n\n\n\n\n\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.\n\n\n\n\nThis is my code in Python:\n\n\n\n\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm (https://ibb.co/KjKshhKm) , https://ibb.co/2DN3bnV (https://ibb.co/2DN3bnV) , and https://ibb.co/Zpn0JY7z (https://ibb.co/Zpn0JY7z) .\n\n\n\n\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45100", "selected_answer": {"answer_html": "Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.
\nHence one might get steps where the objective is not minimized.
There are monotonic versions of some of the methods.
\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (Code) and Monotonicity and Restart in Fast Gradient Methods.
Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.
\nHence one might get steps where the objective is not minimized.
There are monotonic versions of some of the methods.
\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (Code) and Monotonicity and Restart in Fast Gradient Methods.
I have this Exercise in my Numerical Optimization class and here it is:
\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:
\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:
\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.
\nThis is my code in Python:
\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = "Gradient Descent")\n plt.semilogy(agd_values, label = "Accelerated Gradient Descent")\n plt.xlabel("Iteration")\n plt.ylabel("Objective Value with Logarithmic Scale")\n plt.title("Ridge Regression: Objective Value vs Iteration "+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm , https://ibb.co/2DN3bnV , and https://ibb.co/Zpn0JY7z .
\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.
\n", "question_id": 45100, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I have this Exercise in my Numerical Optimization class and here it is:\n\n\n\n\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:\n\n\n\n\n\nthe underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$\n\n\n\n\nthe measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$\n\n\n\n\nthe observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$\n\n\n\n\n\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:\n\n\n\n\n\nGradient descent\n\n\n\n\nAccelerated gradient descent\n\n\n\n\n\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.\n\n\n\n\nThis is my code in Python:\n\n\n\n\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm (https://ibb.co/KjKshhKm) , https://ibb.co/2DN3bnV (https://ibb.co/2DN3bnV) , and https://ibb.co/Zpn0JY7z (https://ibb.co/Zpn0JY7z) .\n\n\n\n\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Sid Meka", "profile_url": "https://scicomp.stackexchange.com/users/51369/sid-meka", "user_type": "registered"}, "created_at": "2025-06-07T03:14:18+00:00", "raw_file": "raw/codex_api_v1/18019c65cead443968e23d401a2956091deb8b40ada648e04bed5e2f03ce54b5_1790825348716030900_0.json", "raw_sha256": "05729e3e9dd3f73dae19eda7639475c736dfb4d5818353d669924bc12ddae880", "revision_guid": "211F9448-16A8-4E36-8763-3B16D1CD1986", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/211F9448-16A8-4E36-8763-3B16D1CD1986/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent", "split": "train", "split_group": "ddd364ccf30cc296781c53becb9c4293936b018fbfccf6baa82fcd982ae5b9df", "tags": ["optimization", "python", "numerics", "regression", "data-analysis"], "thread_id": "scicomp:45100", "title": "Gradient Descent vs Accelerated Gradient Descent"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45105, "sha256": "b1990766f774a1d5b850c3adb758d23b68bc5ef84affbe8978c36bc7ea02fb03", "source_url": "https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting"}], "other_answers": [], "product": "code_qa", "question": "Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.\n\n\n\n\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:\n\n\n\n\n\n$\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$\n\n\n\n\n$X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$\n\n\n\n\n$z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$\n\n\n\n\n$y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$\n\n\n\n\n$\\theta_0$ has independent and identically distributed standard normal entries\n\n\n\n\n\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.\n\n\n\n\nHere is my code and these are the images that generate:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\nThese are the plots that generate:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/M60t0s9p.png] (https://i.sstatic.net/M60t0s9p.png)\n\n\n\n\nWhy are my plots increasing in general and not generally decreasing?\n\n\n\n\nWhat line of code do I need to fix?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45105", "selected_answer": {"answer_html": "The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).
The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).
Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.
\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:
\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.
\nHere is my code and these are the images that generate:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label="Gradient Descent")\n plt.semilogy(agd_values, label="Accelerated Gradient Descent")\n plt.xlabel("Iteration")\n plt.ylabel("Objective Value with Logarithmic Scale")\n plt.title("Logistic Regression: Objective Value vs Iteration "+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\nThese are the plots that generate:
\n\nWhy are my plots increasing in general and not generally decreasing?
\nWhat line of code do I need to fix?
\n", "question_id": 45105, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.\n\n\n\n\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:\n\n\n\n\n\n$\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$\n\n\n\n\n$X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$\n\n\n\n\n$z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$\n\n\n\n\n$y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$\n\n\n\n\n$\\theta_0$ has independent and identically distributed standard normal entries\n\n\n\n\n\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.\n\n\n\n\nHere is my code and these are the images that generate:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\nThese are the plots that generate:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/M60t0s9p.png] (https://i.sstatic.net/M60t0s9p.png)\n\n\n\n\nWhy are my plots increasing in general and not generally decreasing?\n\n\n\n\nWhat line of code do I need to fix?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Sid Meka", "profile_url": "https://scicomp.stackexchange.com/users/51369/sid-meka", "user_type": "registered"}, "created_at": "2025-06-09T03:53:39+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "6C5B17A4-CCFF-4791-B573-A3BEFEA6E971", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6C5B17A4-CCFF-4791-B573-A3BEFEA6E971/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anton Menshov", "profile_url": "https://scicomp.stackexchange.com/users/20688/anton-menshov", "user_type": "moderator"}, "created_at": "2025-06-10T17:23:33+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "04CCF3DF-8003-43DC-8B20-604199CED7CE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/04CCF3DF-8003-43DC-8B20-604199CED7CE/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M. A.", "profile_url": "https://scicomp.stackexchange.com/users/54367/m-a", "user_type": "registered"}, "created_at": "2025-08-03T03:10:56+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "432A63F6-E7D4-4894-AE88-DA68EC44307B", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/432A63F6-E7D4-4894-AE88-DA68EC44307B/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting", "split": "train", "split_group": "10d72cc0b1e82969ed446d7f6bc4fec359af8252377e4286e10dc421d486cc6e", "tags": ["optimization", "numpy", "regression"], "thread_id": "scicomp:45105", "title": "Logistic Regression: Gradient Descent and Accelerated Version Thereof not acting as intended"}} {"accepted_answer": null, "code_blocks": [{"block_index": 2, "code_text": "#includeThere is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.
\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$
\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n
If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n
My python code used to compute this and make the animation is below:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r"$\\phi(t)$", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f"Updating frame{frame}")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45119, "answer_text": "There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45119", "author": "spektr", "author_url": "https://scicomp.stackexchange.com/users/9804/spektr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-17T21:04:45+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": 45112, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "spektr", "profile_url": "https://scicomp.stackexchange.com/users/9804/spektr", "user_type": "registered"}, "created_at": "2025-06-17T21:04:45+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "E3F7E841-70B0-4D84-AA38-D0BBD92FA08E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}], "score": 3, "updated_at": "2025-06-17T21:04:45+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.
\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$
\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n
If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n
My python code used to compute this and make the animation is below:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r"$\\phi(t)$", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f"Updating frame{frame}")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45119, "answer_text": "There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45119", "author": "spektr", "author_url": "https://scicomp.stackexchange.com/users/9804/spektr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-17T21:04:45+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": 45112, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "spektr", "profile_url": "https://scicomp.stackexchange.com/users/9804/spektr", "user_type": "registered"}, "created_at": "2025-06-17T21:04:45+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "E3F7E841-70B0-4D84-AA38-D0BBD92FA08E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}], "score": 3, "updated_at": "2025-06-17T21:04:45+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Leapfrog_integration", "https://i.sstatic.net/2fRhShDM.gif", "https://i.sstatic.net/813fBMTK.gif", "https://jumpshare.com/s/IyNNcFdCeCTAcpIShWLY", "https://jumpshare.com/s/zPqlo3o0AGXPfadHQmxG"], "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": "Peter", "question_author_url": "https://scicomp.stackexchange.com/users/46677/peter", "question_author_user_type": "registered", "question_created_at": "2025-06-13T14:05:56+00:00", "question_html": "i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.
\nBelow i listed some input files
\nUnstable simulation
\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\nHere is much more stable simulation with this input file
\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\nThis is my C++ code.
\nsimulation.cpp
\n#include <iostream>\n#include <fstream>\n#include <cmath>\nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin("input.txt");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = new int[nx];\n double *phi = new double[nx];\n double *pi = new double[nx];\n double *psi = new double[nx];\n double *chi = new double[nx];\n for (int x = 0; x < nx; ++x) {\n if (x == 0) {\n sup[x] = x+1;\n sdn[x] = nx-1;\n }\n else if (x == nx-1) {\n sup[x] = 0;\n sdn[x] = x-1;\n }\n else {\n sup[x] = x+1;\n sdn[x] = x-1;\n }\n phi[x] = cos(x*dx);\n pi[x] = sin(x*dx);\n }\n std::ofstream fout;\n for (int t = 0; t < nt; ++t) {\n fout.open("output_"+std::to_string(t)+".txt");\n for (int x = 0; x < nx; ++x) {\n psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n fout << x*dx << '\\t' << phi[x] << '\\n';\n }\n for (int x = 0; x < nx; ++x) {\n phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n }\n for (int x = 0; x < nx; ++x) {\n chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n }\n for (int x = 0; x < nx; ++x) {\n pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n }\n fout.close();\n }\n delete[] psi;\n delete[] chi;\n delete[] pi;\n delete[] phi;\n delete[] sup;\n delete[] sdn;\n}\n\n\n", "question_id": 45112, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog (https://en.wikipedia.org/wiki/Leapfrog_integration) method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.\n\n\n\n\nBelow i listed some input files\n\n\n\n\nUnstable simulation (https://jumpshare.com/s/zPqlo3o0AGXPfadHQmxG)\n\n\n\n\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nHere is much more stable simulation (https://jumpshare.com/s/IyNNcFdCeCTAcpIShWLY) with this input file\n\n\n\n\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nThis is my C++ code.\n\n\n\n\nsimulation.cpp\n\n\n\n\n#include In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:
\nIn the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:
\nI wrote a symbolic regression tool in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?
import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n "abs": (sympy.Abs, operator.abs),\n "inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n "sqrt": (sympy.sqrt, np.sqrt),\n "cos": (sympy.cos, np.cos),\n "sin": (sympy.sin, np.sin),\n "exp": (sympy.tan, np.tan),\n "log": (sympy.log, np.log),\n "exp": (sympy.exp, np.exp),\n "sinh": (sympy.sinh, np.sinh),\n "cosh": (sympy.cosh, np.cosh),\n "floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n "ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor)}\n\nbinary_operators = {"+": (operator.add, operator.add),\n "-": (operator.sub, operator.sub),\n "*": (operator.mul, operator.mul),\n "/": (operator.truediv, operator.truediv),\n "//": (operator.floordiv, operator.floordiv),\n "%": (operator.mod, operator.mod),\n "**": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False}\nsymbols = sympy.symbols("x1 x2")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint("Top 10 features les plus corrélées (Pearson):\\n")\nfor name in correlations_sorted.head(10).index:\n print(f"{name:30} corr: {correlations[name]:+.4f}")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint("Top 10 features les plus utiles :\\n")\nfor name, score, r in features_sorted[:10]:\n print(f"{name:30} importance: {score:.4f} {r:.4f}")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint("un_ops", un_ops)\nprint("bin_ops", bin_ops)\n\nThe corresponding output is:
\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.
\nThe corresponding code could approach this:
\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = "a" + str(self.index)\n b = "b" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + "*" + str(self.leaf1) + "+" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr())) + ")+" + b)\n \n return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + ")+" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, "", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n #"abs": (sympy.Abs, operator.abs),\n #"inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n "sqrt": (sympy.sqrt, np.sqrt),\n "cos": (sympy.cos, np.cos),\n #"sin": (sympy.sin, np.sin),\n #"tan": (sympy.tan, np.tan),\n "log": (sympy.log, np.log),\n #"exp": (sympy.exp, np.exp),\n #"sinh": (sympy.sinh, np.sinh),\n #"cosh": (sympy.cosh, np.cosh),\n #"floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n #"ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor),\n }\n\nbinary_operators = {#"+": (operator.add, operator.add),\n #"-": (operator.sub, operator.sub),\n #"*": (operator.mul, operator.mul),\n #"/": (operator.truediv, operator.truediv),\n #"//": (operator.floordiv, operator.floordiv),\n #"%": (operator.mod, operator.mod),\n #"**": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False, "fmin": True, "fmax": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol("x1")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols("x1 x2"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:
\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == "a"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\nAnd the associated output (cos(log) optimization failed):
\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]\n\n", "question_id": 45114, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "I wrote a symbolic regression tool (https://github.com/Julien-Livet/SymbolicRegression) in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?\n\n\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n \"abs\": (sympy.Abs, operator.abs),\n \"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n \"sin\": (sympy.sin, np.sin),\n \"exp\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n \"exp\": (sympy.exp, np.exp),\n \"sinh\": (sympy.sinh, np.sinh),\n \"cosh\": (sympy.cosh, np.cosh),\n \"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n \"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor)}\n\nbinary_operators = {\"+\": (operator.add, operator.add),\n \"-\": (operator.sub, operator.sub),\n \"*\": (operator.mul, operator.mul),\n \"/\": (operator.truediv, operator.truediv),\n \"//\": (operator.floordiv, operator.floordiv),\n \"%\": (operator.mod, operator.mod),\n \"**\": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False}\nsymbols = sympy.symbols(\"x1 x2\")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint(\"Top 10 features les plus corrélées (Pearson):\\n\")\nfor name in correlations_sorted.head(10).index:\n print(f\"{name:30} corr: {correlations[name]:+.4f}\")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint(\"Top 10 features les plus utiles :\\n\")\nfor name, score, r in features_sorted[:10]:\n print(f\"{name:30} importance: {score:.4f} {r:.4f}\")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint(\"un_ops\", un_ops)\nprint(\"bin_ops\", bin_ops)\n\n\n\n\n\nThe corresponding output is:\n\n\n\n\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\n\n\n\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.\n\n\n\n\nThe corresponding code could approach this:\n\n\n\n\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = \"a\" + str(self.index)\n b = \"b\" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + \"*\" + str(self.leaf1) + \"+\" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr())) + \")+\" + b)\n \n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + \")+\" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, \"\", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n #\"abs\": (sympy.Abs, operator.abs),\n #\"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n #\"sin\": (sympy.sin, np.sin),\n #\"tan\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n #\"exp\": (sympy.exp, np.exp),\n #\"sinh\": (sympy.sinh, np.sinh),\n #\"cosh\": (sympy.cosh, np.cosh),\n #\"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n #\"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor),\n }\n\nbinary_operators = {#\"+\": (operator.add, operator.add),\n #\"-\": (operator.sub, operator.sub),\n #\"*\": (operator.mul, operator.mul),\n #\"/\": (operator.truediv, operator.truediv),\n #\"//\": (operator.floordiv, operator.floordiv),\n #\"%\": (operator.mod, operator.mod),\n #\"**\": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False, \"fmin\": True, \"fmax\": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol(\"x1\")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols(\"x1 x2\"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\n\n\n\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:\n\n\n\n\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == \"a\"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\n\n\n\n\nAnd the associated output (cos(log) optimization failed):\n\n\n\n\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-15T09:46:23+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "6EC977E1-3082-4152-AE79-21C738DBF959", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6EC977E1-3082-4152-AE79-21C738DBF959/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-15T17:29:07+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "B4A3E844-33AB-4467-864F-D74942286C5A", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B4A3E844-33AB-4467-864F-D74942286C5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-16T18:01:50+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "4E41E649-9940-470F-BD64-37949F9902D3", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/4E41E649-9940-470F-BD64-37949F9902D3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-17T08:11:19+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "C61EE61B-3C64-482A-BAC2-3A48B78BE0AE", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C61EE61B-3C64-482A-BAC2-3A48B78BE0AE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression", "split": "train", "split_group": "07c5c062925aee88caf5e7ca1c0a8add39323326adf026634b0bca11257a82ca", "tags": ["python", "regression", "sympy"], "thread_id": "scicomp:45114", "title": "Find necessary operators for symbolic regression"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45132, "sha256": "daf7c1f5e770a9fe6fe40e7f104e8f930491aaaf3fd354e26756660092fce0d9", "source_url": "https://scicomp.stackexchange.com/a/45132"}], "other_answers": [], "product": "code_qa", "question": "CONTEXT FOR THE QUESTION\n\n\n\n\nI'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the source game uses all 3 angles for every bone, but the destination game only allows for 2 angles for some of the bones while the remaining angle is always 0.\n\n\n\n\nFor now I'm specifically interested in character arms that mainly consist of the following bones: shoulder, upper arm, forearm. Shoulder uses 2 angles (pitch, roll), upper arm uses 3 angles (yaw, pitch, roll), forearm uses 2 angles (yaw, pitch). Angle order for all the bones is YXZ (yaw, pitch, roll).\n\n\n\n\nTHE QUESTION\n\n\n\n\nHaving data for all 3 angles for all 3 arm bones from the source game, how do I convert it to the destination game's format by discarding shoulder's yaw data and forearm's roll data but modifying all the remaining data to achieve the best possible visual match to the original animation?\n\n\n\n\nIs it at all possible to calculate something like this? I'm thinking it should be possible since the games share a lot of animations that look the same visually. So the developers must have had some kind of way to discard some of the data and compensate for it by modifying other values.\n\n\n\n\nI have managed to do it manually for one frame by experimenting with different values but obviously it's not viable to do if for every frame in many animations.\n\n\n\n\nFor example, in this frame the original data is (in degrees, the order is yaw, pitch, roll):\n\n\n\n\nShoulder 4.22, -11.25, -105.47\n\n\n\n\nUpper arm -11.25, -29.53, -45.00\n\n\n\n\nForearm 21.09, -30.94, -111.09\n\n\n\n\nMy modified data:\n\n\n\n\nShoulder 0.00, -11.25, -105.47\n\n\n\n\nUpper arm 49.22, -29.53, -45.00\n\n\n\n\nForearm -105.47, -98.44, 0.00\n\n\n\n\nWhat the result looks like (look at the left arm only). Of course, it won't be an exact match but something like this is close enough for me if I can automate the process.\n\n\n\n\nhttps://i.sstatic.net/XWepsVJc.gif (https://i.sstatic.net/XWepsVJc.gif)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45129", "selected_answer": {"answer_html": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.
\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a "pole" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.
\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize
from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.
\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.
\n", "answer_id": 45132, "answer_text": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.\n\n\n\n\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a \"pole\" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.\n\n\n\n\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize\n\n\n\n\nfrom scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\n\n\n\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.\n\n\n\n\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.", "answer_url": "https://scicomp.stackexchange.com/a/45132", "author": "Mikael Öhman", "author_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-21T13:55:43+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": 45129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Mikael Öhman", "profile_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "user_type": "registered"}, "created_at": "2025-06-21T13:55:43+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "71AFAA67-7DB9-4B14-A90D-8C508E2041E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/71AFAA67-7DB9-4B14-A90D-8C508E2041E0/view-source"}], "score": 2, "updated_at": "2025-06-21T13:55:43+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.
\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a "pole" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.
\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize
from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.
\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.
\n", "answer_id": 45132, "answer_text": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.\n\n\n\n\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a \"pole\" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.\n\n\n\n\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize\n\n\n\n\nfrom scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\n\n\n\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.\n\n\n\n\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.", "answer_url": "https://scicomp.stackexchange.com/a/45132", "author": "Mikael Öhman", "author_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-21T13:55:43+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": 45129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Mikael Öhman", "profile_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "user_type": "registered"}, "created_at": "2025-06-21T13:55:43+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "71AFAA67-7DB9-4B14-A90D-8C508E2041E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/71AFAA67-7DB9-4B14-A90D-8C508E2041E0/view-source"}], "score": 2, "updated_at": "2025-06-21T13:55:43+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/XWepsVJc.gif"], "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": "Inspired", "question_author_url": "https://scicomp.stackexchange.com/users/54154/inspired", "question_author_user_type": "registered", "question_created_at": "2025-06-20T15:11:42+00:00", "question_html": "CONTEXT FOR THE QUESTION
\nI'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the source game uses all 3 angles for every bone, but the destination game only allows for 2 angles for some of the bones while the remaining angle is always 0.
\nFor now I'm specifically interested in character arms that mainly consist of the following bones: shoulder, upper arm, forearm. Shoulder uses 2 angles (pitch, roll), upper arm uses 3 angles (yaw, pitch, roll), forearm uses 2 angles (yaw, pitch). Angle order for all the bones is YXZ (yaw, pitch, roll).
\nTHE QUESTION
\nHaving data for all 3 angles for all 3 arm bones from the source game, how do I convert it to the destination game's format by discarding shoulder's yaw data and forearm's roll data but modifying all the remaining data to achieve the best possible visual match to the original animation?
\nIs it at all possible to calculate something like this? I'm thinking it should be possible since the games share a lot of animations that look the same visually. So the developers must have had some kind of way to discard some of the data and compensate for it by modifying other values.
\nI have managed to do it manually for one frame by experimenting with different values but obviously it's not viable to do if for every frame in many animations.
\nFor example, in this frame the original data is (in degrees, the order is yaw, pitch, roll):
\nShoulder 4.22, -11.25, -105.47
\nUpper arm -11.25, -29.53, -45.00
\nForearm 21.09, -30.94, -111.09
\nMy modified data:
\nShoulder 0.00, -11.25, -105.47
\nUpper arm 49.22, -29.53, -45.00
\nForearm -105.47, -98.44, 0.00
\nWhat the result looks like (look at the left arm only). Of course, it won't be an exact match but something like this is close enough for me if I can automate the process.
\nhttps://i.sstatic.net/XWepsVJc.gif
\n", "question_id": 45129, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "CONTEXT FOR THE QUESTION\n\n\n\n\nI'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the source game uses all 3 angles for every bone, but the destination game only allows for 2 angles for some of the bones while the remaining angle is always 0.\n\n\n\n\nFor now I'm specifically interested in character arms that mainly consist of the following bones: shoulder, upper arm, forearm. Shoulder uses 2 angles (pitch, roll), upper arm uses 3 angles (yaw, pitch, roll), forearm uses 2 angles (yaw, pitch). Angle order for all the bones is YXZ (yaw, pitch, roll).\n\n\n\n\nTHE QUESTION\n\n\n\n\nHaving data for all 3 angles for all 3 arm bones from the source game, how do I convert it to the destination game's format by discarding shoulder's yaw data and forearm's roll data but modifying all the remaining data to achieve the best possible visual match to the original animation?\n\n\n\n\nIs it at all possible to calculate something like this? I'm thinking it should be possible since the games share a lot of animations that look the same visually. So the developers must have had some kind of way to discard some of the data and compensate for it by modifying other values.\n\n\n\n\nI have managed to do it manually for one frame by experimenting with different values but obviously it's not viable to do if for every frame in many animations.\n\n\n\n\nFor example, in this frame the original data is (in degrees, the order is yaw, pitch, roll):\n\n\n\n\nShoulder 4.22, -11.25, -105.47\n\n\n\n\nUpper arm -11.25, -29.53, -45.00\n\n\n\n\nForearm 21.09, -30.94, -111.09\n\n\n\n\nMy modified data:\n\n\n\n\nShoulder 0.00, -11.25, -105.47\n\n\n\n\nUpper arm 49.22, -29.53, -45.00\n\n\n\n\nForearm -105.47, -98.44, 0.00\n\n\n\n\nWhat the result looks like (look at the left arm only). Of course, it won't be an exact match but something like this is close enough for me if I can automate the process.\n\n\n\n\nhttps://i.sstatic.net/XWepsVJc.gif (https://i.sstatic.net/XWepsVJc.gif)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Inspired", "profile_url": "https://scicomp.stackexchange.com/users/54154/inspired", "user_type": "registered"}, "created_at": "2025-06-20T15:11:42+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "05E735E6-596D-4C15-8F55-58E74FB44487", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/05E735E6-596D-4C15-8F55-58E74FB44487/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45129/euler-angle-compression", "split": "train", "split_group": "559a48cf38ddb7e085009f562735e87213495f3f4322f83579162ce0b53f8c81", "tags": ["optimization", "numerics", "matrix", "approximation"], "thread_id": "scicomp:45129", "title": "Euler Angle Compression"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45185, "sha256": "0d2b3403abb149f3932d554d6c2486b994277a374004385ddffc9f133673e9b4", "source_url": "https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything"}, {"block_index": 1, "code_text": "GDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45185, "sha256": "ede79eca3b653fe963abc5472095cd3c0de51969188b65b546e86f4f30cabf88", "source_url": "https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything"}], "other_answers": [], "product": "code_qa", "question": "I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.\n\n\n\n\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).\n\n\n\n\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.\n\n\n\n\nHere are the fundamental cells of the notebook:\n\n\n\n\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\n\n\n\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention\n\n\n\n\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\n\n\n\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45185", "selected_answer": {"answer_html": "I might have found the solution, of which I'm listing the main points/observations here below:
\nOf course, if you have any further comments or observations let me know!
\n", "answer_id": 45186, "answer_text": "I might have found the solution, of which I'm listing the main points/observations here below:\n\n\n\n\n\nthe FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok\n\n\n\n\nthe dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output\n\n\n\n\nSPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)\n\n\n\n\na spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)\n\n\n\n\n\nOf course, if you have any further comments or observations let me know!", "answer_url": "https://scicomp.stackexchange.com/a/45186", "author": "Lorenzo Iori", "author_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-07-29T14:07:20+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": 45185, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-29T14:07:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "163AA634-CBFB-456A-AD54-8FFDF16B1F6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}], "score": 3, "updated_at": "2025-07-29T14:07:20+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I might have found the solution, of which I'm listing the main points/observations here below:
\nOf course, if you have any further comments or observations let me know!
\n", "answer_id": 45186, "answer_text": "I might have found the solution, of which I'm listing the main points/observations here below:\n\n\n\n\n\nthe FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok\n\n\n\n\nthe dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output\n\n\n\n\nSPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)\n\n\n\n\na spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)\n\n\n\n\n\nOf course, if you have any further comments or observations let me know!", "answer_url": "https://scicomp.stackexchange.com/a/45186", "author": "Lorenzo Iori", "author_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-07-29T14:07:20+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": 45185, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-29T14:07:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "163AA634-CBFB-456A-AD54-8FFDF16B1F6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}], "score": 3, "updated_at": "2025-07-29T14:07:20+00:00"}], "domain": "computational_science", "external_links": [], "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": "Lorenzo Iori", "question_author_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "question_author_user_type": "registered", "question_created_at": "2025-07-28T09:04:03+00:00", "question_html": "I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.
\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).
\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.
\nHere are the fundamental cells of the notebook:
\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention
\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...
\n", "question_id": 45185, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.\n\n\n\n\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).\n\n\n\n\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.\n\n\n\n\nHere are the fundamental cells of the notebook:\n\n\n\n\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\n\n\n\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention\n\n\n\n\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\n\n\n\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T09:04:03+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T09:15:52+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "BE26735D-FCBC-47F1-A566-F341DD41F55C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BE26735D-FCBC-47F1-A566-F341DD41F55C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T14:07:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "67CC67B8-AC93-4C69-9C21-0E6BDBF43102", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/67CC67B8-AC93-4C69-9C21-0E6BDBF43102/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T14:32:46+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "3BBDD6A2-8D30-430A-8EAF-A458144119BA", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3BBDD6A2-8D30-430A-8EAF-A458144119BA/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-29T14:04:04+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "B35F7AAE-2953-45D0-AD16-97CC9997095D", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B35F7AAE-2953-45D0-AD16-97CC9997095D/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything", "split": "train", "split_group": "97b6217d7144a5979dec5a03255a67e3c5677a313d0070d017c11d0b2f5ebede", "tags": ["python", "computational-physics", "fourier-transform", "wave-propagation", "operator-splitting"], "thread_id": "scicomp:45185", "title": "Split-step Fourier method for ultrashort pulse propagation predicts everything, but not the spectral phase"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45236, "sha256": "a635a3b792dcc184f0c00b72996f91bef2185154972e2cde57e2134986e16b37", "source_url": "https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere"}, {"block_index": 0, "code_text": "import operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45249, "sha256": "e4d397e8c08b33a0a68cb32ae1237aaa1b2c1f7aef510dd3dbb955639a59e4c1", "source_url": "https://scicomp.stackexchange.com/a/45249"}], "other_answers": [], "product": "code_qa", "question": "I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)\n\n\n\n\nOn page 4 I am trying to turn this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)\n\n\n\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'\n\n\n\n\nHere is my code, where am I going wrong? Thanks.\n\n\n\n\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45236", "selected_answer": {"answer_html": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:
\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n930.8341950323121\n\n", "answer_id": 45249, "answer_text": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121", "answer_url": "https://scicomp.stackexchange.com/a/45249", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-05T23:39:31+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": 45236, "revision_attribution": [{"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-10-05T23:39:31+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "75229101-2A2D-4D73-B2A6-80096500FF72", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/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-10-05T23:51:10+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "11E4EE0D-659A-4B05-9326-A45AF5CAE292", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}], "score": 3, "updated_at": "2025-10-05T23:51:10+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:
\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n930.8341950323121\n\n", "answer_id": 45249, "answer_text": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121", "answer_url": "https://scicomp.stackexchange.com/a/45249", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-05T23:39:31+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": 45236, "revision_attribution": [{"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-10-05T23:39:31+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "75229101-2A2D-4D73-B2A6-80096500FF72", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/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-10-05T23:51:10+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "11E4EE0D-659A-4B05-9326-A45AF5CAE292", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}], "score": 3, "updated_at": "2025-10-05T23:51:10+00:00"}], "domain": "computational_science", "external_links": ["http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf", "https://i.sstatic.net/Bod2tUzu.jpg"], "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": "gregb", "question_author_url": "https://scicomp.stackexchange.com/users/54734/gregb", "question_author_user_type": "registered", "question_created_at": "2025-09-15T21:46:02+00:00", "question_html": "I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf
\nOn page 4 I am trying to turn this:
\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'
\nHere is my code, where am I going wrong? Thanks.
\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f"The result of the expression is: {result}")\n\n\n", "question_id": 45236, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)\n\n\n\n\nOn page 4 I am trying to turn this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)\n\n\n\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'\n\n\n\n\nHere is my code, where am I going wrong? Thanks.\n\n\n\n\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "gregb", "profile_url": "https://scicomp.stackexchange.com/users/54734/gregb", "user_type": "registered"}, "created_at": "2025-09-15T21:46:02+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "67059698-6CDA-4CFD-903D-00B6A505C963", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/67059698-6CDA-4CFD-903D-00B6A505C963/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "gregb", "profile_url": "https://scicomp.stackexchange.com/users/54734/gregb", "user_type": "registered"}, "created_at": "2025-09-15T22:34:16+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "D1E2F3BD-4E46-4D76-9C39-8BDE6F9F73EC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D1E2F3BD-4E46-4D76-9C39-8BDE6F9F73EC/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "gregb", "profile_url": "https://scicomp.stackexchange.com/users/54734/gregb", "user_type": "registered"}, "created_at": "2025-09-16T10:52:22+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "9212784D-B74F-41A1-8936-363A81039240", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9212784D-B74F-41A1-8936-363A81039240/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere", "split": "train", "split_group": "76be7f1172db17290960f99d691aca6c9e1556b29863a36dbc96231e4c01a99d", "tags": ["python"], "thread_id": "scicomp:45236", "title": "Panini sticker python coding problem - bug in my code somewhere"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45246, "sha256": "8be5b8d21acaa3124f11278e9e1956344bcf0077a81fcffd51aa290ed3d02098", "source_url": "https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation"}, {"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45250, "sha256": "e4c81797aebb0183f7ae202e8f40018f8a8f8af8534cea97bd44225f2587483d", "source_url": "https://scicomp.stackexchange.com/a/45250"}], "other_answers": [], "product": "code_qa", "question": "I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45246", "selected_answer": {"answer_html": "Dear Lutz Lehmann and community,
\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.
\nFor reference, here is the corresponding code.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label="Velocity (m/s) at pipe center")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity at the middle of the pipe (m/s)")\nplt.title("Velocity evolution at the middle of the pipe")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f"t = {temps_selectionnes[i]:.1f} s")\nplt.xlabel("Position x (m)")\nplt.ylabel("Velocity (m/s)")\nplt.title("Velocity profile along the pipe at different times")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\nBest regards,\nRaphaël
\n", "answer_id": 45250, "answer_text": "Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël", "answer_url": "https://scicomp.stackexchange.com/a/45250", "author": "Ev0Cation", "author_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-07T14:19:16+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": 45246, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ev0Cation", "profile_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "user_type": "registered"}, "created_at": "2025-10-07T14:19:16+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C3CA863F-650C-4C2D-BD76-4C6863DC85E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}], "score": 2, "updated_at": "2025-10-07T14:19:16+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Dear Lutz Lehmann and community,
\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.
\nFor reference, here is the corresponding code.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label="Velocity (m/s) at pipe center")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity at the middle of the pipe (m/s)")\nplt.title("Velocity evolution at the middle of the pipe")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f"t = {temps_selectionnes[i]:.1f} s")\nplt.xlabel("Position x (m)")\nplt.ylabel("Velocity (m/s)")\nplt.title("Velocity profile along the pipe at different times")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\nBest regards,\nRaphaël
\n", "answer_id": 45250, "answer_text": "Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël", "answer_url": "https://scicomp.stackexchange.com/a/45250", "author": "Ev0Cation", "author_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-07T14:19:16+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": 45246, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ev0Cation", "profile_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "user_type": "registered"}, "created_at": "2025-10-07T14:19:16+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C3CA863F-650C-4C2D-BD76-4C6863DC85E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}], "score": 2, "updated_at": "2025-10-07T14:19:16+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/pB2ZlSLf.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": "Ev0Cation", "question_author_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "question_author_user_type": "registered", "question_created_at": "2025-10-03T16:37:31+00:00", "question_html": "I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.
\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.
\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.
\nCould you please give me some guidance on how to solve this problem please?
\nI will include my current code and figure below for reference.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label="Velocity (m/s)")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity")\nplt.title("Velocity evolution")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n", "question_id": 45246, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ev0Cation", "profile_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "user_type": "registered"}, "created_at": "2025-10-03T16:37:31+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "10D2B924-C266-46E3-844E-A857A83DB2A0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/10D2B924-C266-46E3-844E-A857A83DB2A0/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation", "split": "train", "split_group": "9ebe77aea8994080981623ecf3e0fcdc2cc1b6fdd3111e5329a42df53e338196", "tags": ["python", "fluid-dynamics", "boundary-conditions", "navier-stokes"], "thread_id": "scicomp:45246", "title": "Oscillations in 1D compressible Navier–Stokes simulation"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 1, "code_text": "#include The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.
\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.
\n", "answer_id": 45279, "answer_text": "The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.", "answer_url": "https://scicomp.stackexchange.com/a/45279", "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-11T08:18:46+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": 45261, "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-11T08:18:46+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/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-11T08:58:34+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A797FC73-4FE4-442D-9FE9-D187BC73817D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}], "score": 2, "updated_at": "2025-11-11T08:58:34+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.
\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.
\n", "answer_id": 45279, "answer_text": "The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.", "answer_url": "https://scicomp.stackexchange.com/a/45279", "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-11T08:18:46+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": 45261, "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-11T08:18:46+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/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-11T08:58:34+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A797FC73-4FE4-442D-9FE9-D187BC73817D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}], "score": 2, "updated_at": "2025-11-11T08:58:34+00:00"}], "domain": "computational_science", "external_links": ["https://arxiv.org/pdf/quant-ph/9511042"], "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": "Peter", "question_author_url": "https://scicomp.stackexchange.com/users/46677/peter", "question_author_user_type": "registered", "question_created_at": "2025-10-19T14:49:08+00:00", "question_html": "I'm trying to code the path integral simulation described in this article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?
\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.
\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:
\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\nAs you can see the matrix elements match the propagator at first time step.
\nHere i my code written in C.
\n#include <stdio.h>\n#include <complex.h>\n#include <math.h>\nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n for (int i = 0; i < size; ++i) {\n for (int j = 0; j < size; ++j) {\n B[i][j] = 0.0+I*0.0;\n for (int k = 0; k < size; ++k) {\n B[i][j] += A[i][k]*A[k][j];\n }\n B[i][j] *= pow(dx,n+1);\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n complex A[size][size];\n complex B[size][size];\n double x_a = 0;\n double x_b = 0;\n for (int i = 0; i < size; ++i) {\n double xi = -xmax+i*dx;\n for (int j = 0; j < size; ++j) {\n double xj = -xmax+j*dx;\n A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n if (i == 0 && j == 6) {\n x_a = xi;\n x_b = xj;\n printf("x_a = %f, x_b = %f\\n",xi,xj);\n }\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n for (int n = 0; n < 4; ++n) {\n if (n % 2 == 0) {\n mult(A,B,x_a,x_b,n);\n }\n else {\n mult(B,A,x_a,x_b,n);\n }\n }\n}\n\n\n", "question_id": 45261, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I'm trying to code the path integral simulation described in this (https://arxiv.org/pdf/quant-ph/9511042) article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?\n\n\n\n\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.\n\n\n\n\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:\n\n\n\n\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\n\n\n\n\nAs you can see the matrix elements match the propagator at first time step.\n\n\n\n\nHere i my code written in C.\n\n\n\n\n#include The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n", "answer_id": 45312, "answer_text": "Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.", "answer_url": "https://scicomp.stackexchange.com/a/45312", "author": "Federico Poloni", "author_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-12-13T10:03:37+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": 45311, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-13T10:03:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFC0D245-EF3B-4C7B-9150-73518AFD2D2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-18T09:34:32+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "74B8DDDA-9B0B-40CA-BE67-18501D69153F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}], "score": 6, "updated_at": "2025-12-18T09:34:32+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45311, "sha256": "ad56fe2c0260b1f75acb06603952a687d5a2487cdcb7f14fa35ca2ddbe95dbe9", "source_url": "https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"}, {"block_index": 1, "code_text": "U_, s_, Vt_ = np.linalg.svd(A)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45311, "sha256": "c8237ba622cf113feb706a6dd46de44c41ac2edd5ac548cd0e9562bf82e74fa5", "source_url": "https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"}], "other_answers": [], "product": "code_qa", "question": "Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code\n\n\n\n\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\n\n\n\n\nI am validating my code with the svd method that comes with numpy\n\n\n\n\nU_, s_, Vt_ = np.linalg.svd(A)\n\n\n\n\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:\n\n\n\n\narray([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\n\n\n\n\nbut for U_ (numpy code) it gives\n\n\n\n\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\n\n\n\n\nthe second column of the U and U_ are not same. What did I wrong in my code?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45311", "selected_answer": {"answer_html": "The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n", "answer_id": 45312, "answer_text": "Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.", "answer_url": "https://scicomp.stackexchange.com/a/45312", "author": "Federico Poloni", "author_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-12-13T10:03:37+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": 45311, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-13T10:03:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFC0D245-EF3B-4C7B-9150-73518AFD2D2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-18T09:34:32+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "74B8DDDA-9B0B-40CA-BE67-18501D69153F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}], "score": 6, "updated_at": "2025-12-18T09:34:32+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45312, "answers": [{"answer_html": "The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n", "answer_id": 45312, "answer_text": "Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.", "answer_url": "https://scicomp.stackexchange.com/a/45312", "author": "Federico Poloni", "author_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-12-13T10:03:37+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": 45311, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-13T10:03:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFC0D245-EF3B-4C7B-9150-73518AFD2D2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-18T09:34:32+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "74B8DDDA-9B0B-40CA-BE67-18501D69153F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}], "score": 6, "updated_at": "2025-12-18T09:34:32+00:00"}], "domain": "computational_science", "external_links": [], "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": "Argha Nilanjon Nondi", "question_author_url": "https://scicomp.stackexchange.com/users/56165/argha-nilanjon-nondi", "question_author_user_type": "registered", "question_created_at": "2025-12-12T11:42:59+00:00", "question_html": "Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code
\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\nI am validating my code with the svd method that comes with numpy
\nU_, s_, Vt_ = np.linalg.svd(A)\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:
array([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\nbut for U_ (numpy code) it gives
\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\nthe second column of the U and U_ are not same. What did I wrong in my code?
The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n", "answer_id": 45327, "answer_text": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).", "answer_url": "https://scicomp.stackexchange.com/a/45327", "author": "Wolfgang Bangerth", "author_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-03T02:46:44+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Wolfgang Bangerth", "profile_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "user_type": "registered"}, "created_at": "2026-01-03T02:46:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-23T14:37:58+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "B49E063C-3F0D-471B-956C-B179F2F73567", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}], "score": 10, "updated_at": "2026-01-23T14:37:58+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "class PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "72f89f4e70a0d9ea27afa54ad378f9c4e2b0812f96becf4acbd8f7ebf0cc9b85", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 1, "code_text": "def df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "b2d3d4f6e01670c9cb767d689a925772aaee0c1b9223facf411446def617adca", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 2, "code_text": "class Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "1a915d175651e4b9f9655e9ec1c9264bc3f1f929f0579d7c759eeba08ce30194", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 3, "code_text": "def train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "c7d15b6e7e7d62ba263632f66347f76b266d871b1ee7544ec9e25530d170018b", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 4, "code_text": "def create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "9ad8906458885f3d360ec2d77e3f1ad1f6ff1f533262564103a2e6f6d9b8174e", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}], "other_answers": [{"answer_html": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.
\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).
\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.
\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.
\n", "answer_id": 45328, "answer_text": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.\n\n\n\n\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).\n\n\n\n\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.\n\n\n\n\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.", "answer_url": "https://scicomp.stackexchange.com/a/45328", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-05T07:08:57+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": 45326, "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": "2026-01-05T07:08:57+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "E5705B06-7DAC-4324-A752-C8064C49BB6C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}], "score": 3, "updated_at": "2026-01-05T07:08:57+00:00"}, {"answer_html": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.
\n", "answer_id": 45348, "answer_text": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.", "answer_url": "https://scicomp.stackexchange.com/a/45348", "author": "Donte Lightfoot", "author_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-22T23:46:46+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Donte Lightfoot", "profile_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "user_type": "registered"}, "created_at": "2026-01-22T23:46:46+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "790DF00C-3B67-42CD-A314-653CD46193C9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}], "score": 2, "updated_at": "2026-01-22T23:46:46+00:00"}], "product": "code_qa", "question": "I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.\n\n\n\n\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.\n\n\n\n\n[image: output GIF; source: https://i.sstatic.net/9QczcfVK.gif] (https://i.sstatic.net/9QczcfVK.gif)\n\n\n\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/IMsKTvWk.png] (https://i.sstatic.net/IMsKTvWk.png)\n\n\n\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$\n\n\n\n\nwhere:\n\n\n\n\n\n(c = 1)\n\n\n\n\n(f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence\n\n\n\n\n\nInitial conditions:\n\n\n\n\n\n(u(x,y,0) = 0)\n\n\n\n\n$\\partial_t u(x,y,0) = 0$\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nFirst-order absorbing (Sommerfeld):\n\n\n\n\n\n$\\partial_t u + c\\,\\partial_n u = 0$\n\n\n\n\n\nThe wavefronts don't make much sense\n\n\n\n\n\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\n\n\n\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\n\n\n\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\n\n\n\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\n\n\n\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\n\n\n\n\n\n\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer\n\n\n\n\n\n\n\n\n\nActivation: sin\n\n\n\n\n\n\n\n\n\nTraining:\n\n\n\n\n\nAdam optimizer (20k epochs)\n\n\n\n\nLBFGS refinement\n\n\n\n\n\n\n\n\n\n\nCollocation points:\n\n\n\n\n\nUniform tensor-product grid in (x, y, t)\n\n\n\n\n\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nImplemented via additional loss terms using autograd\n\n\n\n\n\n\n\n\n\n\nVisualization:\n\n\n\n\n\nPINN evaluated on a dense grid and animated with Matplotlib\n\n\n\n\n\n\n\n\n\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.\n\n\n\n\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45326", "selected_answer": {"answer_html": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n", "answer_id": 45327, "answer_text": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).", "answer_url": "https://scicomp.stackexchange.com/a/45327", "author": "Wolfgang Bangerth", "author_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-03T02:46:44+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Wolfgang Bangerth", "profile_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "user_type": "registered"}, "created_at": "2026-01-03T02:46:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-23T14:37:58+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "B49E063C-3F0D-471B-956C-B179F2F73567", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}], "score": 10, "updated_at": "2026-01-23T14:37:58+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45327, "answers": [{"answer_html": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n", "answer_id": 45327, "answer_text": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).", "answer_url": "https://scicomp.stackexchange.com/a/45327", "author": "Wolfgang Bangerth", "author_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-03T02:46:44+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Wolfgang Bangerth", "profile_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "user_type": "registered"}, "created_at": "2026-01-03T02:46:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-23T14:37:58+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "B49E063C-3F0D-471B-956C-B179F2F73567", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}], "score": 10, "updated_at": "2026-01-23T14:37:58+00:00"}, {"answer_html": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.
\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).
\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.
\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.
\n", "answer_id": 45328, "answer_text": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.\n\n\n\n\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).\n\n\n\n\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.\n\n\n\n\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.", "answer_url": "https://scicomp.stackexchange.com/a/45328", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-05T07:08:57+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": 45326, "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": "2026-01-05T07:08:57+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "E5705B06-7DAC-4324-A752-C8064C49BB6C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}], "score": 3, "updated_at": "2026-01-05T07:08:57+00:00"}, {"answer_html": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.
\n", "answer_id": 45348, "answer_text": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.", "answer_url": "https://scicomp.stackexchange.com/a/45348", "author": "Donte Lightfoot", "author_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-22T23:46:46+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Donte Lightfoot", "profile_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "user_type": "registered"}, "created_at": "2026-01-22T23:46:46+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "790DF00C-3B67-42CD-A314-653CD46193C9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}], "score": 2, "updated_at": "2026-01-22T23:46:46+00:00"}], "domain": "computational_science", "external_links": ["https://arxiv.org/abs/2407.07218", "https://i.sstatic.net/9QczcfVK.gif", "https://i.sstatic.net/IMsKTvWk.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": "Anwesh Saha", "question_author_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "question_author_user_type": "registered", "question_created_at": "2026-01-01T19:29:53+00:00", "question_html": "I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.
\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.
\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):
\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$
\nwhere:
\nInitial conditions:
\nBoundary conditions:
\n$\\partial_t u + c\\,\\partial_n u = 0$
\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer
\nActivation: sin
Training:
\nCollocation points:
\nBoundary conditions:
\nVisualization:
\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.
\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.
\n", "question_id": 45326, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.\n\n\n\n\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.\n\n\n\n\n[image: output GIF; source: https://i.sstatic.net/9QczcfVK.gif] (https://i.sstatic.net/9QczcfVK.gif)\n\n\n\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/IMsKTvWk.png] (https://i.sstatic.net/IMsKTvWk.png)\n\n\n\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$\n\n\n\n\nwhere:\n\n\n\n\n\n(c = 1)\n\n\n\n\n(f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence\n\n\n\n\n\nInitial conditions:\n\n\n\n\n\n(u(x,y,0) = 0)\n\n\n\n\n$\\partial_t u(x,y,0) = 0$\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nFirst-order absorbing (Sommerfeld):\n\n\n\n\n\n$\\partial_t u + c\\,\\partial_n u = 0$\n\n\n\n\n\nThe wavefronts don't make much sense\n\n\n\n\n\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\n\n\n\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\n\n\n\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\n\n\n\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\n\n\n\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\n\n\n\n\n\n\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer\n\n\n\n\n\n\n\n\n\nActivation: sin\n\n\n\n\n\n\n\n\n\nTraining:\n\n\n\n\n\nAdam optimizer (20k epochs)\n\n\n\n\nLBFGS refinement\n\n\n\n\n\n\n\n\n\n\nCollocation points:\n\n\n\n\n\nUniform tensor-product grid in (x, y, t)\n\n\n\n\n\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nImplemented via additional loss terms using autograd\n\n\n\n\n\n\n\n\n\n\nVisualization:\n\n\n\n\n\nPINN evaluated on a dense grid and animated with Matplotlib\n\n\n\n\n\n\n\n\n\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.\n\n\n\n\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anwesh Saha", "profile_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "user_type": "registered"}, "created_at": "2026-01-01T19:29:53+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "48F1548B-237A-4E64-9D2B-23708297897F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/48F1548B-237A-4E64-9D2B-23708297897F/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-02T05:44:50+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "F9E6ED4E-E272-4959-AB38-6016CEED48E6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/F9E6ED4E-E272-4959-AB38-6016CEED48E6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anwesh Saha", "profile_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "user_type": "registered"}, "created_at": "2026-01-02T05:49:23+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "D31A0254-33EE-4DC9-BC16-D05905CA3663", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D31A0254-33EE-4DC9-BC16-D05905CA3663/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anwesh Saha", "profile_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "user_type": "registered"}, "created_at": "2026-01-02T06:00:26+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "C90C675C-FD01-4F7F-8343-47D3A101E2AF", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C90C675C-FD01-4F7F-8343-47D3A101E2AF/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-01-03T11:41:26+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "C6534CC8-3DAF-4FF7-918C-DDE4C08B9232", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/C6534CC8-3DAF-4FF7-918C-DDE4C08B9232/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis", "split": "train", "split_group": "45c7425e154db27f580935b67401becade107a292d53c7f95ef776a2eb87be1b", "tags": ["fluid-dynamics", "computational-physics", "machine-learning", "physics-informed-neural-networks"], "thread_id": "scicomp:45326", "title": "Physics-Informed Neural Network for 2D Wave Equation Produces Non-Circular / Distorted Wavefronts"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45335, "sha256": "57aac7578bb6f741268023073e8caf04782e2d1a8ebdc92d20507478f02d64b4", "source_url": "https://scicomp.stackexchange.com/a/45335"}, {"block_index": 0, "code_text": "function [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45337, "sha256": "535fd63b99697fb569289a64746583e07c5d7d903898e20406ca04bde8aa5841", "source_url": "https://scicomp.stackexchange.com/a/45337"}], "other_answers": [{"answer_html": "I managed to create a prototype solver based on ADMM in MATLAB:
\nfunction [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %<! Optimization variable\nvS = zeros(numInEq, 1); %<! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %<! Preious iteration buffer\nvMu = zeros(numInEq, 1); %<! Dual variable for inequality\nvNu = zeros(numEq, 1); %<! Dual variabe for equality\n\n% Factorize the KKT System\n% (Q + rho * A' * A + rho * E' * E) * z = r\nmK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\nsK = decomposition(mK, 'chol', 'CheckCondition', false);\n\nisConv = false;\nupdatedRho = false;\n\nfor ii = 1:numIter\n vS1(:) = vS; %<! Previous iteration\n\n % Solve the Linear System\n vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %<! Right hand vector\n vX = sK \\ vR;\n\n % Proximal / Projection Step\n % s = -A * z with s >= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.
\nI will add mathematical formulation and a memory optimized version using Julia.
On MATLAB with this naive code I could beat quadprog() by 30% with the same output:
I produced an ADMM based solver which I found very efficient.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.
\nThe equality constraints can be turned into matrix form and the problem becomes:
$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe equality constraints are introduced by the Augmented Lagrangian:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe stopping condition is when both residuals are below a threshold:
\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.
\nI also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.
\nI implemented all in Julia and compared to the ECOS / SCS solvers wrapped by Convex.jl.
Run Times:
\nBenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n\nBenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n\nBenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n\nThe ADMM method is an order of magnitude faster than the generic solvers.
\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.
The code is available on my StackExchange Code GitHub Repository (Look at the ComputationalScience\\Q45334 folder).
Another formulation take advantage of the equality constraint to make the problem formulation smaller.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:
\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$
\nThen the above can be formulated as:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.
\nThis formulation reduces the number of constraints to handle.
\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.
The Augmented Lagrangian (Scaled form) is given by:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe rest is similar to above with the needed adjustments for the residuals calculations.
\nThis implementation reduced another 40 [Micro Sec] of the run time.
\n", "answer_id": 45342, "answer_text": "Another formulation take advantage of the equality constraint to make the problem formulation smaller.\n\n\n\n\nThe problem is given by:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:\n\n\n\n\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$\n\n\n\n\nThen the above can be formulated as:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.\n\n\n\n\nThis formulation reduces the number of constraints to handle.\n\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.\n\n\n\n\nThe Augmented Lagrangian (Scaled form) is given by:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.\n\n\n\n\n\nThe rest is similar to above with the needed adjustments for the residuals calculations.\n\n\n\n\nThis implementation reduced another 40 [Micro Sec] of the run time.", "answer_url": "https://scicomp.stackexchange.com/a/45342", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-17T12:18:23+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": 45334, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-17T12:18:23+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}], "score": 1, "updated_at": "2026-01-17T12:18:23+00:00"}], "product": "code_qa", "question": "Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.\n\n\n\n\nI want to smooth the curve with the following properties:\n\n\n\n\n\nThe result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.\n\n\n\n\nFor a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.\n\n\n\n\nThe smoothed values between 2 reference points must be monotonic.\n\n\n\n\n\nI came up with the following model:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.\n\n\n\n\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.\n\n\n\n\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45334", "selected_answer": {"answer_html": "\n\nmonothonic
\n
I'm sure you meant monotonic.
\n\n\nI am looking for a fast way to solve the problem
\n
Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:
\nA traditional LP would express the problem thus. Define the following decision vectors:
\nFind
\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$
\ngiven the following constraints:
\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$
\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$
\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.
\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\nHere we see that the solution does exactly what we tell it to:
\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:
\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):
\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.
\n", "answer_id": 45335, "answer_text": "monothonic\n\n\n\n\n\n\n\nI'm sure you meant monotonic.\n\n\n\n\n\n\n\nI am looking for a fast way to solve the problem\n\n\n\n\n\n\n\nAre you actually? I think if you were, you would use something off-the-shelf. \"Simple iterative\" and \"fast\" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:\n\n\n\n\n\nLinear, not quadratic\n\n\n\n\nNo manual iteration per se\n\n\n\n\nEnforce inter-reference monotonicity through simple linear constraints\n\n\n\n\nModel cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight\n\n\n\n\n\nA traditional LP would express the problem thus. Define the following decision vectors:\n\n\n\n\n\n$z \\in \\mathbb R^n$, the fit points\n\n\n\n\n$z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error\n\n\n\n\n$z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error\n\n\n\n\n$d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials\n\n\n\n\n$d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials\n\n\n\n\n\nFind\n\n\n\n\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$\n\n\n\n\ngiven the following constraints:\n\n\n\n\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$\n\n\n\n\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$\n\n\n\n\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\nHere we see that the solution does exactly what we tell it to:\n\n\n\n\n[image: example solution; source: https://i.sstatic.net/oTyX0oWA.png] (https://i.sstatic.net/oTyX0oWA.png)\n\n\n\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:\n\n\n\n\n[image: smoothing; source: https://i.sstatic.net/cW1t1avg.png] (https://i.sstatic.net/cW1t1avg.png)\n\n\n\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):\n\n\n\n\n[image: sparsity; source: https://i.sstatic.net/UmVF5qyE.png] (https://i.sstatic.net/UmVF5qyE.png)\n\n\n\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.", "answer_url": "https://scicomp.stackexchange.com/a/45335", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-10T07:56:42+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": 45334, "revision_attribution": [{"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-10T07:56:42+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "49224026-A98C-4DFC-B187-28324764F758", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/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-10T15:16:37+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "0462867C-327F-469E-957B-1FE451F4CE5C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/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-10T20:00:35+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "302EF20B-4729-4185-A059-5377ED4B7555", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}], "score": 3, "updated_at": "2026-01-10T20:00:35+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "\n\nmonothonic
\n
I'm sure you meant monotonic.
\n\n\nI am looking for a fast way to solve the problem
\n
Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:
\nA traditional LP would express the problem thus. Define the following decision vectors:
\nFind
\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$
\ngiven the following constraints:
\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$
\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$
\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.
\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\nHere we see that the solution does exactly what we tell it to:
\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:
\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):
\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.
\n", "answer_id": 45335, "answer_text": "monothonic\n\n\n\n\n\n\n\nI'm sure you meant monotonic.\n\n\n\n\n\n\n\nI am looking for a fast way to solve the problem\n\n\n\n\n\n\n\nAre you actually? I think if you were, you would use something off-the-shelf. \"Simple iterative\" and \"fast\" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:\n\n\n\n\n\nLinear, not quadratic\n\n\n\n\nNo manual iteration per se\n\n\n\n\nEnforce inter-reference monotonicity through simple linear constraints\n\n\n\n\nModel cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight\n\n\n\n\n\nA traditional LP would express the problem thus. Define the following decision vectors:\n\n\n\n\n\n$z \\in \\mathbb R^n$, the fit points\n\n\n\n\n$z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error\n\n\n\n\n$z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error\n\n\n\n\n$d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials\n\n\n\n\n$d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials\n\n\n\n\n\nFind\n\n\n\n\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$\n\n\n\n\ngiven the following constraints:\n\n\n\n\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$\n\n\n\n\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$\n\n\n\n\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\nHere we see that the solution does exactly what we tell it to:\n\n\n\n\n[image: example solution; source: https://i.sstatic.net/oTyX0oWA.png] (https://i.sstatic.net/oTyX0oWA.png)\n\n\n\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:\n\n\n\n\n[image: smoothing; source: https://i.sstatic.net/cW1t1avg.png] (https://i.sstatic.net/cW1t1avg.png)\n\n\n\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):\n\n\n\n\n[image: sparsity; source: https://i.sstatic.net/UmVF5qyE.png] (https://i.sstatic.net/UmVF5qyE.png)\n\n\n\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.", "answer_url": "https://scicomp.stackexchange.com/a/45335", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-10T07:56:42+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": 45334, "revision_attribution": [{"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-10T07:56:42+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "49224026-A98C-4DFC-B187-28324764F758", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/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-10T15:16:37+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "0462867C-327F-469E-957B-1FE451F4CE5C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/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-10T20:00:35+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "302EF20B-4729-4185-A059-5377ED4B7555", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}], "score": 3, "updated_at": "2026-01-10T20:00:35+00:00"}, {"answer_html": "I managed to create a prototype solver based on ADMM in MATLAB:
\nfunction [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %<! Optimization variable\nvS = zeros(numInEq, 1); %<! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %<! Preious iteration buffer\nvMu = zeros(numInEq, 1); %<! Dual variable for inequality\nvNu = zeros(numEq, 1); %<! Dual variabe for equality\n\n% Factorize the KKT System\n% (Q + rho * A' * A + rho * E' * E) * z = r\nmK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\nsK = decomposition(mK, 'chol', 'CheckCondition', false);\n\nisConv = false;\nupdatedRho = false;\n\nfor ii = 1:numIter\n vS1(:) = vS; %<! Previous iteration\n\n % Solve the Linear System\n vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %<! Right hand vector\n vX = sK \\ vR;\n\n % Proximal / Projection Step\n % s = -A * z with s >= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.
\nI will add mathematical formulation and a memory optimized version using Julia.
On MATLAB with this naive code I could beat quadprog() by 30% with the same output:
I produced an ADMM based solver which I found very efficient.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.
\nThe equality constraints can be turned into matrix form and the problem becomes:
$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe equality constraints are introduced by the Augmented Lagrangian:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe stopping condition is when both residuals are below a threshold:
\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.
\nI also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.
\nI implemented all in Julia and compared to the ECOS / SCS solvers wrapped by Convex.jl.
Run Times:
\nBenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n\nBenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n\nBenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n\nThe ADMM method is an order of magnitude faster than the generic solvers.
\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.
The code is available on my StackExchange Code GitHub Repository (Look at the ComputationalScience\\Q45334 folder).
Another formulation take advantage of the equality constraint to make the problem formulation smaller.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:
\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$
\nThen the above can be formulated as:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.
\nThis formulation reduces the number of constraints to handle.
\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.
The Augmented Lagrangian (Scaled form) is given by:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe rest is similar to above with the needed adjustments for the residuals calculations.
\nThis implementation reduced another 40 [Micro Sec] of the run time.
\n", "answer_id": 45342, "answer_text": "Another formulation take advantage of the equality constraint to make the problem formulation smaller.\n\n\n\n\nThe problem is given by:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:\n\n\n\n\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$\n\n\n\n\nThen the above can be formulated as:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.\n\n\n\n\nThis formulation reduces the number of constraints to handle.\n\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.\n\n\n\n\nThe Augmented Lagrangian (Scaled form) is given by:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.\n\n\n\n\n\nThe rest is similar to above with the needed adjustments for the residuals calculations.\n\n\n\n\nThis implementation reduced another 40 [Micro Sec] of the run time.", "answer_url": "https://scicomp.stackexchange.com/a/45342", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-17T12:18:23+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": 45334, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-17T12:18:23+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}], "score": 1, "updated_at": "2026-01-17T12:18:23+00:00"}], "domain": "computational_science", "external_links": ["https://github.com/RoyiAvital/StackExchangeCodes", "https://github.com/cvxgrp/scs", "https://github.com/embotech/ecos", "https://github.com/jump-dev/Convex.jl", "https://i.sstatic.net/UmVF5qyE.png", "https://i.sstatic.net/VC8uzUSt.png", "https://i.sstatic.net/cW1t1avg.png", "https://i.sstatic.net/f5YcjFm6.png", "https://i.sstatic.net/oTyX0oWA.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": "Royi", "question_author_url": "https://scicomp.stackexchange.com/users/7951/royi", "question_author_user_type": "registered", "question_created_at": "2026-01-09T11:12:06+00:00", "question_html": "Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.
\nI want to smooth the curve with the following properties:
\nI came up with the following model:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.
\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.
\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.
\n", "question_id": 45334, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.\n\n\n\n\nI want to smooth the curve with the following properties:\n\n\n\n\n\nThe result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.\n\n\n\n\nFor a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.\n\n\n\n\nThe smoothed values between 2 reference points must be monotonic.\n\n\n\n\n\nI came up with the following model:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.\n\n\n\n\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.\n\n\n\n\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-09T11:12:06+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "47824E2B-27A9-4037-A643-E3F6522A8C95", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/47824E2B-27A9-4037-A643-E3F6522A8C95/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-09T11:26:36+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2026-01-10T07:58:10+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "2599F6AB-3F4E-455C-9665-0A36994C9F01", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2599F6AB-3F4E-455C-9665-0A36994C9F01/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-01-10T17:02:45+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "DE676BCF-D21E-4A19-B947-DB9D0FD71DA6", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/DE676BCF-D21E-4A19-B947-DB9D0FD71DA6/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con", "split": "train", "split_group": "f136ae78b6249a1eba9450dcaebaadcc09a41c6eb57a74d9f7e7aba798cd242d", "tags": ["linear-algebra", "optimization", "constrained-optimization", "convex-optimization", "curve-fitting"], "thread_id": "scicomp:45334", "title": "Solving Regularized Least Squares with Linear Equality and Linear Inequality Constraints for Curve Smoothing"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45394, "sha256": "3ba14f7d8ca6fcf552a8429426a59372f6c08c1fad801078f723f57a680abda3", "source_url": "https://scicomp.stackexchange.com/a/45394"}], "other_answers": [], "product": "code_qa", "question": "I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.\n\n\n\n\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.\n\n\n\n\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45362", "selected_answer": {"answer_html": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)
\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}
\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.
\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}
\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.
\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:
\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f"Numerical Result: {result:.10f}")\n# Result from WolframAlpha = 0.0187983\n\n", "answer_id": 45394, "answer_text": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983", "answer_url": "https://scicomp.stackexchange.com/a/45394", "author": "mle", "author_url": "https://scicomp.stackexchange.com/users/46538/mle", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-03-04T18:29:45+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": 45362, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mle", "profile_url": "https://scicomp.stackexchange.com/users/46538/mle", "user_type": "registered"}, "created_at": "2026-03-04T18:29:45+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "D8A9E199-F055-462B-8A0D-91FD9CE698F5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}], "score": 2, "updated_at": "2026-03-04T18:29:45+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)
\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}
\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.
\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}
\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.
\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:
\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f"Numerical Result: {result:.10f}")\n# Result from WolframAlpha = 0.0187983\n\n", "answer_id": 45394, "answer_text": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983", "answer_url": "https://scicomp.stackexchange.com/a/45394", "author": "mle", "author_url": "https://scicomp.stackexchange.com/users/46538/mle", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-03-04T18:29:45+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": 45362, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mle", "profile_url": "https://scicomp.stackexchange.com/users/46538/mle", "user_type": "registered"}, "created_at": "2026-03-04T18:29:45+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "D8A9E199-F055-462B-8A0D-91FD9CE698F5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}], "score": 2, "updated_at": "2026-03-04T18:29:45+00:00"}], "domain": "computational_science", "external_links": [], "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": "vibe", "question_author_url": "https://scicomp.stackexchange.com/users/28440/vibe", "question_author_user_type": "registered", "question_created_at": "2026-02-04T15:10:39+00:00", "question_html": "I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.
\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.
\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.
\n", "question_id": 45362, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.\n\n\n\n\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.\n\n\n\n\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vibe", "profile_url": "https://scicomp.stackexchange.com/users/28440/vibe", "user_type": "registered"}, "created_at": "2026-02-04T15:10:39+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9B775FCA-6689-4886-BE87-22C985705EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9B775FCA-6689-4886-BE87-22C985705EFF/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials", "split": "train", "split_group": "559c940425b563972be618e91f2ad04e0e7f4e9954fff19ed9350b4bea807ada", "tags": ["integration", "quadrature", "polynomials"], "thread_id": "scicomp:45362", "title": "Quadrature rule for ratio of polynomials"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": " // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "d81fd16ae667dfb8efe92a3dda8a25f1a01e7ae62e280e6f57c915faf6a9265d", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 1, "code_text": "// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "0ff70c4acae7ce49e4ba6a456dcfb50acf9848af56d6d6cfd2ba003acc2b42c0", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 2, "code_text": "// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "287d4fd2bd10409c0afec92b345d9927a085e1409a4d4e69e112658316bd1de1", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 3, "code_text": "// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "c8ee4a8e2f292c4de523aa887dc5d69dcc882f56e8ce9a348ee5fe51ca071886", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 4, "code_text": " // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "9fe12fd49b69dcf79f44653d42997784ead03639737baf06c0857f5384c12f14", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 5, "code_text": "#includeit seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature fields will look different than what you have shown in the picture. For clarity, can you check the following steps 1) Simulate a moving cavity lid at different Re numbers and compare against standard literature (like Ghia et.al (1982)). This freezes multiple things like verification of upwind schemes etc. 2) Recheck the enthalpy/heat equation whether the convection terms are taken care properly. For reference, typically over time, it should develop into convection cells. Please find my simulations for omega-psi attached in below picture
it seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature fields will look different than what you have shown in the picture. For clarity, can you check the following steps 1) Simulate a moving cavity lid at different Re numbers and compare against standard literature (like Ghia et.al (1982)). This freezes multiple things like verification of upwind schemes etc. 2) Recheck the enthalpy/heat equation whether the convection terms are taken care properly. For reference, typically over time, it should develop into convection cells. Please find my simulations for omega-psi attached in below picture
Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:
\n\n\n$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\\ldots$1e7.\nLeft and right walls are insulated. At the bottom wall $q_1= 1000$ and at\nthe upper wall $q_2=0.5*q_1$
\n
The temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.
\nThe isotherms are straight horizontal lines. It looks like the heat conduction of a block of copper when one of the wall has higher constant temperature
\nMay be a problem when defining the heat flux in solveTemperature function. Shouldnt the isotherms be waivier? The walls are nonpermeable (no liquid passes trouht them).
I tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n
Here is the piece of code for calculating the temperatures
\n // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n\nVortex solver
\n// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n\nStream function solver
\n// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n\nVelocity calculator
\n// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n\nSetting boundary conditions
\n // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n\nThis is the main code
\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\nconstexpr int Nx = 180;\nconstexpr int Ny = 60;\n\n int main()\n {\n const double Lx = 1.5, Ly = 1.0;\n const double hx = Lx / Nx, hy = Ly / Ny;\n const double Pr = 0.7, Ra = 1e8, dt = 0.001;\n const double eps = 1e-6, relax = 1.0;\n \n double t = 0.0, t_k = 10.0;\n \n static double psi[Nx + 1][Ny + 1]{}, psik[Nx + 1][Ny + 1]{}, omega[Nx + 1][Ny + 1]{};\n static double theta[Nx + 1][Ny + 1]{}, u[Nx + 1][Ny + 1]{}, v[Nx + 1][Ny + 1]{};\n static double alpha[(Nx > Ny ? Nx : Ny) + 1]{}, beta[(Nx > Ny ? Nx : Ny) + 1]{}; // if Nx > Ny then take Nx\n // otherwise take Ny\n \n while (t < t_k)\n {\n applyPsiBC(psi);\n solvePsi(psi, psik, omega, hx, hy, relax, eps);\n computeVelocity(psi, u, v, hx, hy);\n solveOmegaX(psi, theta, u, omega, alpha, beta, hx, dt, Pr, Ra);\n solveOmegaY(psi, v, omega, alpha, beta, hy, dt, Pr, Ra);\n solveTemperature(theta, u, v, alpha, beta, hx, hy, dt, Pr, Ra);\n \n t += dt;\n cout << t << endl;\n }\n \n // OUTPUT to files\n ofstream fpsi("psitest.txt"), fomega("omegatest.txt"), ftheta("thetatest.txt");\n \n for (int i = 0; i <= Nx; i++)\n {\n for (int j = 0; j <= Ny; j++)\n {\n double x = i * hx;\n double y = j * hy;\n fomega << x << " " << y << " " << omega[i][j] << "\\n";\n ftheta << x << " " << y << " " << theta[i][j] << "\\n";\n fpsi << x << " " << y << " " << psi[i][j] << "\\n";\n }\n }\n \n cout << "Calculation completed. Files: psitest.txt, omegatest.txt, thetatest.txt\\n";\n return 0;\n }\n\n", "question_id": 45377, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:\n\n\n\n\n\n\n\n$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\\ldots$1e7.\nLeft and right walls are insulated. At the bottom wall $q_1= 1000$ and at\nthe upper wall $q_2=0.5*q_1$\n\n\n\n\n\n\n\nThe temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.\n\n\n\n\nThe isotherms are straight horizontal lines. It looks like the heat conduction of a block of copper when one of the wall has higher constant temperature\n\n\n\n\nMay be a problem when defining the heat flux in solveTemperature function. Shouldnt the isotherms be waivier? The walls are nonpermeable (no liquid passes trouht them).\n\n\n\n\nI tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n[image: for Ra = 1e3; source: https://i.sstatic.net/Z4fMSBrm.png] (https://i.sstatic.net/Z4fMSBrm.png)\n\n\n\n\nThis image is for Ra = 1e7\n[image: for Ra = 1e7; source: https://i.sstatic.net/4a2ls0zL.png] (https://i.sstatic.net/4a2ls0zL.png)\n\n\n\n\nHere is the piece of code for calculating the temperatures\n\n\n\n\n // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n\n\n\n\n\nVortex solver\n\n\n\n\n// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n\n\n\n\n\nStream function solver\n\n\n\n\n// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n\n\n\n\n\nVelocity calculator\n\n\n\n\n// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n\n\n\n\n\nSetting boundary conditions\n\n\n\n\n // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n\n\n\n\n\nThis is the main code\n\n\n\n\n#include Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n", "answer_id": 45388, "answer_text": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.", "answer_url": "https://scicomp.stackexchange.com/a/45388", "author": "wim", "author_url": "https://scicomp.stackexchange.com/users/5286/wim", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-02-27T09:44:31+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": 45387, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-27T09:44:31+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "42AA8384-A67D-4B93-8A67-6F2708905EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-28T23:54:12+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "3E89E9AE-7857-41C4-8456-59AB2D1A01FD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-02T09:09:00+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "98F99AB1-1D15-4C9A-942A-7E8E8455BA0F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}], "score": 7, "updated_at": "2026-03-02T09:09:00+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "function [x, y] = ThreeProduct(a, b, c)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45387, "sha256": "bd4356e06b4e83b3708b56f9d06ac35cfeedc70c4f5106650611050aae8f90f8", "source_url": "https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers"}, {"block_index": 1, "code_text": "function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45387, "sha256": "80ed3e97e5f90454b0f805d53e1135475404e4eec18ee94dae66478e44276393", "source_url": "https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers"}], "other_answers": [], "product": "code_qa", "question": "TL;DR: I am looking for a function that computes the product of three floating point numbers:\n\n\n\n\nfunction [x, y] = ThreeProduct(a, b, c)\n\n\n\n\n\nSuch that:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\n\n\n\nBackground\n\n\n\n\nOgita et al. (2005) introduced a method of computing a dot product based on \"Error Free Transformation\" primitives, such as TwoSum() (due to Knuth) and TwoProduct():\n\n\n\n\nfunction [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\n\n\n\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name \"Error Free Transformation\". That is, for TwoSum():\n\n\n\n\n$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$\n\n\n\n\nAnd for TwoProduct():\n\n\n\n\n$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$\n\n\n\n\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.\n\n\n\n\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.\n\n\n\n\nMy question is whether there is a known algorithm for the product of three floating point numbers (\"ThreeProduct()\"). That is, something where the following holds:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.\n\n\n\n\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.\n\n\n\n\n\n\n\nReferences:\n\n\n\n\nOgita, T. et al., \"Accurate Sum and Dot Product\", SIAM Journal of Scientific Computing, 2005.\n\n\n\n\nGraillat, S. \"Accurate Floating Point Product and Exponentiation (https://hal.science/hal-00164607v1)\". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45387", "selected_answer": {"answer_html": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n", "answer_id": 45388, "answer_text": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.", "answer_url": "https://scicomp.stackexchange.com/a/45388", "author": "wim", "author_url": "https://scicomp.stackexchange.com/users/5286/wim", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-02-27T09:44:31+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": 45387, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-27T09:44:31+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "42AA8384-A67D-4B93-8A67-6F2708905EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-28T23:54:12+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "3E89E9AE-7857-41C4-8456-59AB2D1A01FD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-02T09:09:00+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "98F99AB1-1D15-4C9A-942A-7E8E8455BA0F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}], "score": 7, "updated_at": "2026-03-02T09:09:00+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45388, "answers": [{"answer_html": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n", "answer_id": 45388, "answer_text": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.", "answer_url": "https://scicomp.stackexchange.com/a/45388", "author": "wim", "author_url": "https://scicomp.stackexchange.com/users/5286/wim", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-02-27T09:44:31+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": 45387, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-27T09:44:31+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "42AA8384-A67D-4B93-8A67-6F2708905EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-28T23:54:12+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "3E89E9AE-7857-41C4-8456-59AB2D1A01FD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-02T09:09:00+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "98F99AB1-1D15-4C9A-942A-7E8E8455BA0F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}], "score": 7, "updated_at": "2026-03-02T09:09:00+00:00"}], "domain": "computational_science", "external_links": ["https://hal.science/hal-00164607v1", "https://ieeexplore.ieee.org/document/4358278"], "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": "Damien", "question_author_url": "https://scicomp.stackexchange.com/users/761/damien", "question_author_user_type": "registered", "question_created_at": "2026-02-27T05:27:22+00:00", "question_html": "TL;DR: I am looking for a function that computes the product of three floating point numbers:
\nfunction [x, y] = ThreeProduct(a, b, c)\n\nSuch that:
\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nBackground
\nOgita et al. (2005) introduced a method of computing a dot product based on "Error Free Transformation" primitives, such as TwoSum() (due to Knuth) and TwoProduct():
function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name "Error Free Transformation". That is, for TwoSum():
$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$
\nAnd for TwoProduct():
$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$
\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.
\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.
\nMy question is whether there is a known algorithm for the product of three floating point numbers ("ThreeProduct()"). That is, something where the following holds:
$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.
\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.
References:
\nOgita, T. et al., "Accurate Sum and Dot Product", SIAM Journal of Scientific Computing, 2005.
\nGraillat, S. "Accurate Floating Point Product and Exponentiation". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.
\n", "question_id": 45387, "question_license": "CC BY-SA 4.0", "question_score": 10, "question_text": "TL;DR: I am looking for a function that computes the product of three floating point numbers:\n\n\n\n\nfunction [x, y] = ThreeProduct(a, b, c)\n\n\n\n\n\nSuch that:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\n\n\n\nBackground\n\n\n\n\nOgita et al. (2005) introduced a method of computing a dot product based on \"Error Free Transformation\" primitives, such as TwoSum() (due to Knuth) and TwoProduct():\n\n\n\n\nfunction [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\n\n\n\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name \"Error Free Transformation\". That is, for TwoSum():\n\n\n\n\n$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$\n\n\n\n\nAnd for TwoProduct():\n\n\n\n\n$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$\n\n\n\n\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.\n\n\n\n\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.\n\n\n\n\nMy question is whether there is a known algorithm for the product of three floating point numbers (\"ThreeProduct()\"). That is, something where the following holds:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.\n\n\n\n\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.\n\n\n\n\n\n\n\nReferences:\n\n\n\n\nOgita, T. et al., \"Accurate Sum and Dot Product\", SIAM Journal of Scientific Computing, 2005.\n\n\n\n\nGraillat, S. \"Accurate Floating Point Product and Exponentiation (https://hal.science/hal-00164607v1)\". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-02-27T05:27:22+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "652E8057-1F40-4128-9B15-6014E7677D14", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/652E8057-1F40-4128-9B15-6014E7677D14/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-02-27T06:42:56+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "59EECD04-2DAA-4DFE-BCE0-7030495A97DF", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/59EECD04-2DAA-4DFE-BCE0-7030495A97DF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-01T22:07:55+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "E19820FB-0C5D-448A-8B7D-D7FDF8F66E81", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E19820FB-0C5D-448A-8B7D-D7FDF8F66E81/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-01T22:16:04+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "D963AE6C-EC36-4A5E-8DC4-93C74CE72E7B", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D963AE6C-EC36-4A5E-8DC4-93C74CE72E7B/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers", "split": "train", "split_group": "ccbf1a2018830746c8a5890b1f9c9d0e315a7b4d5a58beb262b81c93f94c5380", "tags": ["floating-point"], "thread_id": "scicomp:45387", "title": "\"Error Free Transformation\" for the product of three floating point numbers"}} {"accepted_answer": {"answer_html": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n", "answer_id": 45440, "answer_text": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.", "answer_url": "https://scicomp.stackexchange.com/a/45440", "author": "FilmCoder", "author_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-05-05T05:53:32+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45396, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "FilmCoder", "profile_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "user_type": "registered"}, "created_at": "2026-05-05T05:53:32+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "C39D8103-AD54-44E2-90A3-4461BB25C47E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}], "score": 3, "updated_at": "2026-05-05T05:53:32+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "let quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &NodeMakogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n", "answer_id": 45440, "answer_text": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.", "answer_url": "https://scicomp.stackexchange.com/a/45440", "author": "FilmCoder", "author_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-05-05T05:53:32+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45396, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "FilmCoder", "profile_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "user_type": "registered"}, "created_at": "2026-05-05T05:53:32+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "C39D8103-AD54-44E2-90A3-4461BB25C47E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}], "score": 3, "updated_at": "2026-05-05T05:53:32+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45440, "answers": [{"answer_html": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n", "answer_id": 45440, "answer_text": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.", "answer_url": "https://scicomp.stackexchange.com/a/45440", "author": "FilmCoder", "author_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-05-05T05:53:32+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45396, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "FilmCoder", "profile_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "user_type": "registered"}, "created_at": "2026-05-05T05:53:32+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "C39D8103-AD54-44E2-90A3-4461BB25C47E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}], "score": 3, "updated_at": "2026-05-05T05:53:32+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/4aqhk3tL.png", "https://i.sstatic.net/K6cTCsGy.png", "https://i.sstatic.net/mLTa1ZsD.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": "Makogan", "question_author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "question_author_user_type": "registered", "question_created_at": "2026-03-05T07:11:11+00:00", "question_html": "I have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):
\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.
\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.
\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:
\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.
\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:
\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.
\nI am going to describe the logic in a high level:
\nThe actual code is this:
\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node<HpNode<f32, 10>>| {\n // Legendre coefficients.\n let cfs = node.data.coeffs(); \n let coeff_count = node.data.coeff_count();\n\n let pos = box_position + box_dims / 2.;\n let p = (cam_pos - pos) / box_dims;\n let v = ray / box_dims;\n\n let mut a = 0.;\n let mut b = 0.;\n let mut c = 0.;\n // Shift and scale the ray and pos to the local node.\n let ray = v;\n let ray_pos = p;\n for i in 0..coeff_count\n {\n // Coefficient + the degree of each legendre polynomial that was\n // tensor producted to make the basis element, i.e. one of\n // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n let (s, powers) = cfs[i as usize];\n // Compute coefficients for each dimension's Legendre polynomial\n // restricted to line.\n let mut poly = [1., 0., 0.];\n // accumulates as [t^0, t^1, t^2] coefficients.\n\n for axis in 0..3\n {\n // Get teh axial coefficients of this ray\n let (v, p) = match axis\n {\n 0 => (ray.x, ray_pos.x),\n 1 => (ray.y, ray_pos.y),\n 2 => (ray.z, ray_pos.z),\n _ => unreachable!(),\n };\n\n let power = powers[axis];\n\n // Legendre polynomial P_n(vt + p) coefficients in t.\n let leg_coeffs = match power\n {\n 0 => [1., 0., 0.],\n 1 => [p, v, 0.],\n // coefficients of the legendre polynomial of degree 2\n 2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n _ => unreachable!(),\n };\n\n // Multiply poly *= leg_coeffs.\n let temp = [\n poly[0] * leg_coeffs[0],\n poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n poly[0] * leg_coeffs[2]\n + poly[1] * leg_coeffs[1]\n + poly[2] * leg_coeffs[0],\n ];\n poly = temp;\n }\n\n a += s * poly[2];\n b += s * poly[1];\n c += s * poly[0];\n }\n\n let disc = b * b - 4. * a * c;\n if disc < 0.\n {\n return f32::INFINITY;\n }\n\n let sqrt_disc = disc.sqrt();\n let inv_2a = 1. / (2. * a);\n\n // Quadratic solutions.\n let x1 = (-b - sqrt_disc) * inv_2a;\n let x2 = (-b + sqrt_disc) * inv_2a;\n\n // Branchless valid selection: if x < 0, replace with infinity.\n let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n // Take minimum of valid solutions.\n let quad_t = valid_x1.min(valid_x2);\n\n // Handle linear case.\n let is_linear = a.abs() < 0.0001;\n let linear_t = -c / b;\n\n let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n if is_linear { linear_t } else { quad_t }\n };\n\nTo add further context, to generate the image with the additional spheres all you need to do is hard code the coefficients for a sphere:
\n let cfs = [\n (-0.1 + 1., [0, 0, 0]),\n (2./3., [2, 0, 0]),\n (2./3., [0, 2, 0]),\n (2./3., [0, 0, 2]),\n ];\n let coeff_count = 4;\n\nTo override the ones coming in. But the input coefficients cannot eb wrong because then the first image would not work.
\nThere's something wrong with the way I am computing my ray quadric collisions that is specific to the Legendre case. When I modify my logic to work with the sphere quadrics it works, as shown, so I must have messed something up with when computing the coefficients, but when I see the written code I fail to see what.
\n", "question_id": 45396, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Background\n\n\n\n\nI have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/mLTa1ZsD.png] (https://i.sstatic.net/mLTa1ZsD.png)\n\n\n\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.\n\n\n\n\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.\n\n\n\n\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/K6cTCsGy.png] (https://i.sstatic.net/K6cTCsGy.png)\n\n\n\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.\n\n\n\n\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/4aqhk3tL.png] (https://i.sstatic.net/4aqhk3tL.png)\n\n\n\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.\n\n\n\n\nI am going to describe the logic in a high level:\n\n\n\n\n\nConsider that an $\\mathbb{R^3}$ legendre polynomial becomes a regular polynomial when restricted to the parametric line of a ray.\n\n\n\n\nGrab the coefficients of the quadric on the current node, knowing these are coefficients of a legendre polynomial, not monomials.\n\n\n\n\nFor each coefficient, add it to the corresponding constant, linear or quadric set of coefficents (for monomials).\n\n\n\n\nGrab the final, properly factored, coeffcients and solve a simple quadratic equation to figure out if and where the ray intersects the quadric on the current node.\n\n\n\n\n\nThe actual code is this:\n\n\n\n\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &NodeThe gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.
\nThe given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).
\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.
\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.
\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.
\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.
\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).
\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:
\n| First polynomial | \nSecond polynomial | \n
|---|---|
| $1$ or $q^0$ | \n$q^{8+2x_{13}}$ | \n
| $q^2$ | \n$q^{10+2x_{13}}$ | \n
| $q^8$ | \n$q^{4+2x_{15}}$ | \n
| $q^{10}$ | \n$q^{6+2x_{15}}$ | \n
| $q^{12}$ | \n$q^{2x_{17}}$ | \n
| $q^{14}$ | \n$q^{2+2x_{17}}$ | \n
| $q^{16}$ | \n$q^{2x_{35}}$ | \n
| $q^{18}$ | \n$q^{2+2x_{35}}$ | \n
| $q^{20}$ | \n$q^{-4+2x_{37}}$ | \n
| $q^{22}$ | \n$q^{-2+2x_{37}}$ | \n
| $q^{24}$ | \n$q^{-8+2x_{57}}$ | \n
| $q^{26}$ | \n$q^{-6+2x_{57}}$ | \n
Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.
\nThis resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.
\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.
\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.
\n", "answer_id": 45473, "answer_text": "The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.", "answer_url": "https://scicomp.stackexchange.com/a/45473", "author": "hardmath", "author_url": "https://scicomp.stackexchange.com/users/651/hardmath", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-24T21:53:31+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "hardmath", "profile_url": "https://scicomp.stackexchange.com/users/651/hardmath", "user_type": "moderator"}, "created_at": "2026-06-24T21:53:31+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "6B10CE88-2D26-43C8-9F27-870834FE5FB3", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}], "score": 2, "updated_at": "2026-06-24T21:53:31+00:00"}], "product": "code_qa", "question": "I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.\n\n\n\n\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.\n\n\n\n\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.\n\n\n\n\nDo you guys know of any hint or solution on how to tackle these problems?\n\n\n\n\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$\n\n\n\n\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$\n\n\n\n\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45472", "selected_answer": {"answer_html": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative "pulls down" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:
restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.
\n", "answer_id": 45482, "answer_text": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative \"pulls down\" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:\n\n\n\n\nrestart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\n\n\n\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.", "answer_url": "https://scicomp.stackexchange.com/a/45482", "author": "dharr", "author_url": "https://scicomp.stackexchange.com/users/50934/dharr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-28T17:22:41+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:22:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "17B5B435-530D-44FB-A531-8C7EBC69DAB0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:30:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B335F14D-BC1A-4871-8C8E-AA1A1574CE8E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T00:34:42+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "AE6B318A-E224-4873-94DF-796E47B0400A", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T01:28:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "E46B4CBF-9F68-49D7-885E-BE0F07FBA25B", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T02:02:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BE24CE57-475F-48DB-8B09-676A64E891E3", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-07-06T01:31:28+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "64B9EB1B-7407-427F-BF22-4AF94181F69C", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}], "score": 3, "updated_at": "2026-07-06T01:31:28+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.
\nThe given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).
\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.
\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.
\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.
\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.
\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).
\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:
\n| First polynomial | \nSecond polynomial | \n
|---|---|
| $1$ or $q^0$ | \n$q^{8+2x_{13}}$ | \n
| $q^2$ | \n$q^{10+2x_{13}}$ | \n
| $q^8$ | \n$q^{4+2x_{15}}$ | \n
| $q^{10}$ | \n$q^{6+2x_{15}}$ | \n
| $q^{12}$ | \n$q^{2x_{17}}$ | \n
| $q^{14}$ | \n$q^{2+2x_{17}}$ | \n
| $q^{16}$ | \n$q^{2x_{35}}$ | \n
| $q^{18}$ | \n$q^{2+2x_{35}}$ | \n
| $q^{20}$ | \n$q^{-4+2x_{37}}$ | \n
| $q^{22}$ | \n$q^{-2+2x_{37}}$ | \n
| $q^{24}$ | \n$q^{-8+2x_{57}}$ | \n
| $q^{26}$ | \n$q^{-6+2x_{57}}$ | \n
Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.
\nThis resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.
\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.
\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.
\n", "answer_id": 45473, "answer_text": "The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.", "answer_url": "https://scicomp.stackexchange.com/a/45473", "author": "hardmath", "author_url": "https://scicomp.stackexchange.com/users/651/hardmath", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-24T21:53:31+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "hardmath", "profile_url": "https://scicomp.stackexchange.com/users/651/hardmath", "user_type": "moderator"}, "created_at": "2026-06-24T21:53:31+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "6B10CE88-2D26-43C8-9F27-870834FE5FB3", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}], "score": 2, "updated_at": "2026-06-24T21:53:31+00:00"}, {"answer_html": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative "pulls down" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:
restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.
\n", "answer_id": 45482, "answer_text": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative \"pulls down\" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:\n\n\n\n\nrestart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\n\n\n\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.", "answer_url": "https://scicomp.stackexchange.com/a/45482", "author": "dharr", "author_url": "https://scicomp.stackexchange.com/users/50934/dharr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-28T17:22:41+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:22:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "17B5B435-530D-44FB-A531-8C7EBC69DAB0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:30:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B335F14D-BC1A-4871-8C8E-AA1A1574CE8E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T00:34:42+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "AE6B318A-E224-4873-94DF-796E47B0400A", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T01:28:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "E46B4CBF-9F68-49D7-885E-BE0F07FBA25B", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T02:02:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BE24CE57-475F-48DB-8B09-676A64E891E3", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-07-06T01:31:28+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "64B9EB1B-7407-427F-BF22-4AF94181F69C", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}], "score": 3, "updated_at": "2026-07-06T01:31:28+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Graph_realization_problem", "https://en.wikipedia.org/wiki/Laurent_polynomial", "https://en.wikipedia.org/wiki/Prolog"], "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": "ateixeira82", "question_author_url": "https://scicomp.stackexchange.com/users/56972/ateixeira82", "question_author_user_type": "registered", "question_created_at": "2026-06-21T10:31:05+00:00", "question_html": "I am trying to solve a linear system of equations that comes from equating two Laurent polynomials. The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.
\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.
\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.
\nDo you guys know of any hint or solution on how to tackle these problems?
\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$
\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$
\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.
\n", "question_id": 45472, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.\n\n\n\n\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.\n\n\n\n\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.\n\n\n\n\nDo you guys know of any hint or solution on how to tackle these problems?\n\n\n\n\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$\n\n\n\n\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$\n\n\n\n\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ateixeira82", "profile_url": "https://scicomp.stackexchange.com/users/56972/ateixeira82", "user_type": "registered"}, "created_at": "2026-06-21T10:31:05+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "F5FC1979-2C80-415C-8F46-2AF9C62D8214", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/F5FC1979-2C80-415C-8F46-2AF9C62D8214/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ateixeira82", "profile_url": "https://scicomp.stackexchange.com/users/56972/ateixeira82", "user_type": "registered"}, "created_at": "2026-06-21T14:46:19+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "53FB132D-482A-4B58-AD12-EF8D7216467C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/53FB132D-482A-4B58-AD12-EF8D7216467C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "hardmath", "profile_url": "https://scicomp.stackexchange.com/users/651/hardmath", "user_type": "moderator"}, "created_at": "2026-06-24T19:16:29+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "41EC7BF5-D5F7-4405-918D-9C3797D59DDE", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/41EC7BF5-D5F7-4405-918D-9C3797D59DDE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45472/solving-linear-system-of-equations-with-combinatorics", "split": "train", "split_group": "bc3b4da5bdff031e2377bca4a34351252b5b5eb37044f7ea6ace3a407e2df29e", "tags": ["python", "linear-system", "mathematica", "combinatorics"], "thread_id": "scicomp:45472", "title": "Solving linear system of equations with combinatorics"}} {"accepted_answer": {"answer_html": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n", "answer_id": 45503, "answer_text": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.", "answer_url": "https://scicomp.stackexchange.com/a/45503", "author": "Omar Osman Mahamoud", "author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-29T16:42:27+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-29T16:42:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DD32D002-9E3F-4398-BC22-FB7FBF667951", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}], "score": 2, "updated_at": "2026-07-29T16:42:27+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "def euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45487, "sha256": "cf0bde6333be3658682c2bbbf3514be3f691d7dfe36bcc4c07befe85d7046069", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"}, {"block_index": 1, "code_text": "def Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45487, "sha256": "16f70485ac76c3d299f343fc55817b8b11ff0d5048050d78df40f99c7a3c34d5", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"}, {"block_index": 2, "code_text": "def Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45487, "sha256": "664f217d728581a98996f2f18b9c12d83f56da4e8f3ec3511a3531d746e98194", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"}, {"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45490, "sha256": "0739849795b9b7d88e5352edf2511378cd32dd94d0652612d0afef3309011d46", "source_url": "https://scicomp.stackexchange.com/a/45490"}, {"block_index": 1, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45490, "sha256": "5e92562921cb4c242909f38ee3d1a780addba783f5b7d0dce4ef1fffc163584d", "source_url": "https://scicomp.stackexchange.com/a/45490"}], "other_answers": [{"answer_html": "Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\nFor n=5000, dt=0.001, the output is closer yet:
\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n", "answer_id": 45490, "answer_text": "From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n[image: comparison; source: https://i.sstatic.net/ZOXbZlmS.png] (https://i.sstatic.net/ZOXbZlmS.png)\n\n\n\n\nFor n=5000, dt=0.001, the output is closer yet:\n\n\n\n\n[image: dt=0.001; source: https://i.sstatic.net/mLRffKQD.png] (https://i.sstatic.net/mLRffKQD.png)\n\n\n\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine (https://www.sciencedirect.com/science/article/pii/0893965989900797) form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: RK32; source: https://i.sstatic.net/DgMDrx4E.png] (https://i.sstatic.net/DgMDrx4E.png)", "answer_url": "https://scicomp.stackexchange.com/a/45490", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T01:47:13+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "revision_attribution": [{"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-07-13T01:47:13+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "06EC415F-DC78-49A5-97D0-ED020CE6C74F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/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-07-13T03:28:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "88B016CA-5B2E-46C7-99DA-7F374A3A0853", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/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-07-13T21:27:38+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "51F9060A-E0B8-4FC6-AAA1-D61ED8331962", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}], "score": 6, "updated_at": "2026-07-13T21:27:38+00:00"}, {"answer_html": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.
\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!
\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)
\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods "symplectic integrators", because they preserve energy and impulse better, but my memory may be leaky.
\n", "answer_id": 45491, "answer_text": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.\n\n\n\n\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!\n\n\n\n\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)\n\n\n\n\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods \"symplectic integrators\", because they preserve energy and impulse better, but my memory may be leaky.", "answer_url": "https://scicomp.stackexchange.com/a/45491", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T06:50:20+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "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": "2026-07-13T06:50:20+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}], "score": 7, "updated_at": "2026-07-13T06:50:20+00:00"}], "product": "code_qa", "question": "I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.\n\n\n\n\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.\n\n\n\n\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?\n\n\n\n\nHere are the three implementations.\n\n\n\n\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\n\n\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45487", "selected_answer": {"answer_html": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n", "answer_id": 45503, "answer_text": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.", "answer_url": "https://scicomp.stackexchange.com/a/45503", "author": "Omar Osman Mahamoud", "author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-29T16:42:27+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-29T16:42:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DD32D002-9E3F-4398-BC22-FB7FBF667951", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}], "score": 2, "updated_at": "2026-07-29T16:42:27+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45503, "answers": [{"answer_html": "Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\nFor n=5000, dt=0.001, the output is closer yet:
\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n", "answer_id": 45490, "answer_text": "From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n[image: comparison; source: https://i.sstatic.net/ZOXbZlmS.png] (https://i.sstatic.net/ZOXbZlmS.png)\n\n\n\n\nFor n=5000, dt=0.001, the output is closer yet:\n\n\n\n\n[image: dt=0.001; source: https://i.sstatic.net/mLRffKQD.png] (https://i.sstatic.net/mLRffKQD.png)\n\n\n\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine (https://www.sciencedirect.com/science/article/pii/0893965989900797) form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: RK32; source: https://i.sstatic.net/DgMDrx4E.png] (https://i.sstatic.net/DgMDrx4E.png)", "answer_url": "https://scicomp.stackexchange.com/a/45490", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T01:47:13+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "revision_attribution": [{"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-07-13T01:47:13+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "06EC415F-DC78-49A5-97D0-ED020CE6C74F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/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-07-13T03:28:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "88B016CA-5B2E-46C7-99DA-7F374A3A0853", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/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-07-13T21:27:38+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "51F9060A-E0B8-4FC6-AAA1-D61ED8331962", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}], "score": 6, "updated_at": "2026-07-13T21:27:38+00:00"}, {"answer_html": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.
\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!
\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)
\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods "symplectic integrators", because they preserve energy and impulse better, but my memory may be leaky.
\n", "answer_id": 45491, "answer_text": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.\n\n\n\n\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!\n\n\n\n\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)\n\n\n\n\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods \"symplectic integrators\", because they preserve energy and impulse better, but my memory may be leaky.", "answer_url": "https://scicomp.stackexchange.com/a/45491", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T06:50:20+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "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": "2026-07-13T06:50:20+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}], "score": 7, "updated_at": "2026-07-13T06:50:20+00:00"}, {"answer_html": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n", "answer_id": 45503, "answer_text": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.", "answer_url": "https://scicomp.stackexchange.com/a/45503", "author": "Omar Osman Mahamoud", "author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-29T16:42:27+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-29T16:42:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DD32D002-9E3F-4398-BC22-FB7FBF667951", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}], "score": 2, "updated_at": "2026-07-29T16:42:27+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Semi-implicit_Euler_method", "https://i.sstatic.net/DgMDrx4E.png", "https://i.sstatic.net/ZOXbZlmS.png", "https://i.sstatic.net/mLRffKQD.png", "https://www.sciencedirect.com/science/article/pii/0893965989900797", "https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6"], "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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-07-12T12:23:53+00:00", "question_html": "Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.
\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.
\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?
\nHere are the three implementations.
\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?
\n", "question_id": 45487, "question_license": "CC BY-SA 4.0", "question_score": 7, "question_text": "I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.\n\n\n\n\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.\n\n\n\n\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?\n\n\n\n\nHere are the three implementations.\n\n\n\n\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\n\n\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-12T12:23:53+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "D3AC3DA9-7794-465F-AF03-B877C6C0EF0D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D3AC3DA9-7794-465F-AF03-B877C6C0EF0D/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-07-13T01:54:39+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "8CA42130-747B-47CA-BB4D-D7CD4CD70CC8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/8CA42130-747B-47CA-BB4D-D7CD4CD70CC8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T09:09:11+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "3FEC6861-FADA-4330-8FB0-12A8839B955D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3FEC6861-FADA-4330-8FB0-12A8839B955D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-15T23:49:16+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "7914AE3D-629C-4FCA-BF96-6D9824005EDC", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/7914AE3D-629C-4FCA-BF96-6D9824005EDC/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-16T00:10:59+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "62C0155C-4F90-4C15-8CFB-EDCF7BC7548E", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/62C0155C-4F90-4C15-8CFB-EDCF7BC7548E/view-source"}, {"content_license": null, "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-16T11:22:30+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BAF51E0F-7B50-4443-B0DF-BC44A34EF5BE", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BAF51E0F-7B50-4443-B0DF-BC44A34EF5BE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t", "split": "train", "split_group": "e3c4c48d2016f7277be3216b64a0dd6deac291a4bba983d1b0acef890102a34a", "tags": ["python", "simulation", "runge-kutta", "physics"], "thread_id": "scicomp:45487", "title": "Why do my RK2 and Velocity Verlet implementations produce less accurate orbits than Euler?"}} {"accepted_answer": {"answer_html": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.
\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.
\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.
\n", "answer_id": 45492, "answer_text": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.\n\n\n\n\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.\n\n\n\n\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.", "answer_url": "https://scicomp.stackexchange.com/a/45492", "author": "Lutz Lehmann", "author_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T16:52:52+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45488, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T16:52:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A/view-source"}], "score": 6, "updated_at": "2026-07-13T16:52:52+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color=\"green\")\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45488, "sha256": "29098e66448020fa60ce6a91831d46a6b9403f2e88a3a639a5e298caa2a96612", "source_url": "https://scicomp.stackexchange.com/questions/45488/why-do-these-two-python-implementations-of-the-same-algorithm-give-different-out"}, {"block_index": 1, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45488, "sha256": "366f1e96b6f89a37850e16fa5ea865fc24548f235ddec9e4dc27467658dd34a5", "source_url": "https://scicomp.stackexchange.com/questions/45488/why-do-these-two-python-implementations-of-the-same-algorithm-give-different-out"}, {"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45489, "sha256": "279d1d4e50b4e9bc5ece09985d31e55e079e25b1831affda48b09a8e4c244d89", "source_url": "https://scicomp.stackexchange.com/a/45489"}, {"block_index": 1, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45489, "sha256": "66befcd4aaf54a2524fc9549c2ecf654793aedbe892f014947d4721bb37a8e2c", "source_url": "https://scicomp.stackexchange.com/a/45489"}, {"block_index": 2, "code_text": "import time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45489, "sha256": "db1869b930dcad78727f6acb5716fd94e75923783771588824f838bbf9d7d4b4", "source_url": "https://scicomp.stackexchange.com/a/45489"}], "other_answers": [{"answer_html": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\nBut of course expressing this as a proper IVP is more stable:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\nAs a more fulsome demo, note that for an ODE state vector of
\n$$\n[ x, y, \\dot x, \\dot y ]\n$$
\nthe Jacobian is
\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$
\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45489, "answer_text": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\n\n\n\n[image: plot; source: https://i.sstatic.net/Tq7uPZJj.png] (https://i.sstatic.net/Tq7uPZJj.png)\n\n\n\n\nBut of course expressing this as a proper IVP is more stable:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: ivp; source: https://i.sstatic.net/KnVXs58G.png] (https://i.sstatic.net/KnVXs58G.png)\n\n\n\n\n\n\n\nAs a more fulsome demo, note that for an ODE state vector of\n\n\n\n\n$$\n[ x, y, \\dot x, \\dot y ]\n$$\n\n\n\n\nthe Jacobian is\n\n\n\n\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$\n\n\n\n\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45489", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T00:25:35+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45488, "revision_attribution": [{"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-07-13T00:25:35+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "C9922D8C-A590-4B1E-94CA-B97A778DA7B4", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C9922D8C-A590-4B1E-94CA-B97A778DA7B4/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-07-13T01:06:34+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "43E7D35E-D810-41D3-9F12-FDE31BF65860", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/43E7D35E-D810-41D3-9F12-FDE31BF65860/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-09-26T19:23:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "9970817B-8E8F-4EAC-BE66-46090CDC3BB0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9970817B-8E8F-4EAC-BE66-46090CDC3BB0/view-source"}], "score": 8, "updated_at": "2026-09-26T19:23:41+00:00"}], "product": "code_qa", "question": "Can someone please tell me why these two codes don't give the same answer?\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color=\"green\")\nplt.show()\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/mLgbrUlD.png] (https://i.sstatic.net/mLgbrUlD.png)\n\n\n\n\nand\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/XWVvnmXc.png] (https://i.sstatic.net/XWVvnmXc.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45488", "selected_answer": {"answer_html": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.
\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.
\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.
\n", "answer_id": 45492, "answer_text": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.\n\n\n\n\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.\n\n\n\n\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.", "answer_url": "https://scicomp.stackexchange.com/a/45492", "author": "Lutz Lehmann", "author_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T16:52:52+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45488, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T16:52:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A/view-source"}], "score": 6, "updated_at": "2026-07-13T16:52:52+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45492, "answers": [{"answer_html": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\nBut of course expressing this as a proper IVP is more stable:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\nAs a more fulsome demo, note that for an ODE state vector of
\n$$\n[ x, y, \\dot x, \\dot y ]\n$$
\nthe Jacobian is
\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$
\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45489, "answer_text": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\n\n\n\n[image: plot; source: https://i.sstatic.net/Tq7uPZJj.png] (https://i.sstatic.net/Tq7uPZJj.png)\n\n\n\n\nBut of course expressing this as a proper IVP is more stable:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: ivp; source: https://i.sstatic.net/KnVXs58G.png] (https://i.sstatic.net/KnVXs58G.png)\n\n\n\n\n\n\n\nAs a more fulsome demo, note that for an ODE state vector of\n\n\n\n\n$$\n[ x, y, \\dot x, \\dot y ]\n$$\n\n\n\n\nthe Jacobian is\n\n\n\n\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$\n\n\n\n\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45489", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T00:25:35+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45488, "revision_attribution": [{"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-07-13T00:25:35+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "C9922D8C-A590-4B1E-94CA-B97A778DA7B4", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C9922D8C-A590-4B1E-94CA-B97A778DA7B4/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-07-13T01:06:34+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "43E7D35E-D810-41D3-9F12-FDE31BF65860", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/43E7D35E-D810-41D3-9F12-FDE31BF65860/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-09-26T19:23:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "9970817B-8E8F-4EAC-BE66-46090CDC3BB0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9970817B-8E8F-4EAC-BE66-46090CDC3BB0/view-source"}], "score": 8, "updated_at": "2026-09-26T19:23:41+00:00"}, {"answer_html": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.
\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.
\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.
\n", "answer_id": 45492, "answer_text": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.\n\n\n\n\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.\n\n\n\n\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.", "answer_url": "https://scicomp.stackexchange.com/a/45492", "author": "Lutz Lehmann", "author_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T16:52:52+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45488, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T16:52:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A/view-source"}], "score": 6, "updated_at": "2026-07-13T16:52:52+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/KnVXs58G.png", "https://i.sstatic.net/Tq7uPZJj.png", "https://i.sstatic.net/XWVvnmXc.png", "https://i.sstatic.net/mLgbrUlD.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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-07-12T16:05:18+00:00", "question_html": "Can someone please tell me why these two codes don't give the same answer?
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color="green")\nplt.show()\n\n\nand
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n\n\n", "question_id": 45488, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Can someone please tell me why these two codes don't give the same answer?\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color=\"green\")\nplt.show()\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/mLgbrUlD.png] (https://i.sstatic.net/mLgbrUlD.png)\n\n\n\n\nand\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/XWVvnmXc.png] (https://i.sstatic.net/XWVvnmXc.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-12T16:05:18+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "F0D7914F-24E6-41F7-BF73-8B6CAC429B71", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/F0D7914F-24E6-41F7-BF73-8B6CAC429B71/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-07-13T01:24:37+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BC3D64B0-5C3E-43B3-B708-134F783143A0", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/BC3D64B0-5C3E-43B3-B708-134F783143A0/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45488/why-do-these-two-python-implementations-of-the-same-algorithm-give-different-out", "split": "train", "split_group": "4ff0006883a431c9705a554000147f3098c4b66f9f495d2a19d5c9d5cef4057f", "tags": ["python", "computational-physics", "simulation", "numerical-integration"], "thread_id": "scicomp:45488", "title": "Why do these two Python implementations of the same algorithm give different outputs?"}}
{"accepted_answer": {"answer_html": "You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods. Accordingly, I have implemented the scheme as follows::
\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.
\n", "question_id": 45510, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods (https://open.umich.edu/sites/default/files/downloads/2012-parallel-spectral-numerical-methods.pdf). Accordingly, I have implemented the scheme as follows::\n\n\n\n\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\n\n\n\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Manav Jalan", "profile_url": "https://scicomp.stackexchange.com/users/57116/manav-jalan", "user_type": "registered"}, "created_at": "2026-08-05T11:30:29+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "89E117A0-D17A-486B-9AB6-3BFCFC57C353", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/89E117A0-D17A-486B-9AB6-3BFCFC57C353/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-06T12:01:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "669E53D8-1766-46EB-8CA1-42CE9017157D", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/669E53D8-1766-46EB-8CA1-42CE9017157D/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio", "split": "train", "split_group": "6d0c54a4e8c7f952e689a3d4b5202b082d3107c2394fe7cc81a815a1a0401dc5", "tags": ["computational-physics", "spectral-method", "pseudospectral"], "thread_id": "scicomp:45510", "title": "Allen Cahn Psuedospectral solver blowup even after reaching steady state solution"}} {"accepted_answer": {"answer_html": "Your calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n", "answer_id": 45524, "answer_text": "Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nYour calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n", "answer_id": 45524, "answer_text": "Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nYour calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n", "answer_id": 45524, "answer_text": "Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nI am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:
\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:
\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?
\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: "Figure. Regular Heptagon Image taken from a Math Stack Exchange Question", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.
\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:
\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.
\n\n\nFrom the question "What could be this unknown angle in this regular\nheptagon?"
\nThere is the image drawn of a Regular Heptagon:
\n\n\n\n
![]()
Figure. Regular Heptagon Image taken from a\nMath Stack Exchange Question
On the site: https://www.onlinegdb.com/online_c_compiler
\n#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double pid;\n // pid=acos(-1);\n // double DegreesToRadians = 3.14159265358979323846/180.0;\n // double DegreesToRadians = pid/180.0;\n // const double DegreesToRadians=3.14159265358979323846/180.0;\n double DegreesToRadians=acos(-1.0)/180.0;\n \n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n // 3. Print Results\n // %lf is the format specifier for double, %f is for float\n // printf("Double: cos(%.1lf degrees) = %lf\\n", degrees_d, result_double);\n // printf("Float: cos(%.1f degrees) = %f\\n", degrees_f, result_float);\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n\n printf("Double: acos(-1.0) %.15lf \\n",acos(-1.0));\n printf("Double: vec cb dot vec cf %0.15lf\\n", cbdotcf);\n printf("Double: vec ab dot vec af %0.15lf\\n", abdotaf);\n printf("Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf("Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n\n return 0;\n}\n\nTaking the suggestions from Reinderien's answer, the source code was updated. Using the online c compiler https://www.onlinegdb.com/online_c_compiler, the below source code compiled fine and yielded angles very consistent with Reinderien's answer quoted below, with instead of 2 digits precision, 15 digit precision:
\n\n\n\n
n = 7\ncbcf = 88.56°\nabaf = 88.56°
#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double DegreesToRadians = 3.14159265358979323846/180.0;\n\n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-veca[1];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n //Calculate the necessary dot products\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n // Print Results\n // %lf is the format specifier for double %l.15 is for 15 digits to the right\n // That amount of precision is consistant with the constant PI as a double float\n printf("Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \\n");\n printf("Double: acos(-1.0) = %.15lf \\n",acos(-1.0));\n printf("Constant 3.14159265358979323846 = %.15lf \\n",3.14159265358979323846);\n printf("Double: acos(-1.0)/180.0 = %.15lf \\n",acos(-1.0)/180.0);\n printf("Double: 3.14159265358979323846/180.0 = %.15lf \\n",3.14159265358979323846/180.0);\n printf("Double: vec cb dot vec cf %0.15lf\\n", cbdotcf);\n printf("Double: vec ab dot vec af %0.15lf\\n", abdotaf);\n printf("Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf("Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n return 0;\n}\n\n", "question_id": 45523, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:\n\n\n\n\nHow can the Referenced Regular Heptagon inscribed within a Unit Circle, with its center coinciding, be drawn using PostScript Programming Language? (https://scicomp.stackexchange.com/questions/45518/how-can-the-referenced-regular-heptagon-inscribed-within-a-unit-circle-with-its)\n\n\n\n\n[image: Image of the Regular Heptagon; source: https://i.sstatic.net/z1YPOvX5.png] (https://i.sstatic.net/z1YPOvX5.png)\n\n\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:\n\n\n\n\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\n\n\n\n\nThe Question: Where Are my C calculations Going Wrong?\n\n\n\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?\n\n\n\n\nUpdate: Answer Calculated, but Angles $\\angle BCF$ and\n$\\angle BAF$ are equal, but not $90^{\\circ}$\n\n\n\n\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: \"Figure. Regular Heptagon Image taken from a Math Stack Exchange Question\", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.\n\n\n\n\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:\n\n\n\n\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\n\n\n\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.\n\n\n\n\n\n\n\nFrom the question \"What could be this unknown angle in this regular\nheptagon?\" (https://math.stackexchange.com/questions/5146710/what-could-be-this-unknown-angle-in-this-regular-heptagon/5146818#5146818)\n\n\n\n\nThere is the image drawn of a Regular Heptagon:\n\n\n\n\n\n\n\n[image: Regular Heptagon Image taken from a Math Stack Exchange Question; source: https://i.sstatic.net/JpG0VRI2.jpg] (https://i.sstatic.net/JpG0VRI2.jpg) \nFigure. Regular Heptagon Image taken from a\nMath Stack Exchange Question\n\n\n\n\n\n\n\n\n\n\n\nAppendix: C Programming Language Source Code to Calculate Angles for a Regular Heptagon\n\n\n\n\nOn the site: https://www.onlinegdb.com/online_c_compiler (https://www.onlinegdb.com/online_c_compiler)\n\n\n\n\n#include I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.
\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.
\nimport sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\nHere are a few finite element specific resources:
\nFor how to analyze the general stability of numerical discretizations:
\nI'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.
\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.
\nimport sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\nHere are a few finite element specific resources:
\nFor how to analyze the general stability of numerical discretizations:
\nI need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled "Finite Element Method", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.
\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?
\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided
\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = "Lagrange" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure("dx", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = "preonly" # Preconditioning Matrix Option\nsolver_type = "lu" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix="first_order_ODE", bcs = [bc], petsc_options={"ksp_type": ksp_type, "pc_type": solver_type})\nu_sol = problem.solve()\n\n\nwe can see the solution is infinity at all node values of the functionspace.
\n", "question_id": 45530, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled \"Finite Element Method\", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.\n\n\n\n\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?\n\n\n\n\n\n\n\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided\n\n\n\n\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = \"Lagrange\" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure(\"dx\", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = \"preonly\" # Preconditioning Matrix Option\nsolver_type = \"lu\" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix=\"first_order_ODE\", bcs = [bc], petsc_options={\"ksp_type\": ksp_type, \"pc_type\": solver_type})\nu_sol = problem.solve()\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/8M1U5hQT.png] (https://i.sstatic.net/8M1U5hQT.png)\n\n\n\n\nwe can see the solution is infinity at all node values of the functionspace.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Researcher R", "profile_url": "https://scicomp.stackexchange.com/users/53321/researcher-r", "user_type": "registered"}, "created_at": "2026-08-30T03:46:19+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "8A694B8D-C740-489D-AB57-AFCBA245C49D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/8A694B8D-C740-489D-AB57-AFCBA245C49D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Researcher R", "profile_url": "https://scicomp.stackexchange.com/users/53321/researcher-r", "user_type": "registered"}, "created_at": "2026-08-30T23:41:50+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-31T23:54:34+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45530/are-there-any-resources-which-cover-finding-stable-weak-forms-to-1st-order-diffe", "split": "train", "split_group": "38a212b64b791c4e49567a55cdb42224036c90a0d764070d65bb8936af2fe336", "tags": ["finite-element", "reference-request", "least-squares", "galerkin", "weak-solution"], "thread_id": "scicomp:45530", "title": "Are there any resources which cover finding stable weak forms to 1st-order differential equations"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print(\"t = \", i)\n for j in range(1,n+1):\n # print(\"n = \", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45541, "sha256": "ec8560746cd8ed8699dc2c11fc07f68d8e9a5474d7445fc7c73a4819a02e76aa", "source_url": "https://scicomp.stackexchange.com/questions/45541/fourier-serie-algorithm"}, {"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45542, "sha256": "86f02ec052fe24ddab955b090bac125c5a7c6db1f2c4bd60e22e97daf6674a7f", "source_url": "https://scicomp.stackexchange.com/a/45542"}, {"block_index": 1, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45542, "sha256": "eed9b19202c4a48fe407d4b2a7b7936f04c96a4ae67364b7f3f275cc3c4d46e3", "source_url": "https://scicomp.stackexchange.com/a/45542"}, {"block_index": 2, "code_text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45542, "sha256": "6a294b184211babd5e09b2cdf09509ad0fdf8c6c7f61af6b68eaf9c092a2d93a", "source_url": "https://scicomp.stackexchange.com/a/45542"}], "other_answers": [], "product": "code_qa", "question": "here is the Fourier series I'm trying to represent:\n\n\n\n\n$$\nf(t) = \\frac{A\\tau}{T} + \\frac{A}{\\pi}\\sum_{n=1}^{\\infty}\\frac{1}{n}\\left[\\sin(n\\omega\\tau)\\cos(n\\omega t) + \\left(1-\\cos(n\\omega\\tau)\\right)\\sin(n\\omega t)\\right]\n$$\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print(\"t = \", i)\n for j in range(1,n+1):\n # print(\"n = \", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n\n\n\n\n\ncan you guys please tell me why my algorithm doesn't work properly?\nactually my teacher says I should obtain the following figure:\n\n\n\n\n[image: the correct figure according to my teacher; source: https://i.sstatic.net/QM4j9vnZ.png] (https://i.sstatic.net/QM4j9vnZ.png)\n\n\n\n\nnot the straight lines I'm obtaining with my code!! here is what I'm getting with my code:\n\n\n\n\n[image: the function I get with my code; source: https://i.sstatic.net/9Q1FTH4K.png] (https://i.sstatic.net/9Q1FTH4K.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45541", "selected_answer": {"answer_html": "Assuming your math is correct, then very literally and using a broadcast sum,
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\nFurther: in "real life", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:
\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()\n\n", "answer_id": 45542, "answer_text": "Assuming your math is correct, then very literally and using a broadcast sum,\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\n\n\n\n[image: f(t); source: https://i.sstatic.net/YjgeAIXx.png] (https://i.sstatic.net/YjgeAIXx.png)\n\n\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\n\n\n\n[image: f(t) hires; source: https://i.sstatic.net/Ag4Fil8J.png] (https://i.sstatic.net/Ag4Fil8J.png)\n\n\n\n\nFurther: in \"real life\", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:\n\n\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()", "answer_url": "https://scicomp.stackexchange.com/a/45542", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-20T17:18:55+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45541, "revision_attribution": [{"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-09-20T17:18:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "62E18C62-347B-4371-A12B-7026926DDD8F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/62E18C62-347B-4371-A12B-7026926DDD8F/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-09-21T01:55:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DB2CC339-A8C8-44D8-816A-B9919DFBB2BE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DB2CC339-A8C8-44D8-816A-B9919DFBB2BE/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-09-27T18:44:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "5CA547D4-1223-44E9-9049-12894162675F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/5CA547D4-1223-44E9-9049-12894162675F/view-source"}], "score": 3, "updated_at": "2026-09-27T18:44:52+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Assuming your math is correct, then very literally and using a broadcast sum,
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\nFurther: in "real life", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:
\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()\n\n", "answer_id": 45542, "answer_text": "Assuming your math is correct, then very literally and using a broadcast sum,\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\n\n\n\n[image: f(t); source: https://i.sstatic.net/YjgeAIXx.png] (https://i.sstatic.net/YjgeAIXx.png)\n\n\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\n\n\n\n[image: f(t) hires; source: https://i.sstatic.net/Ag4Fil8J.png] (https://i.sstatic.net/Ag4Fil8J.png)\n\n\n\n\nFurther: in \"real life\", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:\n\n\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()", "answer_url": "https://scicomp.stackexchange.com/a/45542", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-20T17:18:55+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "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=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45541, "revision_attribution": [{"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-09-20T17:18:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "62E18C62-347B-4371-A12B-7026926DDD8F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/62E18C62-347B-4371-A12B-7026926DDD8F/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-09-21T01:55:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DB2CC339-A8C8-44D8-816A-B9919DFBB2BE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DB2CC339-A8C8-44D8-816A-B9919DFBB2BE/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-09-27T18:44:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "5CA547D4-1223-44E9-9049-12894162675F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/5CA547D4-1223-44E9-9049-12894162675F/view-source"}], "score": 3, "updated_at": "2026-09-27T18:44:52+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/9Q1FTH4K.png", "https://i.sstatic.net/Ag4Fil8J.png", "https://i.sstatic.net/QM4j9vnZ.png", "https://i.sstatic.net/YjgeAIXx.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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-09-20T09:43:07+00:00", "question_html": "here is the Fourier series I'm trying to represent:
\n$$\nf(t) = \\frac{A\\tau}{T} + \\frac{A}{\\pi}\\sum_{n=1}^{\\infty}\\frac{1}{n}\\left[\\sin(n\\omega\\tau)\\cos(n\\omega t) + \\left(1-\\cos(n\\omega\\tau)\\right)\\sin(n\\omega t)\\right]\n$$
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print("t = ", i)\n for j in range(1,n+1):\n # print("n = ", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n\ncan you guys please tell me why my algorithm doesn't work properly?\nactually my teacher says I should obtain the following figure:
\n\nnot the straight lines I'm obtaining with my code!! here is what I'm getting with my code:
\n\n", "question_id": 45541, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "here is the Fourier series I'm trying to represent:\n\n\n\n\n$$\nf(t) = \\frac{A\\tau}{T} + \\frac{A}{\\pi}\\sum_{n=1}^{\\infty}\\frac{1}{n}\\left[\\sin(n\\omega\\tau)\\cos(n\\omega t) + \\left(1-\\cos(n\\omega\\tau)\\right)\\sin(n\\omega t)\\right]\n$$\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print(\"t = \", i)\n for j in range(1,n+1):\n # print(\"n = \", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n\n\n\n\n\ncan you guys please tell me why my algorithm doesn't work properly?\nactually my teacher says I should obtain the following figure:\n\n\n\n\n[image: the correct figure according to my teacher; source: https://i.sstatic.net/QM4j9vnZ.png] (https://i.sstatic.net/QM4j9vnZ.png)\n\n\n\n\nnot the straight lines I'm obtaining with my code!! here is what I'm getting with my code:\n\n\n\n\n[image: the function I get with my code; source: https://i.sstatic.net/9Q1FTH4K.png] (https://i.sstatic.net/9Q1FTH4K.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-09-20T09:43:07+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "8716CC99-7DA9-4A6F-911C-FAACA954CAA2", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/8716CC99-7DA9-4A6F-911C-FAACA954CAA2/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-09-20T19:27:14+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B66CE3FA-A844-4670-A363-F672A05FC4D7", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B66CE3FA-A844-4670-A363-F672A05FC4D7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-09-21T17:20:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "514285A3-DDCE-4F58-8678-1757D1975928", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/514285A3-DDCE-4F58-8678-1757D1975928/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45541/fourier-serie-algorithm", "split": "train", "split_group": "08ece08d441adfb76f86f3181bf0940ebff42417bb75c43be3a5da1104c05c94", "tags": ["python", "algorithms", "fourier-analysis", "fourier-transform"], "thread_id": "scicomp:45541", "title": "Fourier Serie algorithm"}}