File size: 101,415 Bytes
a3a7873 | 1 2 3 4 | {"accepted_answer":{"answer_html":"<p>I think you can find the mean and variance of <span class=\"math-container\">$\\bar y$</span> analytically. Clearly <span class=\"math-container\">$\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$</span> and, using the law of total variance <span class=\"math-container\">$$\\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}.$$</span></p>\n<p>Since <span class=\"math-container\">$\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$</span>, you can then say <span class=\"math-container\">$$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$</span></p>\n<p>For given <span class=\"math-container\">$nk$</span>, you will minimise <span class=\"math-container\">$\\operatorname{Var}(\\bar y)$</span> when <span class=\"math-container\">$k$</span> is as small as possible, i.e. when <span class=\"math-container\">$k=1$</span> and <span class=\"math-container\">$n=nk$</span>, at which point <span class=\"math-container\">$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$</span>, again bounded above by <span class=\"math-container\">$\\frac1{4n}$</span>. As discussed on <a href=\"https://stats.stackexchange.com/q/677226/2958\">your previous question</a>, having <span class=\"math-container\">$k=1$</span> would make it impossible to estimate <span class=\"math-container\">$\\alpha$</span> and <span class=\"math-container\">$\\beta$</span> separately.</p>\n<p>So using <span class=\"math-container\">$k=1$</span> together with <span class=\"math-container\">$n$</span> large enough to make <span class=\"math-container\">$\\frac1{4n}$</span> small enough to meet your needs as an upper bound for <span class=\"math-container\">$\\operatorname{Var}(\\bar y)$</span> should work well.</p>\n<hr />\n<p>Here is an illustrative simulation in R confirming these (with minor simulation noise) for <span class=\"math-container\">$\\alpha=2$</span>, <span class=\"math-container\">$\\beta=3$</span> and <span class=\"math-container\">$nk=12$</span></p>\n<pre><code>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</code></pre>\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"},"answer_scores":[{"answer_id":677267,"score":5},{"answer_id":677268,"score":4}],"answers":[{"answer_html":"<p>I would not go through mean and variance here. Your model for data generation is based on <span class=\"math-container\">$\\alpha$</span> and <span class=\"math-container\">$\\beta$</span> right? So why not work with them? Your population variable <span class=\"math-container\">$\\theta$</span>, 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 <span class=\"math-container\">$\\{\\theta_i\\}$</span>, are not independent variables, so you should not estimate them independently of each other.</p>\n<p>If I had a sample <span class=\"math-container\">$\\{y_{ij}\\}$</span> I would estimate it like this:</p>\n<ol>\n<li>Have variables <span class=\"math-container\">$u$</span>, <span class=\"math-container\">$v$</span>, and take <span class=\"math-container\">$\\frac{\\alpha}{\\alpha+\\beta}=expit\\left(u\\right)=\\frac{1}{1+\\exp\\left(-u\\right)}$</span>, <span class=\"math-container\">$\\alpha=softplus(v)=\\log\\left(1+\\exp(v)\\right)$</span></li>\n<li><span class=\"math-container\">$\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$</span></li>\n</ol>\n<p>Optimise jointly <span class=\"math-container\">$u,v$</span> (maximum likelihood).</p>\n<p>So your sample size calculation would be a wrap-around for this procedure, i.e. select, <span class=\"math-container\">$n, k$</span> etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when <span class=\"math-container\">$\\theta$</span> is close to the edges for the given variance (and thus cannot be treated as normal).</p>\n<hr />\n<p>If you want to stick to variance and mean, you should be honest with yourself and state <span class=\"math-container\">$\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$</span>. If you get reasonable numbers, good, if not then you know your approximation is not suitable</p>\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":"<p>I think you can find the mean and variance of <span class=\"math-container\">$\\bar y$</span> analytically. Clearly <span class=\"math-container\">$\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$</span> and, using the law of total variance <span class=\"math-container\">$$\\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}.$$</span></p>\n<p>Since <span class=\"math-container\">$\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$</span>, you can then say <span class=\"math-container\">$$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$</span></p>\n<p>For given <span class=\"math-container\">$nk$</span>, you will minimise <span class=\"math-container\">$\\operatorname{Var}(\\bar y)$</span> when <span class=\"math-container\">$k$</span> is as small as possible, i.e. when <span class=\"math-container\">$k=1$</span> and <span class=\"math-container\">$n=nk$</span>, at which point <span class=\"math-container\">$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$</span>, again bounded above by <span class=\"math-container\">$\\frac1{4n}$</span>. As discussed on <a href=\"https://stats.stackexchange.com/q/677226/2958\">your previous question</a>, having <span class=\"math-container\">$k=1$</span> would make it impossible to estimate <span class=\"math-container\">$\\alpha$</span> and <span class=\"math-container\">$\\beta$</span> separately.</p>\n<p>So using <span class=\"math-container\">$k=1$</span> together with <span class=\"math-container\">$n$</span> large enough to make <span class=\"math-container\">$\\frac1{4n}$</span> small enough to meet your needs as an upper bound for <span class=\"math-container\">$\\operatorname{Var}(\\bar y)$</span> should work well.</p>\n<hr />\n<p>Here is an illustrative simulation in R confirming these (with minor simulation noise) for <span class=\"math-container\">$\\alpha=2$</span>, <span class=\"math-container\">$\\beta=3$</span> and <span class=\"math-container\">$nk=12$</span></p>\n<pre><code>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</code></pre>\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"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Cryo","author_url":"https://stats.stackexchange.com/users/275239/cryo","content_license":"CC BY-SA 4.0","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"}],"source_url":"https://stats.stackexchange.com/a/677267"},{"author":"Henry","author_url":"https://stats.stackexchange.com/users/2958/henry","content_license":"CC BY-SA 4.0","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"}],"source_url":"https://stats.stackexchange.com/a/677268"}],"question_author":"adamkostanov","question_author_url":"https://stats.stackexchange.com/users/512554/adamkostanov"},"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","post_id":"stats: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","post_id":677268,"sha256":"1f520efb478c1a41ff425811f24e74461aaaf2f6cd8ba7834ea50d039660d1c6","source_url":"https://stats.stackexchange.com/a/677268"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"c5411ae39ba554450b6b3b2edef9e51b56c99ce766a9a447c37d80a7be04830f","id":"SCT-42d960c211f0e28649b827c9","language":["R"],"library_or_tool":null,"problem_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?","provenance":{"original_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"},"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_commit":"3f6db230c4afe97d558b23fe2bfdb56dc0010d95","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Statistics-QA","source_license":"CC BY-SA 4.0","source_record_id":"Scientific-Statistics-QA:stats:677266","source_record_sha256":"b82084e5d8e57f26e03b51c47a0e7301bc1d4f18e88c15d6d34084eca669e20d","source_url":"https://stats.stackexchange.com/questions/677266/how-to-set-up-a-simulation-study","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>Here is a hierarchical data generating process (DGP):</p>\n<blockquote>\n<p>(Population) Layer 1: <span class=\"math-container\">$$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$</span></p>\n<p>(Individual) Layer 2: <span class=\"math-container\">$$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$</span></p>\n</blockquote>\n<p><span class=\"math-container\">$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$</span></p>\n<p>Using a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of <span class=\"math-container\">$n$</span> and <span class=\"math-container\">$k$</span> I should select to get good results (I know this hugely subjective) such that <span class=\"math-container\">$nk$</span> is minimized (assume that increasing <span class=\"math-container\">$n$</span> by 1 costs the same as increase <span class=\"math-container\">$k$</span> by 1).</p>\n<p>After doing some research, it seems the best way to handle this question is by a simulation study. Assuming <span class=\"math-container\">$\\alpha,\\ \\beta$</span> are known, I could sample from the DGP for different combinations of <span class=\"math-container\">$n$</span> and <span class=\"math-container\">$k$</span> 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 <span class=\"math-container\">$n$</span> or <span class=\"math-container\">$k$</span>, 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.</p>\n<p>Here 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):</p>\n<pre><code>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<span class=\"math-container\">$mu[s]\n tau2 <- scenarios$</span>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</code></pre>\n<p>When visualized, the results look like this (direct upload was not working - however it seems to show that when <span class=\"math-container\">$n$</span> and <span class=\"math-container\">$k$</span> are both large, for many cases, we get high coverage and smaller CI lengths on average): <a href=\"https://imgur.com/a/tgHbtLz\" rel=\"nofollow noreferrer\">https://imgur.com/a/tgHbtLz</a></p>\n<p>The tricky part now is to try and guess what the true value of <span class=\"math-container\">$\\alpha,\\ \\beta$</span> might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what <span class=\"math-container\">$n,k$</span> to use if I want average CI length and average coverage rate to be within certain ranges.</p>\n<p>I am looking for feedback on my methodology. Should I have done this a different way?</p>\n","question_title":"How to set up a simulation study?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677266/how-to-set-up-a-simulation-study","split":"validation"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45441,"score":1}],"answers":[{"answer_html":"<p>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<a href=\"https://i.sstatic.net/9Qqv2fdK.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/9Qqv2fdK.jpg\" alt=\"enter image description here\" /></a></p>\n","answer_id":45441,"answer_text":"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[image: enter image description here; source: https://i.sstatic.net/9Qqv2fdK.jpg] (https://i.sstatic.net/9Qqv2fdK.jpg)","answer_url":"https://scicomp.stackexchange.com/a/45441","author":"Basham Govindan","author_url":"https://scicomp.stackexchange.com/users/41959/basham-govindan","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-05-05T09:13:01+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":45377,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Basham Govindan","profile_url":"https://scicomp.stackexchange.com/users/41959/basham-govindan","user_type":"registered"},"created_at":"2026-05-05T09:13:01+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"E5E280BD-52E3-4097-8B86-76EFC763D8A7","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E5E280BD-52E3-4097-8B86-76EFC763D8A7/view-source"}],"score":1,"updated_at":"2026-05-05T09:13:01+00:00"}],"attempted_method_if_explicit":"I tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.","author_attribution":{"answers":[{"author":"Basham Govindan","author_url":"https://scicomp.stackexchange.com/users/41959/basham-govindan","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Basham Govindan","profile_url":"https://scicomp.stackexchange.com/users/41959/basham-govindan","user_type":"registered"},"created_at":"2026-05-05T09:13:01+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"E5E280BD-52E3-4097-8B86-76EFC763D8A7","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E5E280BD-52E3-4097-8B86-76EFC763D8A7/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45441"}],"question_author":"Maroon Racoon","question_author_url":"https://scicomp.stackexchange.com/users/51966/maroon-racoon"},"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","post_id":"scicomp: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","post_id":"scicomp: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","post_id":"scicomp: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","post_id":"scicomp: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","post_id":"scicomp: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":"#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","post_id":"scicomp:45377","sha256":"8147137bfedb92889b148b03a5eff815652db6581b8332c2b2c8c350103daaa4","source_url":"https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"cc357211dee6b26e8f557f524542a04070eb4a56f8fd52554d6c7cd501771dd2","id":"SCT-47d4305d502f009a7408d81e","language":null,"library_or_tool":null,"problem_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 <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 }","provenance":{"original_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"},"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maroon Racoon","profile_url":"https://scicomp.stackexchange.com/users/51966/maroon-racoon","user_type":"registered"},"created_at":"2026-02-18T13:01:18+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"09701D0D-57FD-4430-8F2E-2E781ED01247","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/09701D0D-57FD-4430-8F2E-2E781ED01247/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maroon Racoon","profile_url":"https://scicomp.stackexchange.com/users/51966/maroon-racoon","user_type":"registered"},"created_at":"2026-02-18T15:47:31+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9CE08707-17D2-4B7A-9212-4CA82E4ABE1B","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9CE08707-17D2-4B7A-9212-4CA82E4ABE1B/view-source"}],"source_commit":null,"source_data_file":"native_scicomp_source.jsonl","source_dataset":"RegalFire/Scientific-Native-Scicomp","source_license":"CC BY-SA 4.0","source_record_id":"45377","source_record_sha256":"0e6e4be9e4d56155b1cbf127375f00b0ff15aa418f14b301fbdcbe0674f0ca6b","source_url":"https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:</p>\n<blockquote>\n<p><span class=\"math-container\">$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$</span> Pr = 7, Re = 7 Ra= 1e3, 1e4 <span class=\"math-container\">$\\ldots$</span>1e7.\nLeft and right walls are insulated. At the bottom wall <span class=\"math-container\">$q_1= 1000$</span> and at\nthe upper wall <span class=\"math-container\">$q_2=0.5*q_1$</span></p>\n</blockquote>\n<p>The temperature field generated by my cpp code was used on <em>SurferProgram</em> 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.</p>\n<p>The 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</p>\n<p>May be a problem when defining the heat flux in <code>solveTemperature</code> function. <strong>Shouldnt the isotherms be waivier?</strong> The walls are nonpermeable (no liquid passes trouht them).</p>\n<p>I tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n<a href=\"https://i.sstatic.net/Z4fMSBrm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/Z4fMSBrm.png\" alt=\"for Ra = 1e3\" /></a></p>\n<p>This image is for Ra = 1e7\n<a href=\"https://i.sstatic.net/4a2ls0zL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/4a2ls0zL.png\" alt=\"for Ra = 1e7\" /></a></p>\n<p>Here is the piece of code for calculating the temperatures</p>\n<pre><code> // 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</code></pre>\n<p>Vortex solver</p>\n<pre><code>// 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</code></pre>\n<p>Stream function solver</p>\n<pre><code>// 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</code></pre>\n<p>Velocity calculator</p>\n<pre><code>// 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</code></pre>\n<p>Setting boundary conditions</p>\n<pre><code> // 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</code></pre>\n<p>This is the main code</p>\n<pre><code>#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</code></pre>\n","question_title":"My code gives inverted temperatures for natural convection problem [C++]","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c","split":"validation"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45429,"score":3}],"answers":[{"answer_html":"<p>This method appears to be simply Implicit Euler but with broken error control and without any actual ability to measure or ensure convergence to the correct solution.</p>\n","answer_id":45429,"answer_text":"This method appears to be simply Implicit Euler but with broken error control and without any actual ability to measure or ensure convergence to the correct solution.","answer_url":"https://scicomp.stackexchange.com/a/45429","author":"Oscar Smith","author_url":"https://scicomp.stackexchange.com/users/33841/oscar-smith","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-04-05T17:38:55+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":45422,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Oscar Smith","profile_url":"https://scicomp.stackexchange.com/users/33841/oscar-smith","user_type":"registered"},"created_at":"2026-04-05T17:38:55+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"FF7D6040-9711-407E-AD44-F933FEAD971C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FF7D6040-9711-407E-AD44-F933FEAD971C/view-source"}],"score":3,"updated_at":"2026-04-05T17:38:55+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Oscar Smith","author_url":"https://scicomp.stackexchange.com/users/33841/oscar-smith","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Oscar Smith","profile_url":"https://scicomp.stackexchange.com/users/33841/oscar-smith","user_type":"registered"},"created_at":"2026-04-05T17:38:55+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"FF7D6040-9711-407E-AD44-F933FEAD971C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FF7D6040-9711-407E-AD44-F933FEAD971C/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45429"}],"question_author":"fethi gaouer","question_author_url":"https://scicomp.stackexchange.com/users/56574/fethi-gaouer"},"code_blocks":[{"block_index":0,"code_text":" ym′ = (ym−y1)/(tm-t1)\n","post_id":"scicomp:45422","sha256":"e07e5d9cced4d3b1bc6646e2641596d9caebc007aaf1bf6355da1c182c5aa594","source_url":"https://scicomp.stackexchange.com/questions/45422/stability-analysis-for-a-derivative-free-ode-solver-based-on-local-geodesic-inte"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":["Error: 1e-6","Error: 0.7% (finner subdivision gives 1e-7)"],"group_id":"3014f47fb8200d2bcf83ca0d38d8f9cf3c3d59b0ac10e380d1c170975f9bb81b","id":"SCT-b8e5514c6c9934e2a912d0f2","language":null,"library_or_tool":null,"problem_text":"We propose a numerical method for stiff ordinary differential equations (ODEs) based on a geometric transformation. The key ideas are:\n\n\n\n\n1-Local geodesic approximation – On a short interval [t1,t2] the solution is approximated by a geodesic in a non‑Euclidean metric space. This geodesic depends on a single free parameter: the value y2=y(t2).\n\n\n\n\n2-Calibration – For a given y2,the geodesic provides the midpoint\n\n\n\n\n(tm,ym). We then compute the derivative from the geodesic:\n\n\n\n\n ym′ = (ym−y1)/(tm-t1)\n\n\n\n\n\n\n\n\n\n\nand evaluate the ODE at the midpoint:\n\n\n\n\nfm =f(tm,ym).\nThe residual is\nR(y2 )=∣ ym′−fm ∣.\n\n\n\n\n3-Adjustment – Because the interval is short,\n\n\n\n\nR is nearly linear in y2 . A few secant iterations (or a simple manual search) suffice to make R negligible.\n\n\n\n\n4-Systems – For a system of ODEs we select one component (e.g.y2) as the only free parameter. The geodesic gives (tm,ym). The other components at the midpoint, as well as their derivatives, are then deduced from the equations and the initial conditions. The residual is built on the remaining equations.\n\n\n\n\n5-Long intervals – The total time interval is split into short segments where the curvature remains small. Each segment is treated independently using the same single‑parameter calibration.\n\n\n\n\n6-Spectral pre‑processing – A coarse scan of the ODE’s right‑hand side estimates the local curvature and detects stiff regions or fast oscillations. This helps choose an optimal segmentation without trial and error.\n\n\n\n\nWhy this method differs from classical ones:\n\n\n\n\nNo implicit solver, no Jacobian.\n\n\n\n\nStability is controlled by curvature, not by a CFL condition.\n\n\n\n\nOnly one scalar parameter is adjusted per segment, regardless of the system size.\n\n\n\n\nBenchmarks (performed in double precision, reference: Radau with tolerance 1e-12):\n\n\n\n\nProthero–Robinson\n\n\n\n\ny′ =−1000y+1000sint+cost with y(0.1)=sin(0.1)\n\nResult: y(0.101)≈0.10083089255\n\nError: 1e-6\n\n\n\n\nVan der Pol,\n\n\n\n\nε=1000, 8 segments from\n\nResult: y(0.248583)≈0.2477211\n\nError: 0.7% (finner subdivision gives 1e-7)\n\n\n\n\nLorenz system (single\nshort segment)\n\n\n\n\nResult: error on all variables\n\nError≈1e-7\n\n\n\n\nBrusselator (single segment)\n\n\n\n\nResult: residual on second equation\n\nerror: <1e-7\n\n\n\n\nQuestions to the community:\n\n\n\n\nAre there other stiff or multi‑scale benchmarks that you would recommend to test this approach further?\n\n\n\n\nHas a similar curvature‑based step control been studied elsewhere?\n\n\n\n\nWhat theoretical tools could help analyse the stability of such a method?","provenance":{"original_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"},"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"fethi gaouer","profile_url":"https://scicomp.stackexchange.com/users/56574/fethi-gaouer","user_type":"registered"},"created_at":"2026-04-01T19:04:02+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"C2B7F1EE-558E-4597-AEC8-AB9AD9D0D121","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C2B7F1EE-558E-4597-AEC8-AB9AD9D0D121/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"fethi gaouer","profile_url":"https://scicomp.stackexchange.com/users/56574/fethi-gaouer","user_type":"registered"},"created_at":"2026-04-05T08:48:09+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"EB6BC856-36CA-4681-8A08-B0FD3EB4B53F","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EB6BC856-36CA-4681-8A08-B0FD3EB4B53F/view-source"}],"source_commit":null,"source_data_file":"native_scicomp_source.jsonl","source_dataset":"RegalFire/Scientific-Native-Scicomp","source_license":"CC BY-SA 4.0","source_record_id":"45422","source_record_sha256":"7674d5bad612f19d4312ae4fee5c49dbe6db34cc7c64096e6c1b5eadad06c56b","source_url":"https://scicomp.stackexchange.com/questions/45422/stability-analysis-for-a-derivative-free-ode-solver-based-on-local-geodesic-inte","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>We propose a numerical method for stiff ordinary differential equations (ODEs) based on a geometric transformation. The key ideas are:</p>\n<p><strong>1-Local geodesic approximation</strong> – On a short interval [t1,t2] the solution is approximated by a geodesic in a non‑Euclidean metric space. This geodesic depends on a single free parameter: the value y2=y(t2).</p>\n<p><strong>2-Calibration</strong> – For a given y2,the geodesic provides the midpoint</p>\n<p>(tm,ym). We then compute the derivative from the geodesic:</p>\n<pre><code> ym′ = (ym−y1)/(tm-t1)\n</code></pre>\n<p></p>\n<p>and evaluate the ODE at the midpoint:</p>\n<p>fm =f(tm,ym).\nThe residual is\nR(y2 )=∣ ym′−fm ∣.</p>\n<p><strong>3-Adjustment</strong> – Because the interval is short,</p>\n<p>R is nearly linear in y2 . A few secant iterations (or a simple manual search) suffice to make R negligible.</p>\n<p><strong>4-Systems –</strong> For a system of ODEs we select one component (e.g.y2) as the only free parameter. The geodesic gives (tm,ym). The other components at the midpoint, as well as their derivatives, are then deduced from the equations and the initial conditions. The residual is built on the remaining equations.</p>\n<p><strong>5-Long intervals</strong> – The total time interval is split into short segments where the curvature remains small. Each segment is treated independently using the same single‑parameter calibration.</p>\n<p><strong>6-Spectral pre‑processing</strong> – A coarse scan of the ODE’s right‑hand side estimates the local curvature and detects stiff regions or fast oscillations. This helps choose an optimal segmentation without trial and error.</p>\n<p><strong>Why this method differs from classical ones:</strong></p>\n<p>No implicit solver, no Jacobian.</p>\n<p>Stability is controlled by curvature, not by a CFL condition.</p>\n<p>Only one scalar parameter is adjusted per segment, regardless of the system size.</p>\n<p><strong><strong>Benchmarks (performed in double precision, reference: Radau</strong> with tolerance 1e-12):</strong></p>\n<p><strong>Prothero–Robinson</strong></p>\n<p>y′ =−1000y+1000sint+cost with y(0.1)=sin(0.1)<br />\nResult: y(0.101)≈0.10083089255<br />\nError: 1e-6</p>\n<p><strong>Van der Pol,</strong></p>\n<p>ε=1000, 8 segments from<br />\nResult: y(0.248583)≈0.2477211<br />\nError: 0.7% (finner subdivision gives 1e-7)</p>\n<p><strong>Lorenz system</strong> (single\nshort segment)</p>\n<p>Result: error on all variables<br />\nError≈1e-7</p>\n<p><strong>Brusselator</strong> (single segment)</p>\n<p>Result: residual on second equation<br />\nerror: <1e-7</p>\n<p><strong>Questions to the community:</strong></p>\n<p>Are there other stiff or multi‑scale benchmarks that you would recommend to test this approach further?</p>\n<p>Has a similar curvature‑based step control been studied elsewhere?</p>\n<p>What theoretical tools could help analyse the stability of such a method?</p>\n","question_title":"Stability analysis for a derivative‑free ODE solver based on local geodesic interpolation","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45422/stability-analysis-for-a-derivative-free-ode-solver-based-on-local-geodesic-inte","split":"validation"}
|