{"accepted_answer":null,"answer_scores":[{"answer_id":112804,"score":5}],"answers":[{"answer_html":"

I know nothing about drug databases, but am familiar with Kegg. As far as I can see from the paper (and I may be wrong) The drug target database would contain the names of enzymes, the activity of which is affected by drugs. So the problem would seem to be to identify so-called Kegg ‘pathways’ in which these target enzymes occur.

\n

(I use the adjective “so-called” as Kegg pathways are not generally what a biochemist would regard as a pathway, but areas of metabolism. However this would not matter if all one is trying to do is find a correlation.)

\n

The poster would seem, therefore, to need to download a list of enzymes for each Kegg pathway. At one time all the Kegg information was available free of charge (I downloaded a considerable amount — although not the enzymes — to construct a relational database). However now one needs to purchase a license to do this — presumably what the authors of the paper did — at a cost of over $1000 pa.

\n

Unless one has grant funding or is independently wealthy, it would seem to be necessary to explore alternatives, such as MetaCyc (https://metacyc.org).

\n

Postscript\nThe addendum from the poster shows the UniProt IDs for the targets of the drug. These can be converted to Kegg IDs using the conversion tool on the Kegg site (https://www.genome.jp/kegg/tool/conv_id.html). The XML tag entitled “pathway” is not equivalent to a Kegg metabolic pathway as such, although the example seems to consist of proteins involved in blood clotting. If my interpretation is correct, it would be irrelevant to the procedure I suggest. However the original paper is sufficiently vague that I cannot be sure.

\n","answer_id":112804,"answer_text":"I know nothing about drug databases, but am familiar with Kegg. As far as I can see from the paper (and I may be wrong) The drug target database would contain the names of enzymes, the activity of which is affected by drugs. So the problem would seem to be to identify so-called Kegg ‘pathways’ in which these target enzymes occur.\n\n\n\n\n(I use the adjective “so-called” as Kegg pathways are not generally what a biochemist would regard as a pathway, but areas of metabolism. However this would not matter if all one is trying to do is find a correlation.)\n\n\n\n\nThe poster would seem, therefore, to need to download a list of enzymes for each Kegg pathway. At one time all the Kegg information was available free of charge (I downloaded a considerable amount — although not the enzymes — to construct a relational database). However now one needs to purchase a license to do this — presumably what the authors of the paper did — at a cost of over $1000 pa.\n\n\n\n\nUnless one has grant funding or is independently wealthy, it would seem to be necessary to explore alternatives, such as MetaCyc (https://metacyc.org (https://metacyc.org)).\n\n\n\n\nPostscript\nThe addendum from the poster shows the UniProt IDs for the targets of the drug. These can be converted to Kegg IDs using the conversion tool on the Kegg site (https://www.genome.jp/kegg/tool/conv_id.html (https://www.genome.jp/kegg/tool/conv_id.html)). The XML tag entitled “pathway” is not equivalent to a Kegg metabolic pathway as such, although the example seems to consist of proteins involved in blood clotting. If my interpretation is correct, it would be irrelevant to the procedure I suggest. However the original paper is sufficiently vague that I cannot be sure.","answer_url":"https://biology.stackexchange.com/a/112804","author":"David","author_url":"https://biology.stackexchange.com/users/22057/david","content_license":"CC BY-SA 4.0","created_at":"2023-08-13T11:37:13+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:38.885561+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/a145de97eabc007745b45919875489a41261075cbdf33d916d9640ba4ad0bd35_0.json","raw_sha256":"e7d8d4315eef8e039a452d2811869cbe305575c6ff8a6bef8f80d6dfb58c5bfd","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/112982;112980;112979;112977;112972;112967;112962;112956;112952;112948;112941;112938;112937;112936;112927;112925;112923;112919;112909;112905;112904;112898;112895;112893;112884;112881;112880;112879;112873;112872;112870;112869;112867;112850;112849;112848;112841;112835;112831;112824;112818;112811;112808;112807;112790;112789;112785;112777;112773;112770;112762;112759;112757;112756;112746;112739;112738;112737;112731;112705;112703;112700;112699;112698;112693;112691;112687;112685;112677;112671;112667;112663;112659;112653;112647;112646;112645;112636;112625;112621;112615;112614;112613;112610;112598;112593;112592;112586;112580;112575;112574;112564;112558;112552;112550;112549;112544;112539;112535;112531/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":112789,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-13T11:37:13+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D881A87-9785-460D-8B6A-4D609910C727","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D881A87-9785-460D-8B6A-4D609910C727/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-17T22:21:55+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"7E664EA3-F130-4C17-B518-C112CBD595B8","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/7E664EA3-F130-4C17-B518-C112CBD595B8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-18T07:26:03+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB/view-source"}],"score":5}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"David","author_url":"https://biology.stackexchange.com/users/22057/david","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-13T11:37:13+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D881A87-9785-460D-8B6A-4D609910C727","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D881A87-9785-460D-8B6A-4D609910C727/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-17T22:21:55+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"7E664EA3-F130-4C17-B518-C112CBD595B8","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/7E664EA3-F130-4C17-B518-C112CBD595B8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-18T07:26:03+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB/view-source"}],"source_url":"https://biology.stackexchange.com/a/112804"}],"question_author":"Orca","question_author_url":"https://biology.stackexchange.com/users/76494/orca"},"code_blocks":[{"block_index":0,"code_text":"\n \n SMP0000278\n Lepirudin Action Pathway\n drug_action\n \n \n DB00001\n Lepirudin\n \n \n DB01022\n Phylloquinone\n \n \n DB01373\n Calcium\n \n \n \n P00734\n P00748\n P02452\n P03952\n P03951\n P00740\n P00451\n P12259\n P00742\n P02671\n P02675\n P02679\n P00488\n P05160\n P00747\n P00750\n P08709\n P13726\n Q9BQB6\n P38435\n \n \n \n\n```\n","post_id":"112789","sha256":"4452dea3b66a2c29df5a54e5e802e54d6339b7f0a59f86f15142323a44138d31","source_url":"https://biology.stackexchange.com/questions/112789/how-to-generate-pathway-fingerprints-of-drugs"}],"content_license":"CC BY-SA 4.0","domain":"biology","error_text_if_explicit":null,"group_id":"21341a8f8da58f78f0df843bca6c30524caaad2ffd24c0988a87895e0f6d2c2c","id":"SCT-888cccfd7708642b5b451223","language":null,"library_or_tool":null,"problem_text":"I have studied a paper that constructs the pathway fingerprint of a drug, which has a vector of $0$ and $1$, and they compare the pathway fingerprint using a similarity measure to assess how similar the drugs are.\n\n\n\n\nBut I don't know where can I download pathways and how to generate their fingerprint vector to evaluate them. I checked KEGG website (https://www.genome.jp/kegg/) but could not find anything there to download. The paper can be downloaded from: https://pubmed.ncbi.nlm.nih.gov/22426982/ (https://pubmed.ncbi.nlm.nih.gov/22426982/)\n\n\n\n\nI really appreciate answers that can help me to solve the problem.\n\n\n\n\nUpdate\nSince i am not familiar with DrugBank and biology science, when I parsed the xml file of drugbank, I find a tag with name pathway . But i am not sure that do these elements show the pathway of drug or not? Is it possible to use them to construct the pathway fingerprint vector for drugs? what does P00734 mean?\n\n\n\n\nthis is the content of pathway tag for Lepirudin:\n\n\n\n\n\n \n SMP0000278\n Lepirudin Action Pathway\n drug_action\n \n \n DB00001\n Lepirudin\n \n \n DB01022\n Phylloquinone\n \n \n DB01373\n Calcium\n \n \n \n P00734\n P00748\n P02452\n P03952\n P03951\n P00740\n P00451\n P12259\n P00742\n P02671\n P02675\n P02679\n P00488\n P05160\n P00747\n P00750\n P08709\n P13726\n Q9BQB6\n P38435\n \n \n \n\n```","provenance":{"original_provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:12.794960+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/01e5186067e30dc1b8d7a145670ab7edd6b017797b271a481af8b7b7f55f13c2_0.json","raw_sha256":"6c3960de7e1d3d7920bb88d02e2184614c219b391f39d9bddc2a582fdc9a71e7","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=10&pagesize=100&site=biology&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":"Orca","profile_url":"https://biology.stackexchange.com/users/76494/orca","user_type":"registered"},"created_at":"2023-08-11T06:06:32+00:00","raw_file":"raw/codex_api_v1/fe6e1ab1e4f14040deb1423c04616e4dd0e7de39b583b42e88a31f79f9375e98_1790824028764975800_0.json","raw_sha256":"08e023ccc811ec000989abb19f483814e44277588eeabf130aa5dbaf177079bf","revision_guid":"98663075-01EA-4309-B06F-A662D694541F","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/98663075-01EA-4309-B06F-A662D694541F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Brendan Darrer","profile_url":"https://biology.stackexchange.com/users/35682/brendan-darrer","user_type":"registered"},"created_at":"2023-08-12T00:08:28+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"1A1830DF-479C-4EA6-8FAB-7D151F12D14C","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/1A1830DF-479C-4EA6-8FAB-7D151F12D14C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MattDMo","profile_url":"https://biology.stackexchange.com/users/948/mattdmo","user_type":"registered"},"created_at":"2023-08-12T00:08:28+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"797A7A2D-66A0-42C2-8856-C45C3E78810C","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/797A7A2D-66A0-42C2-8856-C45C3E78810C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Orca","profile_url":"https://biology.stackexchange.com/users/76494/orca","user_type":"registered"},"created_at":"2023-08-15T09:50:04+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"7F3B7812-28EA-4085-9361-2690329DB2A0","revision_number":4,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/7F3B7812-28EA-4085-9361-2690329DB2A0/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Orca","profile_url":"https://biology.stackexchange.com/users/76494/orca","user_type":"registered"},"created_at":"2023-08-15T10:09:44+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"51E7AEE3-B9D6-4FE6-AA59-BD33BD98B508","revision_number":5,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/51E7AEE3-B9D6-4FE6-AA59-BD33BD98B508/view-source"}],"source_commit":"049a9227f533c13bbc10d1a38c271e055da0ed6e","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Biology-QA","source_license":"CC BY-SA 4.0","source_record_id":"112789","source_record_sha256":"685fe6af1a44935ae67045a2635453e5e1c3363ca9a71cc98f94fdada045bbca","source_url":"https://biology.stackexchange.com/questions/112789/how-to-generate-pathway-fingerprints-of-drugs","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have studied a paper that constructs the pathway fingerprint of a drug, which has a vector of $0$ and $1$, and they compare the pathway fingerprint using a similarity measure to assess how similar the drugs are.

\n

But I don't know where can I download pathways and how to generate their fingerprint vector to evaluate them. I checked KEGG website but could not find anything there to download. The paper can be downloaded from: https://pubmed.ncbi.nlm.nih.gov/22426982/

\n

I really appreciate answers that can help me to solve the problem.

\n

Update\nSince i am not familiar with DrugBank and biology science, when I parsed the xml file of drugbank, I find a tag with name pathway . But i am not sure that do these elements show the pathway of drug or not? Is it possible to use them to construct the pathway fingerprint vector for drugs? what does <uniprot-id>P00734</uniprot-id> mean?

\n

this is the content of pathway tag for Lepirudin:

\n
<pathways>\n    <pathway>\n      <smpdb-id>SMP0000278</smpdb-id>\n      <name>Lepirudin Action Pathway</name>\n      <category>drug_action</category>\n      <drugs>\n        <drug>\n          <drugbank-id>DB00001</drugbank-id>\n          <name>Lepirudin</name>\n        </drug>\n        <drug>\n          <drugbank-id>DB01022</drugbank-id>\n          <name>Phylloquinone</name>\n        </drug>\n        <drug>\n          <drugbank-id>DB01373</drugbank-id>\n          <name>Calcium</name>\n        </drug>\n      </drugs>\n      <enzymes>\n        <uniprot-id>P00734</uniprot-id>\n        <uniprot-id>P00748</uniprot-id>\n        <uniprot-id>P02452</uniprot-id>\n        <uniprot-id>P03952</uniprot-id>\n        <uniprot-id>P03951</uniprot-id>\n        <uniprot-id>P00740</uniprot-id>\n        <uniprot-id>P00451</uniprot-id>\n        <uniprot-id>P12259</uniprot-id>\n        <uniprot-id>P00742</uniprot-id>\n        <uniprot-id>P02671</uniprot-id>\n        <uniprot-id>P02675</uniprot-id>\n        <uniprot-id>P02679</uniprot-id>\n        <uniprot-id>P00488</uniprot-id>\n        <uniprot-id>P05160</uniprot-id>\n        <uniprot-id>P00747</uniprot-id>\n        <uniprot-id>P00750</uniprot-id>\n        <uniprot-id>P08709</uniprot-id>\n        <uniprot-id>P13726</uniprot-id>\n        <uniprot-id>Q9BQB6</uniprot-id>\n        <uniprot-id>P38435</uniprot-id>\n      </enzymes>\n    </pathway>\n  </pathways>\n\n```\n
\n","question_title":"How to generate pathway fingerprints of drugs?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://biology.stackexchange.com/questions/112789/how-to-generate-pathway-fingerprints-of-drugs","split":"holdout"} {"accepted_answer":null,"answer_scores":[{"answer_id":115428,"score":2},{"answer_id":115542,"score":2}],"answers":[{"answer_html":"

I think that @David's comment is worth noting, but the error tells you where the issue is:

\n
“Atom” has no attribute “get_id”\n[snip]\nline 10, in <module> res_id = residue.get_id()[1]\n
\n

Looking at the pymol docs, it looks like what you are iterating over is atoms rather than residues. Atom objects don't have a get_id() method, so that's why it breaks.

\n

You should either figure out how to iterate over residues instead, or access the residue through the atom (possibly atom.resn , better atom.resi).

\n

Here are some examples that might come in handy.

\n","answer_id":115428,"answer_text":"I think that @David's comment is worth noting, but the error tells you where the issue is:\n\n\n\n\n“Atom” has no attribute “get_id”\n[snip]\nline 10, in res_id = residue.get_id()[1]\n\n\n\n\n\nLooking at the pymol docs (https://pymolwiki.org/index.php/Get_Model), it looks like what you are iterating over is atoms rather than residues. Atom objects don't have a get_id() method, so that's why it breaks.\n\n\n\n\nYou should either figure out how to iterate over residues instead, or access the residue through the atom (possibly atom.resn , better atom.resi).\n\n\n\n\nHere (https://www.blopig.com/blog/2019/08/how-to-iterate-in-pymol/) are some examples that might come in handy.","answer_url":"https://biology.stackexchange.com/a/115428","author":"Maximilian Press","author_url":"https://biology.stackexchange.com/users/22392/maximilian-press","content_license":"CC BY-SA 4.0","created_at":"2024-10-02T20:15:52+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:25.304620+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/7fe0b66593eb4c0f175024453138b8bd50811f1580a079ffb990af38e09cd1cf_0.json","raw_sha256":"b0a655f3b4c9626cf981180b3ac018a4a26330c5ab9b925b3df78bedd8169a84","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/115493;115490;115488;115483;115479;115477;115456;115453;115452;115447;115445;115444;115436;115431;115427;115413;115404;115403;115396;115391;115389;115388;115386;115383;115382;115379;115367;115365;115355;115340;115334;115328;115321;115314;115309;115304;115296;115295;115292;115283;115272;115270;115269;115265;115264;115260;115255;115252;115243;115235;115233;115225;115218;115215;115214;115213;115207;115204;115179;115177;115170;115167;115165;115164;115154;115149;115137;115131;115129;115115;115107;115099;115095;115094;115093;115085;115082;115081;115077;115076;115075;115074;115073;115072;115063;115044;115039;115035;115030;115025;115022;115019;115016;115012;115003;115002;114997;114993;114991;114987/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":115427,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2024-10-02T20:15:52+00:00","raw_file":"raw/codex_api_v1/43e0404e391fda3d45541a0db7438bd3a1c2df66d07b9f1a745a1d6a3713c815_1790824097103199200_0.json","raw_sha256":"e55dfe05ee755247d42e0fe87b0ef88822dd9b82f6af36ed5017c907e0ff3823","revision_guid":"41C50A69-CED9-4D24-A8DA-92C3C02BD6BE","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/41C50A69-CED9-4D24-A8DA-92C3C02BD6BE/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"pippo1980","profile_url":"https://biology.stackexchange.com/users/68984/pippo1980","user_type":"registered"},"created_at":"2024-10-24T20:14:59+00:00","raw_file":"raw/codex_api_v1/43e0404e391fda3d45541a0db7438bd3a1c2df66d07b9f1a745a1d6a3713c815_1790824097103199200_0.json","raw_sha256":"e55dfe05ee755247d42e0fe87b0ef88822dd9b82f6af36ed5017c907e0ff3823","revision_guid":"B180B2C1-99AC-4B3C-AB1D-B6A94D18299C","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/B180B2C1-99AC-4B3C-AB1D-B6A94D18299C/view-source"}],"score":2},{"answer_html":"

my attempt , input is protein Acb1 from 7t27.pdb ;

\n

code :

\n
from pymol import cmd, stored\nimport pymol\nimport time\n\npymol.finish_launching()\ntime.sleep(3)\n\n\nprint('\\n\\n------------------------------------------------')\nprint('\\n  PyMOL Version : ',  cmd.get_version()[0])\nprint('\\n\\n------------------------------------------------')\n\n# protein = "Acb1"\ncmd.load('7t27.pdb' , 'Acb1')\ncmd.remove("not chain A and not residue ECI")\ncmd.remove('solvent')\ncmd.select("eci_residues", "chain A and resn ECI")\neci_residues ="eci_residues"\ncmd.select("binding_residues", "byres {} around {}".format(eci_residues, "3")) ### changed from # cmd.select("binding_residues", "byres (eci_residue around 5))")\n  \ndef muta(resi, res_name):\n    print('\\n resi : ', resi, '  resn : ', res_name)\n    if res_name == "ALA":\n        cmd.wizard("mutagenesis")\n        cmd.do("refresh_wizard")\n        cmd.get_wizard().set_mode("TRP")\n        # cmd.get_wizard().do_select('A/'+resi+"/")\n        cmd.get_wizard().do_select(resi+"/")\n        # cmd.frame(1) ### rotamer selection ?? check if rotamer exist\n        print('before apply !!!!!!!!!!!!!')\n        cmd.get_wizard().apply()\n        cmd.wizard() # ends wizard\n        print('mutated !!!!!!!!!!!!!')\n    else:\n        pass\n  \nstored.residues = dict()\n\ncmd.iterate('binding_residues', 'stored.residues[resi] = resn')\n\nprint('\\n\\n residues : \\n', stored.residues , 'lenght : ', len(stored.residues))\n   \nfor resi ,resn in stored.residues.items():\n    \n    # print('resi : ', resi ,'  resn : ', resn)\n    muta(resi,resn)\n\nstored.residues = dict()\n\ncmd.iterate('binding_residues', 'stored.residues[resi] = resn')\n\nprint('\\n\\n residues : \\n', stored.residues , 'lenght : ', len(stored.residues))\n\ncmd.delete("binding_residues")\n
\n

output result:

\n
------------------------------------------------\n\n  PyMOL Version :  2.3.0\n\n\n------------------------------------------------\n\n\n residues : \n {'4': 'TYR', '36': 'HIS', '38': 'THR', '41': 'TYR', '66': 'PHE', '68': 'THR', '69': 'GLN', '74': 'ALA', '100': 'TYR', '104': 'ARG', '106': 'HIS', '108': 'THR', '111': 'TYR', '134': 'GLU', '135': 'GLU', '136': 'LEU', '137': 'ASP', '140': 'TRP', '202': 'SO4'} lenght :  19\n\n resi :  4   resn :  TYR\n\n resi :  36   resn :  HIS\n\n resi :  38   resn :  THR\n\n resi :  41   resn :  TYR\n\n resi :  66   resn :  PHE\n\n resi :  68   resn :  THR\n\n resi :  69   resn :  GLN\n\n resi :  74   resn :  ALA\nPyMOL>refresh_wizard\nSelected!\n ExecutiveRMS: RMSD =    0.022 (4 to 4 atoms)\n Mutagenesis: 7 rotamers loaded.\nbefore apply !!!!!!!!!!!!!\nmutated !!!!!!!!!!!!!\n\n resi :  100   resn :  TYR\n\n resi :  104   resn :  ARG\n\n resi :  106   resn :  HIS\n\n resi :  108   resn :  THR\n\n resi :  111   resn :  TYR\n\n resi :  134   resn :  GLU\n\n resi :  135   resn :  GLU\n\n resi :  136   resn :  LEU\n\n resi :  137   resn :  ASP\n\n resi :  140   resn :  TRP\n\n resi :  202   resn :  SO4\n\n\n residues : \n {'4': 'TYR', '36': 'HIS', '38': 'THR', '41': 'TYR', '66': 'PHE', '68': 'THR', '69': 'GLN', '74': 'TRP', '100': 'TYR', '104': 'ARG', '106': 'HIS', '108': 'THR', '111': 'TYR', '134': 'GLU', '135': 'GLU', '136': 'LEU', '137': 'ASP', '140': 'TRP', '202': 'SO4'} lenght :  19\n
\n

it does 74 ALA ---> 74 TRP :

\n

\"enter

\n

######################################################

\n

Second Script using the cmd.get_model(string "selection", integer "state" ) :

\n
from pymol import cmd\nimport pymol\nimport time\n\npymol.finish_launching()\ntime.sleep(3)\n\nprint('\\n\\n------------------------------------------------')\nprint('\\n  PyMOL Version : ',  cmd.get_version()[0])\nprint('\\n\\n------------------------------------------------')\n\ncmd.load('7t27.pdb' , 'Acb1')\ncmd.remove('solvent')\ncmd.remove("not chain A and not residue ECI")\ncmd.select("eci_residue", "chain A and resn ECI")\ncmd.select("binding_residues", "byres eci_residue around 5") \nprotein = "Acb1"\n\nprint('***' , cmd.get_names('objects' , selection='binding_residues'))\n\nfor residue in cmd.get_model("binding_residues").atom:\n    cmd.copy("Acb1_copy", "Acb1")\n    print('residue , type(residue', residue , type(residue), residue.id , residue.index , residue.resn , residue.resi)\n    # res_id = residue.get_id()[1]    ##### AttributeError: 'Atom' object has no attribute 'get_id'\n    res_id = residue.resi\n    res_name = residue.resn\n    protein = "Acb1"\n   \n    if res_name == "ALA":\n        \n        print('++++++++++++++++++++++++++++++++++++++++++')\n        cmd.wizard("mutagenesis")\n        cmd.do("refresh_wizard")\n        cmd.get_wizard().set_mode("SER")\n        cmd.get_wizard().do_select(f"Acb1_copy//A/{res_id}/")\n        cmd.get_wizard().apply()\n        cmd.wizard()\n        \n        cmd.save(f"{protein}_{res_id}.pdb", 'Acb1_copy')\n        \n        cmd.delete('Acb1_copy')\n        \n    else:\n        \n        pass\n
\n

It does iterate over atoms so the same output file, is overwritten more than once.

\n

The output file Acb1_74.pdb contains the original protein where

\n

the Alanine 74 , the only closer than 5A to ECI ligand is mutated to Serine (yellow original , blue mutated):

\n

\"enter

\n","answer_id":115542,"answer_text":"my attempt , input is protein Acb1 from 7t27.pdb (https://www.rcsb.org/structure/7T27) ;\n\n\n\n\ncode :\n\n\n\n\nfrom pymol import cmd, stored\nimport pymol\nimport time\n\npymol.finish_launching()\ntime.sleep(3)\n\n\nprint('\\n\\n------------------------------------------------')\nprint('\\n PyMOL Version : ', cmd.get_version()[0])\nprint('\\n\\n------------------------------------------------')\n\n# protein = \"Acb1\"\ncmd.load('7t27.pdb' , 'Acb1')\ncmd.remove(\"not chain A and not residue ECI\")\ncmd.remove('solvent')\ncmd.select(\"eci_residues\", \"chain A and resn ECI\")\neci_residues =\"eci_residues\"\ncmd.select(\"binding_residues\", \"byres {} around {}\".format(eci_residues, \"3\")) ### changed from # cmd.select(\"binding_residues\", \"byres (eci_residue around 5))\")\n \ndef muta(resi, res_name):\n print('\\n resi : ', resi, ' resn : ', res_name)\n if res_name == \"ALA\":\n cmd.wizard(\"mutagenesis\")\n cmd.do(\"refresh_wizard\")\n cmd.get_wizard().set_mode(\"TRP\")\n # cmd.get_wizard().do_select('A/'+resi+\"/\")\n cmd.get_wizard().do_select(resi+\"/\")\n # cmd.frame(1) ### rotamer selection ?? check if rotamer exist\n print('before apply !!!!!!!!!!!!!')\n cmd.get_wizard().apply()\n cmd.wizard() # ends wizard\n print('mutated !!!!!!!!!!!!!')\n else:\n pass\n \nstored.residues = dict()\n\ncmd.iterate('binding_residues', 'stored.residues[resi] = resn')\n\nprint('\\n\\n residues : \\n', stored.residues , 'lenght : ', len(stored.residues))\n \nfor resi ,resn in stored.residues.items():\n \n # print('resi : ', resi ,' resn : ', resn)\n muta(resi,resn)\n\nstored.residues = dict()\n\ncmd.iterate('binding_residues', 'stored.residues[resi] = resn')\n\nprint('\\n\\n residues : \\n', stored.residues , 'lenght : ', len(stored.residues))\n\ncmd.delete(\"binding_residues\")\n\n\n\n\n\noutput result:\n\n\n\n\n------------------------------------------------\n\n PyMOL Version : 2.3.0\n\n\n------------------------------------------------\n\n\n residues : \n {'4': 'TYR', '36': 'HIS', '38': 'THR', '41': 'TYR', '66': 'PHE', '68': 'THR', '69': 'GLN', '74': 'ALA', '100': 'TYR', '104': 'ARG', '106': 'HIS', '108': 'THR', '111': 'TYR', '134': 'GLU', '135': 'GLU', '136': 'LEU', '137': 'ASP', '140': 'TRP', '202': 'SO4'} lenght : 19\n\n resi : 4 resn : TYR\n\n resi : 36 resn : HIS\n\n resi : 38 resn : THR\n\n resi : 41 resn : TYR\n\n resi : 66 resn : PHE\n\n resi : 68 resn : THR\n\n resi : 69 resn : GLN\n\n resi : 74 resn : ALA\nPyMOL>refresh_wizard\nSelected!\n ExecutiveRMS: RMSD = 0.022 (4 to 4 atoms)\n Mutagenesis: 7 rotamers loaded.\nbefore apply !!!!!!!!!!!!!\nmutated !!!!!!!!!!!!!\n\n resi : 100 resn : TYR\n\n resi : 104 resn : ARG\n\n resi : 106 resn : HIS\n\n resi : 108 resn : THR\n\n resi : 111 resn : TYR\n\n resi : 134 resn : GLU\n\n resi : 135 resn : GLU\n\n resi : 136 resn : LEU\n\n resi : 137 resn : ASP\n\n resi : 140 resn : TRP\n\n resi : 202 resn : SO4\n\n\n residues : \n {'4': 'TYR', '36': 'HIS', '38': 'THR', '41': 'TYR', '66': 'PHE', '68': 'THR', '69': 'GLN', '74': 'TRP', '100': 'TYR', '104': 'ARG', '106': 'HIS', '108': 'THR', '111': 'TYR', '134': 'GLU', '135': 'GLU', '136': 'LEU', '137': 'ASP', '140': 'TRP', '202': 'SO4'} lenght : 19\n\n\n\n\n\nit does 74 ALA ---> 74 TRP :\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/vTQeAnPo.png] (https://i.sstatic.net/vTQeAnPo.png)\n\n\n\n\n######################################################\n\n\n\n\nSecond Script using the cmd.get_model(string \"selection\", integer \"state\" ) (https://pymolwiki.org/index.php/Get_Model) :\n\n\n\n\nfrom pymol import cmd\nimport pymol\nimport time\n\npymol.finish_launching()\ntime.sleep(3)\n\nprint('\\n\\n------------------------------------------------')\nprint('\\n PyMOL Version : ', cmd.get_version()[0])\nprint('\\n\\n------------------------------------------------')\n\ncmd.load('7t27.pdb' , 'Acb1')\ncmd.remove('solvent')\ncmd.remove(\"not chain A and not residue ECI\")\ncmd.select(\"eci_residue\", \"chain A and resn ECI\")\ncmd.select(\"binding_residues\", \"byres eci_residue around 5\") \nprotein = \"Acb1\"\n\nprint('***' , cmd.get_names('objects' , selection='binding_residues'))\n\nfor residue in cmd.get_model(\"binding_residues\").atom:\n cmd.copy(\"Acb1_copy\", \"Acb1\")\n print('residue , type(residue', residue , type(residue), residue.id , residue.index , residue.resn , residue.resi)\n # res_id = residue.get_id()[1] ##### AttributeError: 'Atom' object has no attribute 'get_id'\n res_id = residue.resi\n res_name = residue.resn\n protein = \"Acb1\"\n \n if res_name == \"ALA\":\n \n print('++++++++++++++++++++++++++++++++++++++++++')\n cmd.wizard(\"mutagenesis\")\n cmd.do(\"refresh_wizard\")\n cmd.get_wizard().set_mode(\"SER\")\n cmd.get_wizard().do_select(f\"Acb1_copy//A/{res_id}/\")\n cmd.get_wizard().apply()\n cmd.wizard()\n \n cmd.save(f\"{protein}_{res_id}.pdb\", 'Acb1_copy')\n \n cmd.delete('Acb1_copy')\n \n else:\n \n pass\n\n\n\n\n\nIt does iterate over atoms so the same output file, is overwritten more than once.\n\n\n\n\nThe output file Acb1_74.pdb contains the original protein where\n\n\n\n\nthe Alanine 74 , the only closer than 5A to ECI ligand is mutated to Serine (yellow original , blue mutated):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/y5DxbP0w.png] (https://i.sstatic.net/y5DxbP0w.png)","answer_url":"https://biology.stackexchange.com/a/115542","author":"pippo1980","author_url":"https://biology.stackexchange.com/users/68984/pippo1980","content_license":"CC BY-SA 4.0","created_at":"2024-10-24T15:23:43+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:26.693224+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/202c0322d4dfac9d4b1c407daba4209579e5cfe73de17e5d578734e1f3315727_0.json","raw_sha256":"63f5bd02e37151da0b36b32c57da219bbcfbb084387a964a28411ca327805827","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/115493;115490;115488;115483;115479;115477;115456;115453;115452;115447;115445;115444;115436;115431;115427;115413;115404;115403;115396;115391;115389;115388;115386;115383;115382;115379;115367;115365;115355;115340;115334;115328;115321;115314;115309;115304;115296;115295;115292;115283;115272;115270;115269;115265;115264;115260;115255;115252;115243;115235;115233;115225;115218;115215;115214;115213;115207;115204;115179;115177;115170;115167;115165;115164;115154;115149;115137;115131;115129;115115;115107;115099;115095;115094;115093;115085;115082;115081;115077;115076;115075;115074;115073;115072;115063;115044;115039;115035;115030;115025;115022;115019;115016;115012;115003;115002;114997;114993;114991;114987/answers?filter=withbody&order=asc&page=2&pagesize=100&site=biology&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":115427,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"pippo1980","profile_url":"https://biology.stackexchange.com/users/68984/pippo1980","user_type":"registered"},"created_at":"2024-10-24T15:23:43+00:00","raw_file":"raw/codex_api_v1/fb80d81a1c70306a433c194be5c69283394737e480e8a1af86817861a93350f3_1790824106677381800_0.json","raw_sha256":"b7384c2681ecb308baf2a286966aa4a5b1b0bd51b1336b06545b82d1c7eda92a","revision_guid":"B6DEA66C-1DBF-40F2-B0B0-752DEA742A14","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/B6DEA66C-1DBF-40F2-B0B0-752DEA742A14/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2024-10-24T21:05:34+00:00","raw_file":"raw/codex_api_v1/fb80d81a1c70306a433c194be5c69283394737e480e8a1af86817861a93350f3_1790824106677381800_0.json","raw_sha256":"b7384c2681ecb308baf2a286966aa4a5b1b0bd51b1336b06545b82d1c7eda92a","revision_guid":"065D30A9-B82F-4D85-8DE9-8144EAD3AB90","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/065D30A9-B82F-4D85-8DE9-8144EAD3AB90/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"pippo1980","profile_url":"https://biology.stackexchange.com/users/68984/pippo1980","user_type":"registered"},"created_at":"2024-10-24T21:24:11+00:00","raw_file":"raw/codex_api_v1/fb80d81a1c70306a433c194be5c69283394737e480e8a1af86817861a93350f3_1790824106677381800_0.json","raw_sha256":"b7384c2681ecb308baf2a286966aa4a5b1b0bd51b1336b06545b82d1c7eda92a","revision_guid":"8BDA4888-898D-4A0B-BFF4-9D9B64C7F94C","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/8BDA4888-898D-4A0B-BFF4-9D9B64C7F94C/view-source"}],"score":2}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Maximilian Press","author_url":"https://biology.stackexchange.com/users/22392/maximilian-press","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2024-10-02T20:15:52+00:00","raw_file":"raw/codex_api_v1/43e0404e391fda3d45541a0db7438bd3a1c2df66d07b9f1a745a1d6a3713c815_1790824097103199200_0.json","raw_sha256":"e55dfe05ee755247d42e0fe87b0ef88822dd9b82f6af36ed5017c907e0ff3823","revision_guid":"41C50A69-CED9-4D24-A8DA-92C3C02BD6BE","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/41C50A69-CED9-4D24-A8DA-92C3C02BD6BE/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"pippo1980","profile_url":"https://biology.stackexchange.com/users/68984/pippo1980","user_type":"registered"},"created_at":"2024-10-24T20:14:59+00:00","raw_file":"raw/codex_api_v1/43e0404e391fda3d45541a0db7438bd3a1c2df66d07b9f1a745a1d6a3713c815_1790824097103199200_0.json","raw_sha256":"e55dfe05ee755247d42e0fe87b0ef88822dd9b82f6af36ed5017c907e0ff3823","revision_guid":"B180B2C1-99AC-4B3C-AB1D-B6A94D18299C","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/B180B2C1-99AC-4B3C-AB1D-B6A94D18299C/view-source"}],"source_url":"https://biology.stackexchange.com/a/115428"},{"author":"pippo1980","author_url":"https://biology.stackexchange.com/users/68984/pippo1980","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"pippo1980","profile_url":"https://biology.stackexchange.com/users/68984/pippo1980","user_type":"registered"},"created_at":"2024-10-24T15:23:43+00:00","raw_file":"raw/codex_api_v1/fb80d81a1c70306a433c194be5c69283394737e480e8a1af86817861a93350f3_1790824106677381800_0.json","raw_sha256":"b7384c2681ecb308baf2a286966aa4a5b1b0bd51b1336b06545b82d1c7eda92a","revision_guid":"B6DEA66C-1DBF-40F2-B0B0-752DEA742A14","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/B6DEA66C-1DBF-40F2-B0B0-752DEA742A14/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2024-10-24T21:05:34+00:00","raw_file":"raw/codex_api_v1/fb80d81a1c70306a433c194be5c69283394737e480e8a1af86817861a93350f3_1790824106677381800_0.json","raw_sha256":"b7384c2681ecb308baf2a286966aa4a5b1b0bd51b1336b06545b82d1c7eda92a","revision_guid":"065D30A9-B82F-4D85-8DE9-8144EAD3AB90","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/065D30A9-B82F-4D85-8DE9-8144EAD3AB90/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"pippo1980","profile_url":"https://biology.stackexchange.com/users/68984/pippo1980","user_type":"registered"},"created_at":"2024-10-24T21:24:11+00:00","raw_file":"raw/codex_api_v1/fb80d81a1c70306a433c194be5c69283394737e480e8a1af86817861a93350f3_1790824106677381800_0.json","raw_sha256":"b7384c2681ecb308baf2a286966aa4a5b1b0bd51b1336b06545b82d1c7eda92a","revision_guid":"8BDA4888-898D-4A0B-BFF4-9D9B64C7F94C","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/8BDA4888-898D-4A0B-BFF4-9D9B64C7F94C/view-source"}],"source_url":"https://biology.stackexchange.com/a/115542"}],"question_author":"Shayan Joarder","question_author_url":"https://biology.stackexchange.com/users/89401/shayan-joarder"},"code_blocks":[{"block_index":0,"code_text":"“Atom” has no attribute “get_id” File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pmg_qt\\pymol_qt_gui.py\", line 1192, in file_run self.cmd.run(fname) File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py\", line 470, in run run_(path, ns_pymol, ns_pymol) File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py\", line 519, in run_file execfile(file,global_ns,local_ns) File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py\", line 514, in execfile exec(co, global_ns, local_ns) File \"C:/Users/will/PycharmProjects/Binding Residues/bindingresidue.py\", line 10, in res_id = residue.get_id()[1]\n","post_id":"115427","sha256":"ce05de15b4645358553920bb6f256e261598708e93c7bc3a46c16fb5d777bc7a","source_url":"https://biology.stackexchange.com/questions/115427/how-to-select-residues-in-a-selection-for-protein-mutagenesis-in-pymol"},{"block_index":1,"code_text":"from pymol import cmd\n\n\ncmd.load(r\"C:\\Users\\will\\.pymol\\Acb1test.pdb\", \"Acb1\")\ncmd.remove(\"not chain A and not residue ECI\")\ncmd.select(\"eci_residue\", \"chain A and resn ECI\")\ncmd.select(\"binding_residues\", \"(byres (eci_residue around 5))\")\nprotein = \"Acb1\"\n\n\nfor residue in cmd.get_model(\"binding_residues\").atom:\n res_id = residue.get_id()[1]\n res_name = residue.get_parent().get_resname()\n\n\n if res_name == \"ALA\":\n cmd.wizard(\"mutagenesis\")\n cmd.wizard().set_mode(\"ser\")\n cmd.get_wizard().do_select(f\"chain A and residue{res_id}\")\n cmd.get_wizard().apply()\n else:\n cmd.wizard(\"mutagenesis\")\n cmd.get_wizard().set_mode(\"ala\")\n cmd.get_wizard().do_select(f\"chain A and residue{res_id}\")\n cmd.get_wizard().apply()\n\n\n cmd.save(r\"C:\\Users\\will\\Acb1test\\{protein}_{res_id}.pdb\")\n cmd.reinitialize()\n cmd.load(r\"C:\\Users\\will\\.pymol\\Acb1test.pdb\", \"Acb1\")\n cmd.remove(\"not chain A and not residue ECI\")\n cmd.select(\"binding_residues\", \"br. (byres (residue ECI around 5))\")\n\ncmd.delete(\"binding_residues\")\n","post_id":"115427","sha256":"3b951207027fa9c1ee1019fff7837108ce97006cedbb06f0c1415700c7bf65ff","source_url":"https://biology.stackexchange.com/questions/115427/how-to-select-residues-in-a-selection-for-protein-mutagenesis-in-pymol"},{"block_index":0,"code_text":"“Atom” has no attribute “get_id”\n[snip]\nline 10, in res_id = residue.get_id()[1]\n","post_id":115428,"sha256":"0cc1c0983b2af21b0591740d1012cd8f4d28882ea051dc8ab3ff8b44232e8c51","source_url":"https://biology.stackexchange.com/a/115428"},{"block_index":0,"code_text":"from pymol import cmd, stored\nimport pymol\nimport time\n\npymol.finish_launching()\ntime.sleep(3)\n\n\nprint('\\n\\n------------------------------------------------')\nprint('\\n PyMOL Version : ', cmd.get_version()[0])\nprint('\\n\\n------------------------------------------------')\n\n# protein = \"Acb1\"\ncmd.load('7t27.pdb' , 'Acb1')\ncmd.remove(\"not chain A and not residue ECI\")\ncmd.remove('solvent')\ncmd.select(\"eci_residues\", \"chain A and resn ECI\")\neci_residues =\"eci_residues\"\ncmd.select(\"binding_residues\", \"byres {} around {}\".format(eci_residues, \"3\")) ### changed from # cmd.select(\"binding_residues\", \"byres (eci_residue around 5))\")\n \ndef muta(resi, res_name):\n print('\\n resi : ', resi, ' resn : ', res_name)\n if res_name == \"ALA\":\n cmd.wizard(\"mutagenesis\")\n cmd.do(\"refresh_wizard\")\n cmd.get_wizard().set_mode(\"TRP\")\n # cmd.get_wizard().do_select('A/'+resi+\"/\")\n cmd.get_wizard().do_select(resi+\"/\")\n # cmd.frame(1) ### rotamer selection ?? check if rotamer exist\n print('before apply !!!!!!!!!!!!!')\n cmd.get_wizard().apply()\n cmd.wizard() # ends wizard\n print('mutated !!!!!!!!!!!!!')\n else:\n pass\n \nstored.residues = dict()\n\ncmd.iterate('binding_residues', 'stored.residues[resi] = resn')\n\nprint('\\n\\n residues : \\n', stored.residues , 'lenght : ', len(stored.residues))\n \nfor resi ,resn in stored.residues.items():\n \n # print('resi : ', resi ,' resn : ', resn)\n muta(resi,resn)\n\nstored.residues = dict()\n\ncmd.iterate('binding_residues', 'stored.residues[resi] = resn')\n\nprint('\\n\\n residues : \\n', stored.residues , 'lenght : ', len(stored.residues))\n\ncmd.delete(\"binding_residues\")\n","post_id":115542,"sha256":"b3fd9f4ebc65a8f20076b5adb7105d641bf4c0ab1594774b47e6241fe5d1c206","source_url":"https://biology.stackexchange.com/a/115542"},{"block_index":1,"code_text":"------------------------------------------------\n\n PyMOL Version : 2.3.0\n\n\n------------------------------------------------\n\n\n residues : \n {'4': 'TYR', '36': 'HIS', '38': 'THR', '41': 'TYR', '66': 'PHE', '68': 'THR', '69': 'GLN', '74': 'ALA', '100': 'TYR', '104': 'ARG', '106': 'HIS', '108': 'THR', '111': 'TYR', '134': 'GLU', '135': 'GLU', '136': 'LEU', '137': 'ASP', '140': 'TRP', '202': 'SO4'} lenght : 19\n\n resi : 4 resn : TYR\n\n resi : 36 resn : HIS\n\n resi : 38 resn : THR\n\n resi : 41 resn : TYR\n\n resi : 66 resn : PHE\n\n resi : 68 resn : THR\n\n resi : 69 resn : GLN\n\n resi : 74 resn : ALA\nPyMOL>refresh_wizard\nSelected!\n ExecutiveRMS: RMSD = 0.022 (4 to 4 atoms)\n Mutagenesis: 7 rotamers loaded.\nbefore apply !!!!!!!!!!!!!\nmutated !!!!!!!!!!!!!\n\n resi : 100 resn : TYR\n\n resi : 104 resn : ARG\n\n resi : 106 resn : HIS\n\n resi : 108 resn : THR\n\n resi : 111 resn : TYR\n\n resi : 134 resn : GLU\n\n resi : 135 resn : GLU\n\n resi : 136 resn : LEU\n\n resi : 137 resn : ASP\n\n resi : 140 resn : TRP\n\n resi : 202 resn : SO4\n\n\n residues : \n {'4': 'TYR', '36': 'HIS', '38': 'THR', '41': 'TYR', '66': 'PHE', '68': 'THR', '69': 'GLN', '74': 'TRP', '100': 'TYR', '104': 'ARG', '106': 'HIS', '108': 'THR', '111': 'TYR', '134': 'GLU', '135': 'GLU', '136': 'LEU', '137': 'ASP', '140': 'TRP', '202': 'SO4'} lenght : 19\n","post_id":115542,"sha256":"49bda429f456094cd7a5df87d28ca2b798d0f937e3558ae19f07db1d589601ef","source_url":"https://biology.stackexchange.com/a/115542"},{"block_index":2,"code_text":"from pymol import cmd\nimport pymol\nimport time\n\npymol.finish_launching()\ntime.sleep(3)\n\nprint('\\n\\n------------------------------------------------')\nprint('\\n PyMOL Version : ', cmd.get_version()[0])\nprint('\\n\\n------------------------------------------------')\n\ncmd.load('7t27.pdb' , 'Acb1')\ncmd.remove('solvent')\ncmd.remove(\"not chain A and not residue ECI\")\ncmd.select(\"eci_residue\", \"chain A and resn ECI\")\ncmd.select(\"binding_residues\", \"byres eci_residue around 5\") \nprotein = \"Acb1\"\n\nprint('***' , cmd.get_names('objects' , selection='binding_residues'))\n\nfor residue in cmd.get_model(\"binding_residues\").atom:\n cmd.copy(\"Acb1_copy\", \"Acb1\")\n print('residue , type(residue', residue , type(residue), residue.id , residue.index , residue.resn , residue.resi)\n # res_id = residue.get_id()[1] ##### AttributeError: 'Atom' object has no attribute 'get_id'\n res_id = residue.resi\n res_name = residue.resn\n protein = \"Acb1\"\n \n if res_name == \"ALA\":\n \n print('++++++++++++++++++++++++++++++++++++++++++')\n cmd.wizard(\"mutagenesis\")\n cmd.do(\"refresh_wizard\")\n cmd.get_wizard().set_mode(\"SER\")\n cmd.get_wizard().do_select(f\"Acb1_copy//A/{res_id}/\")\n cmd.get_wizard().apply()\n cmd.wizard()\n \n cmd.save(f\"{protein}_{res_id}.pdb\", 'Acb1_copy')\n \n cmd.delete('Acb1_copy')\n \n else:\n \n pass\n","post_id":115542,"sha256":"22988772a6dc97e3a7d9a85525d882d34b7ac11f85431ff809d1a7fcb196fffa","source_url":"https://biology.stackexchange.com/a/115542"}],"content_license":"CC BY-SA 4.0","domain":"biology","error_text_if_explicit":null,"group_id":"957edca1e016631c9828f39cfab756c303f69a19f7b5e58d4f29a8ca7c2dcd6a","id":"SCT-7c7ce4a90a6f24620e19ac91","language":null,"library_or_tool":null,"problem_text":"Currently I am creating a selection that has residues 5 angstroms away from a ligand for alanine point mutations at each highlighted residue. Currently, the code is creating the specific selections I want, but it has the error below once selecting the model to use mutagenesis on. I specifically ran this code through PyMOL using File -> Run Script\n\n\n\n\n“Atom” has no attribute “get_id” File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pmg_qt\\pymol_qt_gui.py\", line 1192, in file_run self.cmd.run(fname) File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py\", line 470, in run run_(path, ns_pymol, ns_pymol) File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py\", line 519, in run_file execfile(file,global_ns,local_ns) File \"C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py\", line 514, in execfile exec(co, global_ns, local_ns) File \"C:/Users/will/PycharmProjects/Binding Residues/bindingresidue.py\", line 10, in res_id = residue.get_id()[1]\n\n\n\n\n\nHere is the code I used:\n\n\n\n\nfrom pymol import cmd\n\n\ncmd.load(r\"C:\\Users\\will\\.pymol\\Acb1test.pdb\", \"Acb1\")\ncmd.remove(\"not chain A and not residue ECI\")\ncmd.select(\"eci_residue\", \"chain A and resn ECI\")\ncmd.select(\"binding_residues\", \"(byres (eci_residue around 5))\")\nprotein = \"Acb1\"\n\n\nfor residue in cmd.get_model(\"binding_residues\").atom:\n res_id = residue.get_id()[1]\n res_name = residue.get_parent().get_resname()\n\n\n if res_name == \"ALA\":\n cmd.wizard(\"mutagenesis\")\n cmd.wizard().set_mode(\"ser\")\n cmd.get_wizard().do_select(f\"chain A and residue{res_id}\")\n cmd.get_wizard().apply()\n else:\n cmd.wizard(\"mutagenesis\")\n cmd.get_wizard().set_mode(\"ala\")\n cmd.get_wizard().do_select(f\"chain A and residue{res_id}\")\n cmd.get_wizard().apply()\n\n\n cmd.save(r\"C:\\Users\\will\\Acb1test\\{protein}_{res_id}.pdb\")\n cmd.reinitialize()\n cmd.load(r\"C:\\Users\\will\\.pymol\\Acb1test.pdb\", \"Acb1\")\n cmd.remove(\"not chain A and not residue ECI\")\n cmd.select(\"binding_residues\", \"br. (byres (residue ECI around 5))\")\n\ncmd.delete(\"binding_residues\")\n\n\n\n\n\nI ran this through PyCharm. I expected that after a selection was created with residues 5 angstroms away from the ligand, I could mutate each highlighted residue one by one, and save them to my file. I wished for this process to happen for all residues selected separately, which is why I created a simple loop for the mutagenesis function.","provenance":{"original_provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:05.762873+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/04ed2aa314c5d877c5d79e42620d1f80988a21de8d429a22d8c6af5280cfd6e8_0.json","raw_sha256":"6dd355b99094bb9ba2c965ee7dd7b0e95f92a8078d3b2b85b64196fcb6cf717c","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=5&pagesize=100&site=biology&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":"Shayan Joarder","profile_url":"https://biology.stackexchange.com/users/89401/shayan-joarder","user_type":"registered"},"created_at":"2024-10-02T19:19:04+00:00","raw_file":"raw/codex_api_v1/43e0404e391fda3d45541a0db7438bd3a1c2df66d07b9f1a745a1d6a3713c815_1790824097103199200_0.json","raw_sha256":"e55dfe05ee755247d42e0fe87b0ef88822dd9b82f6af36ed5017c907e0ff3823","revision_guid":"B136B1DA-A9B6-42C0-8CC7-E9FA3FC4870D","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/B136B1DA-A9B6-42C0-8CC7-E9FA3FC4870D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2024-10-02T20:05:17+00:00","raw_file":"raw/codex_api_v1/43e0404e391fda3d45541a0db7438bd3a1c2df66d07b9f1a745a1d6a3713c815_1790824097103199200_0.json","raw_sha256":"e55dfe05ee755247d42e0fe87b0ef88822dd9b82f6af36ed5017c907e0ff3823","revision_guid":"54B7D270-6575-4F67-976D-6FE0652D9B0D","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/54B7D270-6575-4F67-976D-6FE0652D9B0D/view-source"}],"source_commit":"049a9227f533c13bbc10d1a38c271e055da0ed6e","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Biology-QA","source_license":"CC BY-SA 4.0","source_record_id":"115427","source_record_sha256":"b2c993242ad5a4499036a997d396a229a1a471cbe35e3f86eb5caeebbf2a0c48","source_url":"https://biology.stackexchange.com/questions/115427/how-to-select-residues-in-a-selection-for-protein-mutagenesis-in-pymol","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Currently I am creating a selection that has residues 5 angstroms away from a ligand for alanine point mutations at each highlighted residue. Currently, the code is creating the specific selections I want, but it has the error below once selecting the model to use mutagenesis on. I specifically ran this code through PyMOL using File -> Run Script

\n
“Atom” has no attribute “get_id” File "C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pmg_qt\\pymol_qt_gui.py", line 1192, in file_run self.cmd.run(fname) File "C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py", line 470, in run run_(path, ns_pymol, ns_pymol) File "C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py", line 519, in run_file execfile(file,global_ns,local_ns) File "C:\\Users\\will\\AppData\\Local\\Schrodinger\\PyMOL2\\lib\\site-packages\\pymol\\parsing.py", line 514, in execfile exec(co, global_ns, local_ns) File "C:/Users/will/PycharmProjects/Binding Residues/bindingresidue.py", line 10, in <module> res_id = residue.get_id()[1]\n
\n

Here is the code I used:

\n
from pymol import cmd\n\n\ncmd.load(r"C:\\Users\\will\\.pymol\\Acb1test.pdb", "Acb1")\ncmd.remove("not chain A and not residue ECI")\ncmd.select("eci_residue", "chain A and resn ECI")\ncmd.select("binding_residues", "(byres (eci_residue around 5))")\nprotein = "Acb1"\n\n\nfor residue in cmd.get_model("binding_residues").atom:\n   res_id = residue.get_id()[1]\n   res_name = residue.get_parent().get_resname()\n\n\n   if res_name == "ALA":\n       cmd.wizard("mutagenesis")\n       cmd.wizard().set_mode("ser")\n       cmd.get_wizard().do_select(f"chain A and residue{res_id}")\n       cmd.get_wizard().apply()\n   else:\n       cmd.wizard("mutagenesis")\n       cmd.get_wizard().set_mode("ala")\n       cmd.get_wizard().do_select(f"chain A and residue{res_id}")\n       cmd.get_wizard().apply()\n\n\n   cmd.save(r"C:\\Users\\will\\Acb1test\\{protein}_{res_id}.pdb")\n   cmd.reinitialize()\n   cmd.load(r"C:\\Users\\will\\.pymol\\Acb1test.pdb", "Acb1")\n   cmd.remove("not chain A and not residue ECI")\n   cmd.select("binding_residues", "br. (byres (residue ECI around 5))")\n\ncmd.delete("binding_residues")\n
\n

I ran this through PyCharm. I expected that after a selection was created with residues 5 angstroms away from the ligand, I could mutate each highlighted residue one by one, and save them to my file. I wished for this process to happen for all residues selected separately, which is why I created a simple loop for the mutagenesis function.

\n","question_title":"How to select residues in a selection for protein mutagenesis in PyMOL?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://biology.stackexchange.com/questions/115427/how-to-select-residues-in-a-selection-for-protein-mutagenesis-in-pymol","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":116397,"score":1}],"answers":[{"answer_html":"

I would suggest instead looking at the mtDNA sequence deposited in NCBI: https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1

\n

I am not sure how this was generated exactly so maybe look into that more. But as far as I can tell it's what you want:

\n
LOCUS       KC879692               16567 bp    DNA     circular PRI 24-JUN-2013\nDEFINITION  Homo sapiens neanderthalensis mitochondrion, complete genome.\nACCESSION   KC879692\nVERSION     KC879692.1\nKEYWORDS    .\nSOURCE      mitochondrion Homo sapiens neanderthalensis (Neandertal)\n  ORGANISM  Homo sapiens neanderthalensis\n            Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;\n            Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;\n            Catarrhini; Hominidae; Homo.\nREFERENCE   1  (bases 1 to 16567)\n  AUTHORS   Consortium,H.C.N.G.\n  TITLE     The high-coverage genome sequence of a Neandertal individual from\n            Denisova cave in the Altai\n  JOURNAL   Unpublished\nREFERENCE   2  (bases 1 to 16567)\n  AUTHORS   Sawyer,S.\n  TITLE     Direct Submission\n  JOURNAL   Submitted (09-APR-2013) Genetics, Max Planck Institute for\n            Evolutionary Anthropology, Deutscher Platz 6, Leipzig, Saxony\n            04103, Germany\n
\n","answer_id":116397,"answer_text":"I would suggest instead looking at the mtDNA sequence deposited in NCBI: https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1 (https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1)\n\n\n\n\nI am not sure how this was generated exactly so maybe look into that more. But as far as I can tell it's what you want:\n\n\n\n\nLOCUS KC879692 16567 bp DNA circular PRI 24-JUN-2013\nDEFINITION Homo sapiens neanderthalensis mitochondrion, complete genome.\nACCESSION KC879692\nVERSION KC879692.1\nKEYWORDS .\nSOURCE mitochondrion Homo sapiens neanderthalensis (Neandertal)\n ORGANISM Homo sapiens neanderthalensis\n Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;\n Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;\n Catarrhini; Hominidae; Homo.\nREFERENCE 1 (bases 1 to 16567)\n AUTHORS Consortium,H.C.N.G.\n TITLE The high-coverage genome sequence of a Neandertal individual from\n Denisova cave in the Altai\n JOURNAL Unpublished\nREFERENCE 2 (bases 1 to 16567)\n AUTHORS Sawyer,S.\n TITLE Direct Submission\n JOURNAL Submitted (09-APR-2013) Genetics, Max Planck Institute for\n Evolutionary Anthropology, Deutscher Platz 6, Leipzig, Saxony\n 04103, Germany","answer_url":"https://biology.stackexchange.com/a/116397","author":"Maximilian Press","author_url":"https://biology.stackexchange.com/users/22392/maximilian-press","content_license":"CC BY-SA 4.0","created_at":"2025-04-23T00:14:09+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:19.947691+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/df693642d727b738d2a533740632235c18a06cefec7a1e337c9589214a4ec91e_0.json","raw_sha256":"9df534f437f3b2f12d33db8536999ec4e6ffa10f2f59394799d9fe01c3c1ad16","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/117606;117602;117598;117594;117585;117579;117570;117568;117565;117559;117558;117555;117552;117548;117538;117524;117523;117522;117520;117515;117510;116509;116508;116504;116499;116491;116485;116483;116461;116454;116453;116445;116441;116435;116430;116426;116425;116414;116412;116406;116401;116399;116396;116395;116394;116392;116389;116384;116370;116367;116363;116361;116352;116351;116347;116345;116343;116338;116337;116332;116331;116324;116320;116316;116314;116312;116306;116292;116290;116284;116280;116277;116271;116270;116268;116267;116257;116256;116253;116250;116249;116240;116237;116233;116219;116214;116212;116205;116204;116200;116198;116187;116184;116173;116172;116167;116162;116149;116142;116129/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":116396,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2025-04-23T00:14:09+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F/view-source"}],"score":1}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Maximilian Press","author_url":"https://biology.stackexchange.com/users/22392/maximilian-press","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Maximilian Press","profile_url":"https://biology.stackexchange.com/users/22392/maximilian-press","user_type":"registered"},"created_at":"2025-04-23T00:14:09+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F/view-source"}],"source_url":"https://biology.stackexchange.com/a/116397"}],"question_author":"Mehdi Saada","question_author_url":"https://biology.stackexchange.com/users/82694/mehdi-saada"},"code_blocks":[{"block_index":0,"code_text":"LOCUS KC879692 16567 bp DNA circular PRI 24-JUN-2013\nDEFINITION Homo sapiens neanderthalensis mitochondrion, complete genome.\nACCESSION KC879692\nVERSION KC879692.1\nKEYWORDS .\nSOURCE mitochondrion Homo sapiens neanderthalensis (Neandertal)\n ORGANISM Homo sapiens neanderthalensis\n Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;\n Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;\n Catarrhini; Hominidae; Homo.\nREFERENCE 1 (bases 1 to 16567)\n AUTHORS Consortium,H.C.N.G.\n TITLE The high-coverage genome sequence of a Neandertal individual from\n Denisova cave in the Altai\n JOURNAL Unpublished\nREFERENCE 2 (bases 1 to 16567)\n AUTHORS Sawyer,S.\n TITLE Direct Submission\n JOURNAL Submitted (09-APR-2013) Genetics, Max Planck Institute for\n Evolutionary Anthropology, Deutscher Platz 6, Leipzig, Saxony\n 04103, Germany\n","post_id":116397,"sha256":"8999e8a3d26cddcd71f86bf241326194e6d6968f20ed0963be7913098bdfe07e","source_url":"https://biology.stackexchange.com/a/116397"}],"content_license":"CC BY-SA 4.0","domain":"biology","error_text_if_explicit":null,"group_id":"8909fa445a12aa523ea13f6f9f5e64165fd0bcd4bf08283e343f39fdeea0c1d6","id":"SCT-017aac528e26242f29c9e2c1","language":null,"library_or_tool":null,"problem_text":"I am looking for the HVRII locus on the Altai Neandertal sequence. Its accession number is ERP002097, but it's the raw resequencing data so it is not on NCBI. You can download the relevant file (for the mtDNA here) on http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/ (http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/).\nThe file is huge, needless to say, but the problem is because those are the contigs, translating it into FASTA doesn't help as I get millions of small reads, what can I do with that ?\nI have the HVRII from the OG neandertal genome, and it has the tri-thymine insertion in the polycysteine tract from the HVRII. That is what I want to check on the Altai.\nDo I have to assemble it myself to give it to Blast ?\nThank you.","provenance":{"original_provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:02.598621+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/5d480e4bd1bd45ab525a4baf3227fba404f89b6af9dad33215fd9fa7c302a211_0.json","raw_sha256":"d723c7a62c8386d143891d26ae30b2234242ed3dac9599b11f141712ea994a96","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=3&pagesize=100&site=biology&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":"Mehdi Saada","profile_url":"https://biology.stackexchange.com/users/82694/mehdi-saada","user_type":"registered"},"created_at":"2025-04-22T23:19:27+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"641BDAAF-0DF0-4DF6-A92F-9796B028FB47","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/641BDAAF-0DF0-4DF6-A92F-9796B028FB47/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Mehdi Saada","profile_url":"https://biology.stackexchange.com/users/82694/mehdi-saada","user_type":"registered"},"created_at":"2025-04-22T23:22:21+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"FA98BB5E-D9FA-4C7D-AB0A-E887F6F7067E","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/FA98BB5E-D9FA-4C7D-AB0A-E887F6F7067E/view-source"},{"content_license":null,"contributor":{"display_name":"Community","profile_url":"https://biology.stackexchange.com/users/-1/community","user_type":"moderator"},"created_at":"2025-05-23T01:03:20+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"2B8DE90A-567F-4469-A500-58C9EF0A1B1D","revision_number":null,"revision_type":"vote_based","revision_url":"https://biology.stackexchange.com/revisions/2B8DE90A-567F-4469-A500-58C9EF0A1B1D/view-source"}],"source_commit":"049a9227f533c13bbc10d1a38c271e055da0ed6e","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Biology-QA","source_license":"CC BY-SA 4.0","source_record_id":"116396","source_record_sha256":"704022626335419300b4aef24969034056a47440a2d3699ed6905796b77c6cbe","source_url":"https://biology.stackexchange.com/questions/116396/how-to-find-the-hvrii-locus-on-the-altai-neandertal","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am looking for the HVRII locus on the Altai Neandertal sequence. Its accession number is ERP002097, but it's the raw resequencing data so it is not on NCBI. You can download the relevant file (for the mtDNA here) on http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/.\nThe file is huge, needless to say, but the problem is because those are the contigs, translating it into FASTA doesn't help as I get millions of small reads, what can I do with that ?\nI have the HVRII from the OG neandertal genome, and it has the tri-thymine insertion in the polycysteine tract from the HVRII. That is what I want to check on the Altai.\nDo I have to assemble it myself to give it to Blast ?\nThank you.

\n","question_title":"How to find the HVRII locus on the Altai Neandertal","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://biology.stackexchange.com/questions/116396/how-to-find-the-hvrii-locus-on-the-altai-neandertal","split":"test"} {"accepted_answer":null,"answer_scores":[{"answer_id":117635,"score":1}],"answers":[{"answer_html":"

As others are positing, that population is not in equilibrium. This is pretty obvious just from a cursory glance at the numbers. In no situation would you have a population at equilibrium where your Aa freqency is lower than both your AA frequency and your aa frequency. It's just mathematically impossible. Simple proof: assume that this were the case:

\n
2pq < p^2\n2pq < q^2\n
\n

By division, this means that:

\n
2q < p\n2p < q\n
\n

Since p = 1 - q and q = 1 - p,

\n
2q < 1 - q\n2p < 1 - p\n
\n

By adding q or p to both sides of the equations,

\n
3q < 1\n3p < 1\n
\n

Divide:

\n
q < 1/3\np < 1/3\n
\n

Therefore in this situation p + q < 2/3 which is incorrect: p + q = 1 at Hardy Weinberg equilibrium. The Hardy-Weinberg assumptions are violated and this population is not at equilibrium.

\n","answer_id":117635,"answer_text":"As others are positing, that population is not in equilibrium. This is pretty obvious just from a cursory glance at the numbers. In no situation would you have a population at equilibrium where your Aa freqency is lower than both your AA frequency and your aa frequency. It's just mathematically impossible. Simple proof: assume that this were the case:\n\n\n\n\n2pq < p^2\n2pq < q^2\n\n\n\n\n\nBy division, this means that:\n\n\n\n\n2q < p\n2p < q\n\n\n\n\n\nSince p = 1 - q and q = 1 - p,\n\n\n\n\n2q < 1 - q\n2p < 1 - p\n\n\n\n\n\nBy adding q or p to both sides of the equations,\n\n\n\n\n3q < 1\n3p < 1\n\n\n\n\n\nDivide:\n\n\n\n\nq < 1/3\np < 1/3\n\n\n\n\n\nTherefore in this situation p + q < 2/3 which is incorrect: p + q = 1 at Hardy Weinberg equilibrium. The Hardy-Weinberg assumptions are violated and this population is not at equilibrium.","answer_url":"https://biology.stackexchange.com/a/117635","author":"rotaredom","author_url":"https://biology.stackexchange.com/users/24613/rotaredom","content_license":"CC BY-SA 4.0","created_at":"2025-07-01T23:29:19+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:16.948131+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/46a41fae37d5c2c243f9abcbf6829a0045f46a51c624fbba2b897c320cdcba71_0.json","raw_sha256":"e039e310d0106dc61f992ee05bbb0b0b57ded1c5092f97df2c52989edd5eaf68","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/118153;118142;118137;118126;118122;118117;118113;118102;118099;118097;118094;118081;118076;118072;118069;118065;118059;118056;118043;118039;118036;118030;118029;118025;118022;118018;117994;117992;117990;117987;117983;117981;117975;117971;117956;117953;117951;117945;117943;117941;117934;117926;117924;117920;117916;117914;117907;117892;117889;117887;117883;117876;117872;117867;117861;117860;117856;117855;117850;117849;117844;117840;117833;117821;117819;117817;117815;117814;117805;117794;117782;117774;117771;117767;117766;117761;117759;117756;117747;117732;117726;117724;117709;117701;117694;117693;117681;117680;117677;117671;117668;117664;117662;117659;117651;117641;117632;117624;117623;117607/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":117607,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"rotaredom","profile_url":"https://biology.stackexchange.com/users/24613/rotaredom","user_type":"registered"},"created_at":"2025-07-01T23:29:19+00:00","raw_file":"raw/codex_api_v1/80ec0626e4dca1e373c0bba13c4761d1214a376d40d05a99b2449abc3be980f1_1790824142842265700_0.json","raw_sha256":"33eeba97fc2f78c2f9362274c5b7e2be011563807fed5b756d22d51f059bffce","revision_guid":"97794DBA-3FDA-41B0-A529-89F522C5592E","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/97794DBA-3FDA-41B0-A529-89F522C5592E/view-source"}],"score":1}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"rotaredom","author_url":"https://biology.stackexchange.com/users/24613/rotaredom","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"rotaredom","profile_url":"https://biology.stackexchange.com/users/24613/rotaredom","user_type":"registered"},"created_at":"2025-07-01T23:29:19+00:00","raw_file":"raw/codex_api_v1/80ec0626e4dca1e373c0bba13c4761d1214a376d40d05a99b2449abc3be980f1_1790824142842265700_0.json","raw_sha256":"33eeba97fc2f78c2f9362274c5b7e2be011563807fed5b756d22d51f059bffce","revision_guid":"97794DBA-3FDA-41B0-A529-89F522C5592E","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/97794DBA-3FDA-41B0-A529-89F522C5592E/view-source"}],"source_url":"https://biology.stackexchange.com/a/117635"}],"question_author":"Dri Acácio","question_author_url":"https://biology.stackexchange.com/users/110648/dri-ac%c3%a1cio"},"code_blocks":[{"block_index":0,"code_text":"AA: 500\nAa: 200\naa: 300\n","post_id":"117607","sha256":"11a2c9e914d636e0f3d446805c176edbe0e40ca67d94b88c66c19036310d4759","source_url":"https://biology.stackexchange.com/questions/117607/is-this-population-not-in-hardy-weinberg-equilibrium"},{"block_index":1,"code_text":"q = [(2 × aa) + Aa] / (2 × total individuals)\nq = [(2 × 300) + 200] / 2000 = 800/2000 = 0.4\n","post_id":"117607","sha256":"b2533d7921547e7918927ae06f237b1f5a6220c0b7aeed471342d608136e098c","source_url":"https://biology.stackexchange.com/questions/117607/is-this-population-not-in-hardy-weinberg-equilibrium"},{"block_index":2,"code_text":"q² = (0.4)² = 0.16 (16%)\n","post_id":"117607","sha256":"49308ad9005c83295766650b5f5f2be6160c81b2399f50f1fd9d783ccaa41776","source_url":"https://biology.stackexchange.com/questions/117607/is-this-population-not-in-hardy-weinberg-equilibrium"},{"block_index":3,"code_text":"300/1000 = 0.3 (30%)\n","post_id":"117607","sha256":"854690bf5b72a8778af66ba6b999dbdff6b836044c64ca3e5ef23b1e76f03e76","source_url":"https://biology.stackexchange.com/questions/117607/is-this-population-not-in-hardy-weinberg-equilibrium"},{"block_index":0,"code_text":"2pq < p^2\n2pq < q^2\n","post_id":117635,"sha256":"d6161ff9dc7035fd5b4447e7ea719207d25cee9cfea55de03054af05a545e4c0","source_url":"https://biology.stackexchange.com/a/117635"},{"block_index":1,"code_text":"2q < p\n2p < q\n","post_id":117635,"sha256":"7e75908c4910b4f11b3b54cf54cfcf52bef8d2af459c5e03a59e23accf875352","source_url":"https://biology.stackexchange.com/a/117635"},{"block_index":2,"code_text":"2q < 1 - q\n2p < 1 - p\n","post_id":117635,"sha256":"5a2cdd84e777b83b892ba3803eb04322a2971e288f2a351584b836e72f05bfbe","source_url":"https://biology.stackexchange.com/a/117635"},{"block_index":3,"code_text":"3q < 1\n3p < 1\n","post_id":117635,"sha256":"60557b905f05f58c12065fba7138792263ef8d95d0958e26ff7ecc629537d4de","source_url":"https://biology.stackexchange.com/a/117635"},{"block_index":4,"code_text":"q < 1/3\np < 1/3\n","post_id":117635,"sha256":"5e8482ec53b4687cbd90fba7ea743a05713271a48bf04183b7f5af05981c1899","source_url":"https://biology.stackexchange.com/a/117635"}],"content_license":"CC BY-SA 4.0","domain":"biology","error_text_if_explicit":null,"group_id":"08d947ca011443c7883ff818d7123cf3c7a7bc52cd6207a4b343db67b96a3b87","id":"SCT-e1c99624e05dad58687dafd1","language":null,"library_or_tool":null,"problem_text":"I'm a biology student and, while answering a Hardy-Weinberg equilibrium exercise, I found an inconsistency. Could someone verify if my interpretation is correct?\n\n\n\n\nPopulation data\n\n\n\n\nTotal individuals: 1000\n\n\n\n\nGenotype counts:\n\n\n\n\nAA: 500\nAa: 200\naa: 300\n\n\n\n\n\nMy analysis\n\n\n\n\nCalculated allele frequency of a (q):\n\n\n\n\nq = [(2 × aa) + Aa] / (2 × total individuals)\nq = [(2 × 300) + 200] / 2000 = 800/2000 = 0.4\n\n\n\n\n\nExpected frequency of aa under H-W equilibrium:\n\n\n\n\nq² = (0.4)² = 0.16 (16%)\n\n\n\n\n\nObserved frequency of aa:\n\n\n\n\n300/1000 = 0.3 (30%)\n\n\n\n\n\nCore issue:\nThe observed frequency of aa (30%) is much higher than the expected q² (16%) for q = 0.4.\n\n\n\n\nQuestion\n\n\n\n\nDoes this mean the population violates Hardy-Weinberg equilibrium?","provenance":{"original_provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:01.208074+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/f1b387b48f36041f506f18fa9796531023c7eae1e796ec622ad56833c02bea98_0.json","raw_sha256":"3f8214c87c0fe16dd016324597332ca392e0ba98600877cc746483ef492ce03d","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=2&pagesize=100&site=biology&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":"Dri Acácio","profile_url":"https://biology.stackexchange.com/users/110648/dri-ac%c3%a1cio","user_type":"registered"},"created_at":"2025-06-19T16:33:59+00:00","raw_file":"raw/codex_api_v1/80ec0626e4dca1e373c0bba13c4761d1214a376d40d05a99b2449abc3be980f1_1790824142842265700_0.json","raw_sha256":"33eeba97fc2f78c2f9362274c5b7e2be011563807fed5b756d22d51f059bffce","revision_guid":"779236AC-9784-4CD6-9D1E-470E00BCF0C8","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/779236AC-9784-4CD6-9D1E-470E00BCF0C8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dri Acácio","profile_url":"https://biology.stackexchange.com/users/110648/dri-ac%c3%a1cio","user_type":"registered"},"created_at":"2025-06-19T16:34:30+00:00","raw_file":"raw/codex_api_v1/80ec0626e4dca1e373c0bba13c4761d1214a376d40d05a99b2449abc3be980f1_1790824142842265700_0.json","raw_sha256":"33eeba97fc2f78c2f9362274c5b7e2be011563807fed5b756d22d51f059bffce","revision_guid":"3936E62D-46DB-4AC1-8D3C-FF14DED4D67A","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/3936E62D-46DB-4AC1-8D3C-FF14DED4D67A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2025-06-19T18:03:22+00:00","raw_file":"raw/codex_api_v1/80ec0626e4dca1e373c0bba13c4761d1214a376d40d05a99b2449abc3be980f1_1790824142842265700_0.json","raw_sha256":"33eeba97fc2f78c2f9362274c5b7e2be011563807fed5b756d22d51f059bffce","revision_guid":"DFCBDB91-6236-4BBE-8778-BC0C6E5D2A2A","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/DFCBDB91-6236-4BBE-8778-BC0C6E5D2A2A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Domen","profile_url":"https://biology.stackexchange.com/users/39423/domen","user_type":"registered"},"created_at":"2025-07-01T23:16:18+00:00","raw_file":"raw/codex_api_v1/80ec0626e4dca1e373c0bba13c4761d1214a376d40d05a99b2449abc3be980f1_1790824142842265700_0.json","raw_sha256":"33eeba97fc2f78c2f9362274c5b7e2be011563807fed5b756d22d51f059bffce","revision_guid":"04403506-3F5D-41B3-A1F5-84F236B2BFDD","revision_number":4,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/04403506-3F5D-41B3-A1F5-84F236B2BFDD/view-source"}],"source_commit":"049a9227f533c13bbc10d1a38c271e055da0ed6e","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Biology-QA","source_license":"CC BY-SA 4.0","source_record_id":"117607","source_record_sha256":"3e7021b5717c45c3841d60818caa4ec072d69f6a8a0dd2a4e68b56af15e1c8bf","source_url":"https://biology.stackexchange.com/questions/117607/is-this-population-not-in-hardy-weinberg-equilibrium","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I'm a biology student and, while answering a Hardy-Weinberg equilibrium exercise, I found an inconsistency. Could someone verify if my interpretation is correct?

\n

Population data

\n

Total individuals: 1000

\n

Genotype counts:

\n
AA: 500\nAa: 200\naa: 300\n
\n

My analysis

\n

Calculated allele frequency of a (q):

\n
q = [(2 × aa) + Aa] / (2 × total individuals)\nq = [(2 × 300) + 200] / 2000 = 800/2000 = 0.4\n
\n

Expected frequency of aa under H-W equilibrium:

\n
q² = (0.4)² = 0.16 (16%)\n
\n

Observed frequency of aa:

\n
300/1000 = 0.3 (30%)\n
\n

Core issue:\nThe observed frequency of aa (30%) is much higher than the expected q² (16%) for q = 0.4.

\n

Question

\n

Does this mean the population violates Hardy-Weinberg equilibrium?

\n","question_title":"Is this population not in Hardy–Weinberg equilibrium?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://biology.stackexchange.com/questions/117607/is-this-population-not-in-hardy-weinberg-equilibrium","split":"train"} {"accepted_answer":{"answer_html":"

(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.

\n

(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no "information leakage" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.

\n

(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.

\n","answer_id":676887,"answer_text":"(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.\n\n\n\n\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no \"information leakage\" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.\n\n\n\n\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.","answer_url":"https://stats.stackexchange.com/a/676887","author":"Christian Hennig","author_url":"https://stats.stackexchange.com/users/247165/christian-hennig","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-16T11:19:56+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676874,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Christian Hennig","profile_url":"https://stats.stackexchange.com/users/247165/christian-hennig","user_type":"registered"},"created_at":"2026-08-16T11:19:56+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB/view-source"}],"score":5,"updated_at":"2026-08-16T11:19:56+00:00"},"answer_scores":[{"answer_id":676875,"score":6},{"answer_id":676876,"score":2},{"answer_id":676887,"score":5},{"answer_id":676896,"score":3}],"answers":[{"answer_html":"

The principal components (PCs) are not guaranteed to be good predictors. PCA is performed without any regard for an outcome ($y$) variable and, alone, is not a prediction technique. However, the PCs most definitely can be entered into a regression model. See below for an example in R.

\n
set.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n
\n

I did this with a linear regression, but if you have a categorical outcome (“classification” type of problem), you could use the PCs in a (multinomial) logistic regression or a sigmoid/softmax neural network and then measure performance by log loss, Brier score, or any of the other measures of performance used for classification-type problems.

\n","answer_id":676875,"answer_text":"The principal components (PCs) are not guaranteed to be good predictors. PCA is performed without any regard for an outcome ($y$) variable and, alone, is not a prediction technique. However, the PCs most definitely can be entered into a regression model. See below for an example in R.\n\n\n\n\nset.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n\n\n\n\n\nI did this with a linear regression, but if you have a categorical outcome (“classification” type of problem), you could use the PCs in a (multinomial) logistic regression or a sigmoid/softmax neural network and then measure performance by log loss, Brier score, or any of the other measures of performance used for classification-type problems.","answer_url":"https://stats.stackexchange.com/a/676875","author":"Dave","author_url":"https://stats.stackexchange.com/users/247274/dave","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-15T10:57:03+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676874,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dave","profile_url":"https://stats.stackexchange.com/users/247274/dave","user_type":"registered"},"created_at":"2026-08-15T10:57:03+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"7A2458ED-B2DA-472F-BF39-53D6AC4C1287","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/7A2458ED-B2DA-472F-BF39-53D6AC4C1287/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dave","profile_url":"https://stats.stackexchange.com/users/247274/dave","user_type":"registered"},"created_at":"2026-08-15T11:09:18+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2/view-source"}],"score":6,"updated_at":"2026-08-15T11:09:18+00:00"},{"answer_html":"

Prediction is not the only thing we do, so whether PCA can be used for prediction is not the only question to ask.

\n

Wikipedia lists the following

\n
    \n
  1. Intelligence testing
  2. \n
  3. Residential differentiation
  4. \n
  5. Development indexes
  6. \n
  7. Population genetics
  8. \n
  9. Market research
  10. \n
  11. Various uses in quantitative finance
  12. \n
  13. Various uses in neuroscience
  14. \n
\n

A long time ago I did some of the last, looking at patterns from quantitative electroencephalography, where we had data on a huge number of neurons. We tried to use the PCA results to categorize people into various injuries, determine if they had had a concussion, and so on, with less need for a neurologist. This could then be done e.g. on a battlefield, or a sporting event, or emergency room that lacked a neurologist.

\n

I haven't kept up with that field, so I'm not sure what happened there, but our initial results were promising.

\n","answer_id":676876,"answer_text":"Prediction is not the only thing we do, so whether PCA can be used for prediction is not the only question to ask.\n\n\n\n\nWikipedia (https://en.wikipedia.org/wiki/Principal_component_analysis#Applications) lists the following\n\n\n\n\n\nIntelligence testing\n\n\n\n\nResidential differentiation\n\n\n\n\nDevelopment indexes\n\n\n\n\nPopulation genetics\n\n\n\n\nMarket research\n\n\n\n\nVarious uses in quantitative finance\n\n\n\n\nVarious uses in neuroscience\n\n\n\n\n\nA long time ago I did some of the last, looking at patterns from quantitative electroencephalography, where we had data on a huge number of neurons. We tried to use the PCA results to categorize people into various injuries, determine if they had had a concussion, and so on, with less need for a neurologist. This could then be done e.g. on a battlefield, or a sporting event, or emergency room that lacked a neurologist.\n\n\n\n\nI haven't kept up with that field, so I'm not sure what happened there, but our initial results were promising.","answer_url":"https://stats.stackexchange.com/a/676876","author":"Peter Flom","author_url":"https://stats.stackexchange.com/users/686/peter-flom","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-15T11:16:14+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676874,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter Flom","profile_url":"https://stats.stackexchange.com/users/686/peter-flom","user_type":"registered"},"created_at":"2026-08-15T11:16:14+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"5F1D4B92-63F4-42E2-B24E-133C561E4D0A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/5F1D4B92-63F4-42E2-B24E-133C561E4D0A/view-source"}],"score":2,"updated_at":"2026-08-15T11:16:14+00:00"},{"answer_html":"

(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.

\n

(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no "information leakage" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.

\n

(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.

\n","answer_id":676887,"answer_text":"(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.\n\n\n\n\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no \"information leakage\" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.\n\n\n\n\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.","answer_url":"https://stats.stackexchange.com/a/676887","author":"Christian Hennig","author_url":"https://stats.stackexchange.com/users/247165/christian-hennig","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-16T11:19:56+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676874,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Christian Hennig","profile_url":"https://stats.stackexchange.com/users/247165/christian-hennig","user_type":"registered"},"created_at":"2026-08-16T11:19:56+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB/view-source"}],"score":5,"updated_at":"2026-08-16T11:19:56+00:00"},{"answer_html":"

PCA gives you a projection, and that can (and is sucessfully) be used to produce lower-dimensional input for various predictive models. Principal component regression (PCA-CLS) being possibly the most widely known, but in my field also PCA-LDA for classification is widely used (our data generation processes fit nicely with the maths of PCA), and PCA is at the core of SIMCA, an important one-class classifier/class model.

\n

As Christian Hennig's answer details, there is no general guarantee that a projection and dimension reduction by PCA as part of the modeling pipeline is going to help. But there are certain types of data and applications where there is good reason to expect that it does; and of course this can and should be verified.
\nE.g. I'm analytical chemist. We have essentially spent 100 years optimizing our measurements to yield data that nicely approximates linear combinations of concentration x pure component spectra. And PCA or PLS do indeed work nicely on such data. Plus, many industrial applications don't focus on minor components independent of the major sources of variance but rather need quick and non-destructive measurements of the major components which also have largest variance.

\n

In a modeling pipeline unsupervised PCA projection -> predictive model in the narrower sense, the unsupervised nature of the PCA can be particularly helpful if lots of unlabelled data are available, but only a few labelled instances: the PCA projection (with dimension reduction) can then still be fit on the large unlabelled data base, and the (2nd) supervised part of the training can profit from fitting in the lower dimensional PC score space.\nThis scenario is quite common in chemometric modeling of spectroscopic data, where spectra are easy and cheap to acquire (and often non-destructive), while labels require reference (chemical) analyses which are expensive and often also restricted due to being destructive.

\n

Otherwise, if labels are available for all training data, most people in my field would immediately go for the supervised analogue to PCA, PLS.

\n","answer_id":676896,"answer_text":"PCA gives you a projection, and that can (and is sucessfully) be used to produce lower-dimensional input for various predictive models. Principal component regression (PCA-CLS) being possibly the most widely known, but in my field also PCA-LDA for classification is widely used (our data generation processes fit nicely with the maths of PCA), and PCA is at the core of SIMCA (https://en.wikipedia.org/wiki/Soft_independent_modelling_of_class_analogies), an important one-class classifier/class model.\n\n\n\n\nAs Christian Hennig's answer (https://stats.stackexchange.com/a/676887/4598) details, there is no general guarantee that a projection and dimension reduction by PCA as part of the modeling pipeline is going to help. But there are certain types of data and applications where there is good reason to expect that it does; and of course this can and should be verified.\n\nE.g. I'm analytical chemist. We have essentially spent 100 years optimizing our measurements to yield data that nicely approximates linear combinations of concentration x pure component spectra. And PCA or PLS do indeed work nicely on such data. Plus, many industrial applications don't focus on minor components independent of the major sources of variance but rather need quick and non-destructive measurements of the major components which also have largest variance.\n\n\n\n\nIn a modeling pipeline unsupervised PCA projection -> predictive model in the narrower sense, the unsupervised nature of the PCA can be particularly helpful if lots of unlabelled data are available, but only a few labelled instances: the PCA projection (with dimension reduction) can then still be fit on the large unlabelled data base, and the (2nd) supervised part of the training can profit from fitting in the lower dimensional PC score space.\nThis scenario is quite common in chemometric modeling of spectroscopic data, where spectra are easy and cheap to acquire (and often non-destructive), while labels require reference (chemical) analyses which are expensive and often also restricted due to being destructive.\n\n\n\n\nOtherwise, if labels are available for all training data, most people in my field would immediately go for the supervised analogue to PCA, PLS.","answer_url":"https://stats.stackexchange.com/a/676896","author":"cbeleites","author_url":"https://stats.stackexchange.com/users/4598/cbeleites","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-17T17:03:30+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676874,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"cbeleites","profile_url":"https://stats.stackexchange.com/users/4598/cbeleites","user_type":"registered"},"created_at":"2026-08-17T17:03:30+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3A1FC35A-72A0-4215-A06C-3D8E4B7FB085","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3A1FC35A-72A0-4215-A06C-3D8E4B7FB085/view-source"}],"score":3,"updated_at":"2026-08-17T17:03:30+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Dave","author_url":"https://stats.stackexchange.com/users/247274/dave","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dave","profile_url":"https://stats.stackexchange.com/users/247274/dave","user_type":"registered"},"created_at":"2026-08-15T10:57:03+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"7A2458ED-B2DA-472F-BF39-53D6AC4C1287","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/7A2458ED-B2DA-472F-BF39-53D6AC4C1287/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dave","profile_url":"https://stats.stackexchange.com/users/247274/dave","user_type":"registered"},"created_at":"2026-08-15T11:09:18+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2/view-source"}],"source_url":"https://stats.stackexchange.com/a/676875"},{"author":"Peter Flom","author_url":"https://stats.stackexchange.com/users/686/peter-flom","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter Flom","profile_url":"https://stats.stackexchange.com/users/686/peter-flom","user_type":"registered"},"created_at":"2026-08-15T11:16:14+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"5F1D4B92-63F4-42E2-B24E-133C561E4D0A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/5F1D4B92-63F4-42E2-B24E-133C561E4D0A/view-source"}],"source_url":"https://stats.stackexchange.com/a/676876"},{"author":"Christian Hennig","author_url":"https://stats.stackexchange.com/users/247165/christian-hennig","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Christian Hennig","profile_url":"https://stats.stackexchange.com/users/247165/christian-hennig","user_type":"registered"},"created_at":"2026-08-16T11:19:56+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB/view-source"}],"source_url":"https://stats.stackexchange.com/a/676887"},{"author":"cbeleites","author_url":"https://stats.stackexchange.com/users/4598/cbeleites","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"cbeleites","profile_url":"https://stats.stackexchange.com/users/4598/cbeleites","user_type":"registered"},"created_at":"2026-08-17T17:03:30+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3A1FC35A-72A0-4215-A06C-3D8E4B7FB085","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3A1FC35A-72A0-4215-A06C-3D8E4B7FB085/view-source"}],"source_url":"https://stats.stackexchange.com/a/676896"}],"question_author":"Karl Suh","question_author_url":"https://stats.stackexchange.com/users/513622/karl-suh"},"code_blocks":[{"block_index":0,"code_text":"set.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n","post_id":676875,"sha256":"83b92e32f3481c32f864e266e5b1a8c2498a0e79f593a7bfb01f507538e35cf0","source_url":"https://stats.stackexchange.com/a/676875"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"75289916dbeb3f563334247ca0a4653de359eb78d7360042c46047a4ea300f9f","id":"SCT-30b8f67e6228f341e2fea696","language":null,"library_or_tool":null,"problem_text":"I've been reading up on pca. I've seen some people say that you cannot use pca for making predictions especially for linear regression models because it makes principal components that capture the most variability and not necessarily the actual relationships.\n\n\n\n\nHowever, I've seen principal components be reverted to their original variables and then used to make predictions in example cases. I am confused about which one is correct.\n\n\n\n\nI don't really understand the point even using pca if you can't make predictions off of the data. Is this just a linear regression-specific issue and not a classification problem/doesn't apply to other models?","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":"Karl Suh","profile_url":"https://stats.stackexchange.com/users/513622/karl-suh","user_type":"registered"},"created_at":"2026-08-15T04:30:32+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"47012D84-2D0B-46BA-AE42-079A86DD6563","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/47012D84-2D0B-46BA-AE42-079A86DD6563/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-15T12:40:24+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"B197227E-EAF9-49DD-B742-0B419AF26E38","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/B197227E-EAF9-49DD-B742-0B419AF26E38/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-08-17T12:50:40+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3799EB1C-3EFE-4A46-9106-11DCDC93F431","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3799EB1C-3EFE-4A46-9106-11DCDC93F431/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:676874","source_record_sha256":"1b8b6a0302d02ffe8911d18f2d675f49da16fbadf0390517675eeba78cefdef9","source_url":"https://stats.stackexchange.com/questions/676874/can-you-use-pca-to-make-predictions-are-the-issues-with-predictions-specific-to","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I've been reading up on pca. I've seen some people say that you cannot use pca for making predictions especially for linear regression models because it makes principal components that capture the most variability and not necessarily the actual relationships.

\n

However, I've seen principal components be reverted to their original variables and then used to make predictions in example cases. I am confused about which one is correct.

\n

I don't really understand the point even using pca if you can't make predictions off of the data. Is this just a linear regression-specific issue and not a classification problem/doesn't apply to other models?

\n","question_title":"Can you use PCA to make predictions? are the issues with predictions specific to linear regression?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/676874/can-you-use-pca-to-make-predictions-are-the-issues-with-predictions-specific-to","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":676936,"score":5}],"answers":[{"answer_html":"
\n

is trying to use all the data a flawed concept to begin with?

\n
\n

No. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are "missing completely at random" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.

\n
\n

is this even a valid approach to begin with...?

\n
\n

Your most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.

\n
\n

what is the "best" approach?

\n
\n

For MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.

\n

A standard general approach is multiple imputation. Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.

\n

A single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.

\n

Stef van Buuren's Flexible Imputation of Missing Data is a comprehensive guide to the process, which is implemented in his R mice package. Chapter 3 of Regression Modeling Strategies by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms and Hmisc packages.

\n
\n

Does the validity depend on the pattern of missing data?

\n
\n

Yes, in two ways.

\n

First, multiple imputation works correctly if the data are "missing at random" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.

\n

Second, the model for imputation needs to represent the patterns of association among the data values adequately.

\n

The references linked above go into much more detail.

\n","answer_id":676936,"answer_text":"is trying to use all the data a flawed concept to begin with?\n\n\n\n\n\n\n\nNo. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are \"missing completely at random\" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.\n\n\n\n\n\n\n\nis this even a valid approach to begin with...?\n\n\n\n\n\n\n\nYour most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.\n\n\n\n\n\n\n\nwhat is the \"best\" approach?\n\n\n\n\n\n\n\nFor MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.\n\n\n\n\nA standard general approach is multiple imputation (https://stats.stackexchange.com/tags/multiple-imputation/info). Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.\n\n\n\n\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.\n\n\n\n\nStef van Buuren's Flexible Imputation of Missing Data (https://stefvanbuuren.name/fimd/) is a comprehensive guide to the process, which is implemented in his R mice package (https://cran.r-project.org/package=mice). Chapter 3 of Regression Modeling Strategies (https://hbiostat.org/rmsc/missing) by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms (https://cran.r-project.org/package=rms) and Hmisc (https://cran.r-project.org/package=Hmisc) packages.\n\n\n\n\n\n\n\nDoes the validity depend on the pattern of missing data?\n\n\n\n\n\n\n\nYes, in two ways.\n\n\n\n\nFirst, multiple imputation works correctly if the data are \"missing at random\" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.\n\n\n\n\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.\n\n\n\n\nThe references linked above go into much more detail.","answer_url":"https://stats.stackexchange.com/a/676936","author":"EdM","author_url":"https://stats.stackexchange.com/users/28500/edm","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-22T20:30:48+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676935,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-22T20:30:48+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3A662AF2-F298-45A5-889D-7BDCBFDD001E","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-23T17:43:21+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}],"score":5,"updated_at":"2026-08-23T17:43:21+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"EdM","author_url":"https://stats.stackexchange.com/users/28500/edm","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-22T20:30:48+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3A662AF2-F298-45A5-889D-7BDCBFDD001E","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-23T17:43:21+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}],"source_url":"https://stats.stackexchange.com/a/676936"}],"question_author":"A Friendly Fish","question_author_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish"},"code_blocks":[{"block_index":0,"code_text":"# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n","post_id":"stats:676935","sha256":"31ee3b391b409c5129c104a44ceee4665e4ad79f9da5a4e9871a1a05341ae6ea","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"},{"block_index":1,"code_text":"\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n","post_id":"stats:676935","sha256":"b6b0f012237812aeee60a934ab35cd7d57e130e125fb4b2b6e91c84b7c48ca96","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"},{"block_index":2,"code_text":"# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))\n","post_id":"stats:676935","sha256":"8cca68dde9586d6ddecb1ac0f5140745338cd3f8b49ea77f06aa4850b3958b9f","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"03ed9cb55365330b1a43abeaaef4353dbae646c43e695d80e153e28eed85e878","id":"SCT-4e8b2ca95695adbf68f9118d","language":null,"library_or_tool":null,"problem_text":"I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the \"best\" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?\n\n\n\n\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n\n\n\n\n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)\n\n\n\n\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, (\"Full\") one where we actually aren't missing data, (\"Half\") one where we only use $h$ observations, (\"Estimated B\") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and (\"Perfect A\", \"Perfect B\") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:\n\n\n\n\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\n\n\n\n\nAs you can see in the results above, the \"Estimated B\" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points (\"Half Model\"), but it does have a bias.\n\n\n\n\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book (https://stefvanbuuren.name/fimd/sec-simplesolutions.html) and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:\n\n\n\n\n\n\n\n\n\nModel\nMean\nVariance\nBias\nBias_Sq\nMSE\nValid_Runs\n\n\n\n\n\n\n\n\n\tFull Model (N=40)\n\t0.66563\n\t0.02497\n\t-0.00103\n\t0.00000\n\t0.02497\n\t9947\n\n\n\n\n\n\n\tHalf Model (H=20)\n\t0.66289\n\t0.05542\n\t-0.00377\n\t0.00001\n\t0.05543\n\t9947\n\n\n\n\n\n\n\tEstimated B\n\t0.64330\n\t0.05259\n\t-0.02337\n\t0.00055\n\t0.05313\n\t9947\n\n\n\n\n\n\n\tLavaan Pairwise\n\t0.65849\n\t0.07174\n\t-0.00818\n\t0.00007\n\t0.07180\n\t9947\n\n\n\n\n\n\n\n\n\nI am including the code i ran below:\n\n\n\n\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))","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":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-22T12:39:55+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"E204A8FC-AC6E-48BB-AF80-E203CBC8615E","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/E204A8FC-AC6E-48BB-AF80-E203CBC8615E/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-22T20:46:45+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"18F1A87E-216E-4249-8293-E060F71CC55D","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/18F1A87E-216E-4249-8293-E060F71CC55D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T15:52:35+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"70469448-256D-43B2-80C1-746F337D6247","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/70469448-256D-43B2-80C1-746F337D6247/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T16:01:52+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T16:53:21+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30","revision_number":4,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T17:02:49+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"AC468C9B-BCFF-4264-A45F-3229DC6759C1","revision_number":5,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/AC468C9B-BCFF-4264-A45F-3229DC6759C1/view-source"}],"source_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:676935","source_record_sha256":"08d2eb508fc13e87f6b6b85c899b59dbb45aaaab753996fa4f22e7f84ebc2d30","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the "best" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?

\n
# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n    y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n    ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n    multiple[i]<-coefficients(summary(ly1ONy0y2_h))["y0h","Pr(>|t|)"]\n    ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n    r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n    ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n    lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n    lrONr$df.residual <- lrONr$df.residual - dof_correction\n    stage[i]<-coefficients(summary(lrONr))["r_ly0ONy2_n_h","Pr(>|t|)"]\n}\ncat("Multiple:   ", mean(multiple < 0.05), "\\n")\n# Multiple:    0.0529 \ncat("   Stage:   ", mean(stage < 0.05), "\\n")\n#    Stage:    0.0527 \n
\n

Observe that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)

\n

UPDATE (1/2):\nI ran simulation code to compare some of the key models, ("Full") one where we actually aren't missing data, ("Half") one where we only use $h$ observations, ("Estimated B") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and ("Perfect A", "Perfect B") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:

\n
\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n  # 1. Generate base standard normal variables\n  x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n  y0 <- x0 + x1;  y1 <- x1 + x2;  y2 <- x0 + x3\n  \n  # Half-sample subsets\n  x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n  y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n  \n  # 2. Full Model (sfm) - benchmark using full sample (N = n)\n  sfm[i] <- coef(lm(y1 ~ y0 + y2))["y0"]\n  \n  # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n  shm[i] <- coef(lm(y1h ~ y0h + y2h))["y0h"]\n  \n  # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n  y0rph <- y0h - 0.5 * y2h\n  shpa[i] <- coef(lm(y1h ~ y0rph))["y0rph"]\n  \n  # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n  y1rh <- residuals(lm(y1h ~ y2h))\n  shpb[i] <- coef(lm(y1rh ~ y0rph))["y0rph"]\n  \n  # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n  y0re <- residuals(lm(y0 ~ y2))\n  y0reh <- y0re[1:h]\n  sheb[i] <- coef(lm(y1rh ~ y0reh))["y0reh"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n  est <- na.omit(estimates)\n  m <- mean(est)\n  v <- var(est)\n  bias <- m - truth\n  mse <- mean((est - truth)^2)\n  c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n  "Full Model (sfm)"    = sfm,\n  "Half Model (shm)"    = shm,\n  "Perfect A (shpa)"    = shpa,\n  "Perfect B (shpb)"    = shpb,\n  "Estimated B (sheb)"  = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n#                       Mean Variance     Bias Bias_Sq     MSE\n# Full Model (sfm)   0.66641  0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm)   0.66566  0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa)   0.66565  0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb)   0.64255  0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333  0.03325 -0.01334 0.00018 0.03342\n
\n

As you can see in the results above, the "Estimated B" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points ("Half Model"), but it does have a bias.

\n

UPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModelMeanVarianceBiasBias_SqMSEValid_Runs
Full Model (N=40)0.665630.02497-0.001030.000000.024979947
Half Model (H=20)0.662890.05542-0.003770.000010.055439947
Estimated B0.643300.05259-0.023370.000550.053139947
Lavaan Pairwise0.658490.07174-0.008180.000070.071809947
\n

I am including the code i ran below:

\n
# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages("lavaan")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000  # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm  <- rep(NA, num_sims) # Full Model\nshm  <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- "\n  y1 ~ 1 + y0 + y2\n  y1 ~~ y1\n"\n\ncat("Running", num_sims, "simulations. Please wait...\\n")\n\nfor (i in 1:num_sims) {\n  # 1. Generate base standard normal variables\n  x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n  y0 <- x0 + x1;  y1 <- x1 + x2;  y2 <- x0 + x3\n  \n  # Subsets for missing data\n  y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n  \n  # Setup Lavaan data and summary statistics\n  y1_full <- c(y1h, rep(NA, n - h))\n  df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n  \n  mu <- colMeans(df, na.rm = TRUE)\n  cv <- cov(df, use = "pairwise.complete.obs")\n  \n  # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n  lav_fit <- tryCatch({\n    suppressWarnings(lavaan(model_syntax, \n                            sample.mean = mu, \n                            sample.cov = cv, \n                            sample.nobs = h))\n  }, error = function(e) {\n    NULL\n  })\n  \n  # 3. Only store estimates if Lavaan successfully converged\n  if (!is.null(lav_fit)) {\n    # Lavaan estimate\n    params <- parameterEstimates(lav_fit)\n    slav[i] <- params[params$lhs == \"y1\" & params$rhs == "y0", "est"]\n    \n    # Full Model (sfm)\n    sfm[i] <- coef(lm(y1 ~ y0 + y2))["y0"]\n    \n    # Half Model (shm)\n    shm[i] <- coef(lm(y1h ~ y0h + y2h))["y0h"]\n    \n    # Estimated B (sheb)\n    y0re <- residuals(lm(y0 ~ y2))\n    y0reh <- y0re[1:h]\n    y1rh <- residuals(lm(y1h ~ y2h))\n    sheb[i] <- coef(lm(y1rh ~ y0reh))["y0reh"]\n  }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n  est <- na.omit(estimates)\n  m <- mean(est)\n  v <- var(est)\n  bias <- m - truth\n  mse <- mean((est - truth)^2)\n  c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n  "Full Model (N=40)"      = sfm,\n  "Half Model (H=20)"      = shm,\n  "Estimated B"            = sheb,\n  "Lavaan Pairwise"        = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat("\\n--- Simulation Results ---\\n")\nprint(round(results_matrix, 5))\n
\n","question_title":"missing data: break multiple regression into stages; how?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how","split":"holdout"} {"accepted_answer":{"answer_html":"

As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)

\n

\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}

\n

I guess I must have been so eager to verify the original results that I conditioned myself to "see" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.

\n","answer_id":676993,"answer_text":"As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.","answer_url":"https://stats.stackexchange.com/a/676993","author":"Ettore S","author_url":"https://stats.stackexchange.com/users/513606/ettore-s","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-28T23:08:55+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676952,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-28T23:08:55+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"E33B0B4F-D54D-46E9-8E25-81C77E90B942","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-28T23:15:33+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"71D393BD-A8FB-4799-92AF-8FD04BFA27AE","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}],"score":0,"updated_at":"2026-08-28T23:15:33+00:00"},"answer_scores":[{"answer_id":676993,"score":0}],"answers":[{"answer_html":"

As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)

\n

\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}

\n

I guess I must have been so eager to verify the original results that I conditioned myself to "see" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.

\n","answer_id":676993,"answer_text":"As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.","answer_url":"https://stats.stackexchange.com/a/676993","author":"Ettore S","author_url":"https://stats.stackexchange.com/users/513606/ettore-s","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-28T23:08:55+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676952,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-28T23:08:55+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"E33B0B4F-D54D-46E9-8E25-81C77E90B942","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-28T23:15:33+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"71D393BD-A8FB-4799-92AF-8FD04BFA27AE","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}],"score":0,"updated_at":"2026-08-28T23:15:33+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Ettore S","author_url":"https://stats.stackexchange.com/users/513606/ettore-s","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-28T23:08:55+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"E33B0B4F-D54D-46E9-8E25-81C77E90B942","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-28T23:15:33+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"71D393BD-A8FB-4799-92AF-8FD04BFA27AE","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}],"source_url":"https://stats.stackexchange.com/a/676993"}],"question_author":"Ettore S","question_author_url":"https://stats.stackexchange.com/users/513606/ettore-s"},"code_blocks":[{"block_index":0,"code_text":" n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n","post_id":"stats:676952","sha256":"fe8ee795d4c0d8f93e4394aef787c0dca0457bed49da29328a16bd289f7ec7c0","source_url":"https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r"},{"block_index":1,"code_text":"> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n","post_id":"stats:676952","sha256":"72c9e124f3239ba3193dfc9d970d9609087fb1c5639638ee54e2bcf806db2189","source_url":"https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"dcc08cf0b10efb830071860d3f71e07b52ac03248dd10794ed1591cff2051ce8","id":"SCT-f4ee12e96468b941d56ccfc7","language":null,"library_or_tool":null,"problem_text":"In the context of zero-truncated negative binomial regression (see this other post (https://stats.stackexchange.com/q/676385/513606)) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper (https://www.jstor.org/stable/2096628)):\n\n\n\n\n$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$\n\n\n\n\nwhere:\n\n\n\n\n\n$y_i > 0 \\quad (i=1,2,\\dots,n)$ denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);\n\n\n\n\n$\\mathbf{x}^T_i$ is the $i$-th row of the regression data matrix;\n\n\n\n\n$\\boldsymbol{\\beta}$ is the unknown vector of regression coefficients (to be estimated);\n\n\n\n\n$\\alpha$ is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter ($\\alpha$ is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial see e.g., p.745, in this book (https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3)).\n\n\n\n\nAlso notice that the first summation is just the Hessian of the \"parent\" specification: that one works fine i.e., its elements are negative as expected.\n\n\n\n\n\nThe above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.\n\n\n\n\nMaybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, \"bound to\" have positive elements?\n\n\n\n\nI thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.\n\n\n\n\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.\n\n\n\n\nExample\n\n\n\n\nFor the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c(\"los\", \"died\", \"hmo\", \"type2\", \"type3\")] corresponds to the example reported in this STATA documentation for tnbreg (https://www.stata.com/manuals13/rtnbreg.pdf).\n\n\n\n\n\n\n\nInitialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;\n\n\n\n\n\n\n\n\n\nFollowing the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).\n\n\n\n\n\n\n\n\n\nWith X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:\n\n\n\n\n n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n\n\n\n\n\n\n\n\n\nAnd I get a positive Hessian - as I always do\n\n\n\n\n> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n\n\n\n\n\nAny thoughts? Am I missing anything trivial here? Thanks in advance.","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":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-24T16:36:39+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"07E45709-2DC4-449E-9EF1-F194BCC37017","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/07E45709-2DC4-449E-9EF1-F194BCC37017/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ettore S","profile_url":"https://stats.stackexchange.com/users/513606/ettore-s","user_type":"registered"},"created_at":"2026-08-24T16:44:54+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"62966E35-E17B-49AB-8C07-589F8E1C8272","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/62966E35-E17B-49AB-8C07-589F8E1C8272/view-source"}],"source_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:676952","source_record_sha256":"4a4f9d0298ec0a3a0b0ea3aa1b76558c1ae0486b2c0eeb4efb49397c3a9c2d44","source_url":"https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

In the context of zero-truncated negative binomial regression (see this other post) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper):

\n

$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$

\n

where:

\n
    \n
  • $y_i > 0 \\quad (i=1,2,\\dots,n)$ denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);
  • \n
  • $\\mathbf{x}^T_i$ is the $i$-th row of the regression data matrix;
  • \n
  • $\\boldsymbol{\\beta}$ is the unknown vector of regression coefficients (to be estimated);
  • \n
  • $\\alpha$ is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter ($\\alpha$ is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial see e.g., p.745, in this book).
  • \n
  • Also notice that the first summation is just the Hessian of the "parent" specification: that one works fine i.e., its elements are negative as expected.
  • \n
\n

The above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.

\n

Maybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, "bound to" have positive elements?

\n

I thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.

\n

I appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.

\n

Example

\n

For the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c("los", "died", "hmo", "type2", "type3")] corresponds to the example reported in this STATA documentation for tnbreg.

\n
    \n
  • Initialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;

    \n
  • \n
  • Following the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).

    \n
  • \n
  • With X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:

    \n
     n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n   phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n   phi <-  (1/(1 + p_theta*p_lambda)^p_alpha) \n   H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n   H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) /  (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n   x <- X[i,]\n   x <- as.numeric(x)\n   outprod_X <- (x %o% x) \n   A <- H_parent[i]\n   if(zerotrunc){\n     B <- H_zt_A[i]\n     C <- H_zt_B[i]\n   } else {\n     B <- C <- 0\n   }\n   Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X     \n }\n
    \n
  • \n
\n

And I get a positive Hessian - as I always do

\n
> Hessian_iter\n          [,1]      [,2]      [,3]      [,4]      [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,]  53431.28 53431.282  6036.786 12451.468 14079.196\n[3,]  24465.22  6036.786 24465.222  4528.242  1145.349\n[4,]  43243.07 12451.468  4528.242 43243.069     0.000\n[5,]  39578.77 14079.196  1145.349     0.000 39578.773\n
\n

Any thoughts? Am I missing anything trivial here? Thanks in advance.

\n","question_title":"Hessian with invariably positive elements for zero-truncated negative binomial regression","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r","split":"train"} {"accepted_answer":{"answer_html":"

You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).

\n

In your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being "other" or "everything else", or in this specific case, "anything but seagrass".

\n
\n

could I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?

\n
\n

Yes, that sounds OK. The relationship could be with something or things in the "not seagrass" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.

\n","answer_id":676973,"answer_text":"You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).\n\n\n\n\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being \"other\" or \"everything else\", or in this specific case, \"anything but seagrass\".\n\n\n\n\n\n\n\ncould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\n\n\n\nYes, that sounds OK. The relationship could be with something or things in the \"not seagrass\" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.","answer_url":"https://stats.stackexchange.com/a/676973","author":"Gavin Simpson","author_url":"https://stats.stackexchange.com/users/1390/gavin-simpson","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-27T08:11:49+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676971,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Gavin Simpson","profile_url":"https://stats.stackexchange.com/users/1390/gavin-simpson","user_type":"registered"},"created_at":"2026-08-27T08:11:49+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"091B2890-FB1C-44AC-85E1-2C6A5AD73A18","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/091B2890-FB1C-44AC-85E1-2C6A5AD73A18/view-source"}],"score":1,"updated_at":"2026-08-27T08:11:49+00:00"},"answer_scores":[{"answer_id":676973,"score":1}],"answers":[{"answer_html":"

You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).

\n

In your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being "other" or "everything else", or in this specific case, "anything but seagrass".

\n
\n

could I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?

\n
\n

Yes, that sounds OK. The relationship could be with something or things in the "not seagrass" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.

\n","answer_id":676973,"answer_text":"You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).\n\n\n\n\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being \"other\" or \"everything else\", or in this specific case, \"anything but seagrass\".\n\n\n\n\n\n\n\ncould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\n\n\n\nYes, that sounds OK. The relationship could be with something or things in the \"not seagrass\" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.","answer_url":"https://stats.stackexchange.com/a/676973","author":"Gavin Simpson","author_url":"https://stats.stackexchange.com/users/1390/gavin-simpson","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-27T08:11:49+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676971,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Gavin Simpson","profile_url":"https://stats.stackexchange.com/users/1390/gavin-simpson","user_type":"registered"},"created_at":"2026-08-27T08:11:49+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"091B2890-FB1C-44AC-85E1-2C6A5AD73A18","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/091B2890-FB1C-44AC-85E1-2C6A5AD73A18/view-source"}],"score":1,"updated_at":"2026-08-27T08:11:49+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Gavin Simpson","author_url":"https://stats.stackexchange.com/users/1390/gavin-simpson","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Gavin Simpson","profile_url":"https://stats.stackexchange.com/users/1390/gavin-simpson","user_type":"registered"},"created_at":"2026-08-27T08:11:49+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"091B2890-FB1C-44AC-85E1-2C6A5AD73A18","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/091B2890-FB1C-44AC-85E1-2C6A5AD73A18/view-source"}],"source_url":"https://stats.stackexchange.com/a/676973"}],"question_author":"Nate","question_author_url":"https://stats.stackexchange.com/users/337106/nate"},"code_blocks":[{"block_index":0,"code_text":"Count ~ All seagrass cover (%) + random site intercept\n","post_id":"stats:676971","sha256":"0fd0fc0c920f1110fc94144ab84ea05549367bf8f4d87ca0be2c46bdf101d14f","source_url":"https://stats.stackexchange.com/questions/676971/acceptable-conclusions-to-draw-from-incomplete-compositional-data-as-a-model-cov"},{"block_index":1,"code_text":"# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+ total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+ mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+ filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11 1 43.5 14.0 24.4 8.8 15.6 0 0 5.1\n90 C-2019-3-5-27 3 82.0 43.7 30.2 17.1 13.1 0 0 8.1\n70 C-2018-9-10-10 1 51.5 14.4 18.3 16.6 1.7 0 0 18.8\n79 C-2019-3-3-41 4 80.5 26.4 43.3 42.5 0.8 0 0 10.8\n116 C-2020-9-4-27 2 92.5 17.1 49.0 28.5 20.5 0 0 26.4\n14 C-2013-9-8-6 1 100.0 22.5 15.3 0.0 15.3 0 0 62.2\n126 C-2022-2-28-44 1 58.0 16.0 23.5 6.0 17.5 0 0 18.5\n62 C-2017-3-13-17 2 88.0 48.5 28.6 28.5 0.1 0 0 10.9\n4 C-2013-9-3-43 1 51.0 8.8 40.7 40.5 0.2 0 0 1.5\n132 C-2023-3-6-40 4 55.0 17.5 30.0 19.0 11.0 0 0 7.5\n","post_id":"stats:676971","sha256":"b1100c502751f045ff1b651b04807a59d3a1207fc2d8be9e5c39703fe2c3c434","source_url":"https://stats.stackexchange.com/questions/676971/acceptable-conclusions-to-draw-from-incomplete-compositional-data-as-a-model-cov"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"37ebf4ccab8f61f92a8514f0cd49ce5b0eb1fb9803b4c1c45ea16b53f78655e0","id":"SCT-3e8ad75c79031fef967e9fe5","language":null,"library_or_tool":null,"problem_text":"What can be inferred about the relationship between an outcome and a predictor variable (in a statistical model) that is only a piece of compositional data?\n\n\n\n\nI have submerged aquatic vegetation data (underwater seagrass, algae, etc.) by survey calendar year, month, day, and site (CYR_Keyfield). I want to model fish counts vs seagrass (only) cover, but seagrass is just a piece of total cover (ave_sav) in terms of area surveyed. The problem, as I see it, is when seagrass cover=0, that doesn't mean \"no vegetation cover at all\". I have background literature for why I think seagrass specifically is important, but I'm not sure the effect of seagrass can be separated without a proper control (downside of observational studies). It is analogous to testing the effects of \"drug A\", but not accounting for \"drug B\" mixed in. Modeling rows with seagrass-only cover removes about 90% of my data, so that's out.\n\n\n\n\nCount ~ All seagrass cover (%) + random site intercept\n\n\n\n\n\nCould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\nWould this be sufficient to avoid a claim for a causal link?\n\n\n\n\nThis is observational data where each site is surveyed 10x for an average % cover of aquatic vegetation (out of 100% of total area surveyed and average is 1 m$^2$ cover). total_count is fish abundance.\n\n\n\n\nData:\n\n\n\n\n# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+ total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+ mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+ filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11 1 43.5 14.0 24.4 8.8 15.6 0 0 5.1\n90 C-2019-3-5-27 3 82.0 43.7 30.2 17.1 13.1 0 0 8.1\n70 C-2018-9-10-10 1 51.5 14.4 18.3 16.6 1.7 0 0 18.8\n79 C-2019-3-3-41 4 80.5 26.4 43.3 42.5 0.8 0 0 10.8\n116 C-2020-9-4-27 2 92.5 17.1 49.0 28.5 20.5 0 0 26.4\n14 C-2013-9-8-6 1 100.0 22.5 15.3 0.0 15.3 0 0 62.2\n126 C-2022-2-28-44 1 58.0 16.0 23.5 6.0 17.5 0 0 18.5\n62 C-2017-3-13-17 2 88.0 48.5 28.6 28.5 0.1 0 0 10.9\n4 C-2013-9-3-43 1 51.0 8.8 40.7 40.5 0.2 0 0 1.5\n132 C-2023-3-6-40 4 55.0 17.5 30.0 19.0 11.0 0 0 7.5","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":"Nate","profile_url":"https://stats.stackexchange.com/users/337106/nate","user_type":"registered"},"created_at":"2026-08-26T20:02:31+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"BBA3A123-C04E-4867-9529-FDABB64EDA28","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/BBA3A123-C04E-4867-9529-FDABB64EDA28/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-08-27T08:29:59+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"2C063616-3FA6-44EE-924F-76F90F6F8FF5","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2C063616-3FA6-44EE-924F-76F90F6F8FF5/view-source"},{"content_license":null,"contributor":{"display_name":"kjetil b halvorsen","profile_url":"https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen","user_type":"moderator"},"created_at":"2026-08-27T13:02:45+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"20074645-B552-43C0-B76B-009D7B7615A0","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/20074645-B552-43C0-B76B-009D7B7615A0/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-27T13:05:23+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"F65BAED3-ACE9-40FD-9E99-FB55CD1FAA2F","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/F65BAED3-ACE9-40FD-9E99-FB55CD1FAA2F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nate","profile_url":"https://stats.stackexchange.com/users/337106/nate","user_type":"registered"},"created_at":"2026-08-27T13:19:25+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"55EC26AD-487A-4FD1-B6E0-348E7600A650","revision_number":4,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/55EC26AD-487A-4FD1-B6E0-348E7600A650/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:676971","source_record_sha256":"3965187a26bfae45c62339895a3d79b2883bcdc3382d9a15d11668edea78dd09","source_url":"https://stats.stackexchange.com/questions/676971/acceptable-conclusions-to-draw-from-incomplete-compositional-data-as-a-model-cov","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

What can be inferred about the relationship between an outcome and a predictor variable (in a statistical model) that is only a piece of compositional data?

\n

I have submerged aquatic vegetation data (underwater seagrass, algae, etc.) by survey calendar year, month, day, and site (CYR_Keyfield). I want to model fish counts vs seagrass (only) cover, but seagrass is just a piece of total cover (ave_sav) in terms of area surveyed. The problem, as I see it, is when seagrass cover=0, that doesn't mean "no vegetation cover at all". I have background literature for why I think seagrass specifically is important, but I'm not sure the effect of seagrass can be separated without a proper control (downside of observational studies). It is analogous to testing the effects of "drug A", but not accounting for "drug B" mixed in. Modeling rows with seagrass-only cover removes about 90% of my data, so that's out.

\n
Count ~ All seagrass cover (%) + random site intercept\n
\n

Could I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?

\n

Would this be sufficient to avoid a claim for a causal link?

\n

This is observational data where each site is surveyed 10x for an average % cover of aquatic vegetation (out of 100% of total area surveyed and average is 1 m$^2$ cover). total_count is fish abundance.

\n

Data:

\n
# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+                                     total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+                              mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+                              filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n      CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11           1    43.5         14.0         24.4    8.8   15.6      0      0    5.1\n90   C-2019-3-5-27           3    82.0         43.7         30.2   17.1   13.1      0      0    8.1\n70  C-2018-9-10-10           1    51.5         14.4         18.3   16.6    1.7      0      0   18.8\n79   C-2019-3-3-41           4    80.5         26.4         43.3   42.5    0.8      0      0   10.8\n116  C-2020-9-4-27           2    92.5         17.1         49.0   28.5   20.5      0      0   26.4\n14    C-2013-9-8-6           1   100.0         22.5         15.3    0.0   15.3      0      0   62.2\n126 C-2022-2-28-44           1    58.0         16.0         23.5    6.0   17.5      0      0   18.5\n62  C-2017-3-13-17           2    88.0         48.5         28.6   28.5    0.1      0      0   10.9\n4    C-2013-9-3-43           1    51.0          8.8         40.7   40.5    0.2      0      0    1.5\n132  C-2023-3-6-40           4    55.0         17.5         30.0   19.0   11.0      0      0    7.5\n
\n","question_title":"Acceptable conclusions to draw from incomplete compositional data as a model covariate?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/676971/acceptable-conclusions-to-draw-from-incomplete-compositional-data-as-a-model-cov","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":677001,"score":6}],"answers":[{"answer_html":"

Welcome to CV.
\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not "help"...

\n

First, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.
\nNote that the "typical" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.
\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.

\n

Wrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).
\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).

\n

Last, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n\"Topography\"\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?
\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.
\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...
\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?
\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).
\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.
\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).

\n","answer_id":677001,"answer_text":"Welcome to CV.\n\nThis will not be an answer to your direct questions, nor will it be a particularly \"statistical\" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not \"help\"...\n\n\n\n\nFirst, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.\n\nNote that the \"typical\" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.\n\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.\n\n\n\n\nWrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).\n\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).\n\n\n\n\nLast, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n[image: Topography; source: https://i.sstatic.net/TjqmodJj.jpg] (https://i.sstatic.net/TjqmodJj.jpg)\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?\n\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.\n\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...\n\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?\n\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).\n\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.\n\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).","answer_url":"https://stats.stackexchange.com/a/677001","author":"jginestet","author_url":"https://stats.stackexchange.com/users/380096/jginestet","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-29T20:57:23+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676997,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-08-29T20:57:23+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"DAC7BF38-AE45-4623-9327-87A8C22E642C","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/DAC7BF38-AE45-4623-9327-87A8C22E642C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-08-29T22:37:29+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"041DF0BE-0161-4865-A81B-94B540D8D9F9","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/041DF0BE-0161-4865-A81B-94B540D8D9F9/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-08-30T15:10:21+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"624A7F3B-1066-4608-8806-E117E3FA25A5","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/624A7F3B-1066-4608-8806-E117E3FA25A5/view-source"}],"score":6,"updated_at":"2026-08-30T15:10:21+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"jginestet","author_url":"https://stats.stackexchange.com/users/380096/jginestet","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-08-29T20:57:23+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"DAC7BF38-AE45-4623-9327-87A8C22E642C","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/DAC7BF38-AE45-4623-9327-87A8C22E642C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-08-29T22:37:29+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"041DF0BE-0161-4865-A81B-94B540D8D9F9","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/041DF0BE-0161-4865-A81B-94B540D8D9F9/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-08-30T15:10:21+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"624A7F3B-1066-4608-8806-E117E3FA25A5","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/624A7F3B-1066-4608-8806-E117E3FA25A5/view-source"}],"source_url":"https://stats.stackexchange.com/a/677001"}],"question_author":"yuen kei","question_author_url":"https://stats.stackexchange.com/users/516045/yuen-kei"},"code_blocks":[{"block_index":0,"code_text":"data(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n","post_id":"stats:676997","sha256":"23b3b5b39bc0cb13c12c87ccd189366e10e7b70ab1d9469fbec0536fc8e68a7f","source_url":"https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"34c8cf09713a56d442184f5e09ddd7f53aa41a01ed26ac35d4d292e5f6bcad3f","id":"SCT-ca258033a99271411716e7c8","language":["R"],"library_or_tool":null,"problem_text":"I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.\n\n\n\n\nHere is an example of how the data is collected:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Woh1NewX.png] (https://i.sstatic.net/Woh1NewX.png)\n\n\n\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.\n\n\n\n\nWhat I did to solve the issue:\n\n\n\n\n\nDuplicated timestamps\n\n\n\n\nDuplicated location points\n\n\n\n\nACC > 50 (Accuracy estimator in metres)\n\n\n\n\n\nThis left me with ~3000 rows of data for each cat.\n\n\n\n\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:\n\n\n\n\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n\n\n\n\n\nHere is the resulting home range plots of 1 cat:\n[image: L: Home range from wAKDE, R: Home range from AKDE ; source: https://i.sstatic.net/kXgSIQb8.png] (https://i.sstatic.net/kXgSIQb8.png)\n\n\n\n\nHere is the summary of wAKDE and AKDE respectively:\n[image: L: wAKDE, R: AKDE; source: https://i.sstatic.net/bZFkYz3U.png] (https://i.sstatic.net/bZFkYz3U.png)\n\n\n\n\nHere is the plot points of 1 cat across the campus (~2.5 months of data):\n[image: Plot points generated from R; source: https://i.sstatic.net/I6TIxhWk.png] (https://i.sstatic.net/I6TIxhWk.png)\n\n\n\n\nThe issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.\n\n\n\n\nMy questions:\n\n\n\n\n\nHow do I thin out my data? Other than removing obvious outliers, I tried to filter the data by creating new cluster points (in R I attempted to create a function to cluster points within a certain stationary threshold, and the centroid of this point would be the new point)\n\n\n\n\nHow do I account for inaccuracies, especially because this technology is quite new and the only accuracy estimator I have is ACC which I am unsure of how to calibrate it so that I can account for it in the ctmm package.\n\n\n\n\nWhy is the home range a circle?\n\n\n\n\nShould I be using AKDE to find home range or BBMM (Brownian bridge movement model)? BBMM which is better equipped to deal with auto-correlated and clustered position data than KDE home range estimator commonly used in wildlife studies. Specifically, BBMM allows estimation of probabilistic space-use, while accounting for position error and the uncertainty about paths taken between consecutive positions.\n\n\n\n\n\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)","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":"yuen kei","profile_url":"https://stats.stackexchange.com/users/516045/yuen-kei","user_type":"registered"},"created_at":"2026-08-29T12:41:14+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"D14E0134-8761-4D18-9603-809C2EE8BF6C","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/D14E0134-8761-4D18-9603-809C2EE8BF6C/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-30T03:37:51+00:00","raw_file":"raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json","raw_sha256":"75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe","revision_guid":"9EC2BF4F-7493-47E5-9507-BE468E30BE43","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/9EC2BF4F-7493-47E5-9507-BE468E30BE43/view-source"}],"source_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:676997","source_record_sha256":"9c2984f292cd41aaafcc94755e7deeef2e7a2a9ab27f90afbe8d22b782ef388c","source_url":"https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.

\n

Here is an example of how the data is collected:

\n

\"enter

\n

For finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.

\n

What I did to solve the issue:

\n
    \n
  1. Duplicated timestamps
  2. \n
  3. Duplicated location points
  4. \n
  5. ACC > 50 (Accuracy estimator in metres)
  6. \n
\n

This left me with ~3000 rows of data for each cat.

\n

Using ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:

\n
data(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("weighted OUF AKDE"["C"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("OUF AKDE"["C"]))\n
\n

Here is the resulting home range plots of 1 cat:\n\"L:

\n

Here is the summary of wAKDE and AKDE respectively:\n\"L:

\n

Here is the plot points of 1 cat across the campus (~2.5 months of data):\n\"Plot

\n

The issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.

\n

My questions:

\n
    \n
  1. How do I thin out my data? Other than removing obvious outliers, I tried to filter the data by creating new cluster points (in R I attempted to create a function to cluster points within a certain stationary threshold, and the centroid of this point would be the new point)
  2. \n
  3. How do I account for inaccuracies, especially because this technology is quite new and the only accuracy estimator I have is ACC which I am unsure of how to calibrate it so that I can account for it in the ctmm package.
  4. \n
  5. Why is the home range a circle?
  6. \n
  7. Should I be using AKDE to find home range or BBMM (Brownian bridge movement model)? BBMM which is better equipped to deal with auto-correlated and clustered position data than KDE home range estimator commonly used in wildlife studies. Specifically, BBMM allows estimation of probabilistic space-use, while accounting for position error and the uncertainty about paths taken between consecutive positions.
  8. \n
\n

Apologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)

\n","question_title":"Asking for advice on cleaning GPS data from BLE trackers","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers","split":"train"} {"accepted_answer":{"answer_html":"

I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:

\n
# library(tidyverse)\n> shiny_toad %>%  group_by(total_count) %>% \n+   summarise(n()) #%>% \n# A tibble: 8 × 2\n  total_count `n()`\n        <dbl> <int>\n1           0   985\n2           1   102\n3           2    34\n4           3    10\n5           4    10\n6           5     2\n7           7     1\n8          18     1\n
\n

As a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.

\n

I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:

\n
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n  points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n
\n

\"plotting

\n","answer_id":677089,"answer_text":"I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n \n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\n\n\n\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so \"fine\". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.\n\n\n\n\nI couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:\n\n\n\n\nx <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n\n\n\n[image: plotting total counts vs model prediction underlayed with the red simulations from DHARMa. Hard to describe what we see exactly. ; source: https://i.sstatic.net/MLdk1fpB.png] (https://i.sstatic.net/MLdk1fpB.png)","answer_url":"https://stats.stackexchange.com/a/677089","author":"Lukas Lohse","author_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-06T14:51:53+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677079,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lukas Lohse","profile_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","user_type":"registered"},"created_at":"2026-09-06T14:51:53+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"B8B4DF5B-86F9-405A-8C4F-7FB2BEF69F45","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/B8B4DF5B-86F9-405A-8C4F-7FB2BEF69F45/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-06T17:41:01+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"5F1F9165-30E6-48DD-BBC0-9D1AC05FFE35","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/5F1F9165-30E6-48DD-BBC0-9D1AC05FFE35/view-source"}],"score":5,"updated_at":"2026-09-06T17:41:01+00:00"},"answer_scores":[{"answer_id":677089,"score":5}],"answers":[{"answer_html":"

I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:

\n
# library(tidyverse)\n> shiny_toad %>%  group_by(total_count) %>% \n+   summarise(n()) #%>% \n# A tibble: 8 × 2\n  total_count `n()`\n        <dbl> <int>\n1           0   985\n2           1   102\n3           2    34\n4           3    10\n5           4    10\n6           5     2\n7           7     1\n8          18     1\n
\n

As a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.

\n

I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:

\n
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n  points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n
\n

\"plotting

\n","answer_id":677089,"answer_text":"I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n \n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\n\n\n\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so \"fine\". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.\n\n\n\n\nI couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:\n\n\n\n\nx <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n\n\n\n[image: plotting total counts vs model prediction underlayed with the red simulations from DHARMa. Hard to describe what we see exactly. ; source: https://i.sstatic.net/MLdk1fpB.png] (https://i.sstatic.net/MLdk1fpB.png)","answer_url":"https://stats.stackexchange.com/a/677089","author":"Lukas Lohse","author_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-06T14:51:53+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677079,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lukas Lohse","profile_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","user_type":"registered"},"created_at":"2026-09-06T14:51:53+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"B8B4DF5B-86F9-405A-8C4F-7FB2BEF69F45","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/B8B4DF5B-86F9-405A-8C4F-7FB2BEF69F45/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-06T17:41:01+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"5F1F9165-30E6-48DD-BBC0-9D1AC05FFE35","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/5F1F9165-30E6-48DD-BBC0-9D1AC05FFE35/view-source"}],"score":5,"updated_at":"2026-09-06T17:41:01+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Lukas Lohse","author_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lukas Lohse","profile_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","user_type":"registered"},"created_at":"2026-09-06T14:51:53+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"B8B4DF5B-86F9-405A-8C4F-7FB2BEF69F45","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/B8B4DF5B-86F9-405A-8C4F-7FB2BEF69F45/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-06T17:41:01+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"5F1F9165-30E6-48DD-BBC0-9D1AC05FFE35","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/5F1F9165-30E6-48DD-BBC0-9D1AC05FFE35/view-source"}],"source_url":"https://stats.stackexchange.com/a/677089"}],"question_author":"Nate","question_author_url":"https://stats.stackexchange.com/users/337106/nate"},"code_blocks":[{"block_index":0,"code_text":"shiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = \"no food\")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) +\n s(DO, bs=\"ts\", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n","post_id":"stats:677079","sha256":"89b2e690aed756ed58acca94fca99df4cf24001efaaf6e14043cc83121702b61","source_url":"https://stats.stackexchange.com/questions/677079/dharma-are-long-tails-in-dispersion-plot-a-problem"},{"block_index":0,"code_text":"# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n \n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n","post_id":677089,"sha256":"7c798d46ddd213bb87addedf2566105e00112c0f4a5092183b7fa5efb3c12998","source_url":"https://stats.stackexchange.com/a/677089"},{"block_index":1,"code_text":"x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n","post_id":677089,"sha256":"d1d84429d25c76c16bd3caaa082778a894ade206540b18157ef35cf8497c1493","source_url":"https://stats.stackexchange.com/a/677089"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"c4703328fafdb6b71f29af1e8463edc3575effa1b91d7fa371880b0b9a1ed7c4","id":"SCT-58d55cbca671fa1aae2f575a","language":null,"library_or_tool":["mgcv"],"problem_text":"Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.\n\n\n\n\nData here (https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv)\n\n\n\n\nshiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = \"no food\")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) +\n s(DO, bs=\"ts\", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/JpiINT52.png] (https://i.sstatic.net/JpiINT52.png)","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":"Nate","profile_url":"https://stats.stackexchange.com/users/337106/nate","user_type":"registered"},"created_at":"2026-09-05T17:50:46+00:00","raw_file":"raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json","raw_sha256":"18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04","revision_guid":"62485478-1E70-4507-A25A-EFD7CF98BE71","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/62485478-1E70-4507-A25A-EFD7CF98BE71/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nate","profile_url":"https://stats.stackexchange.com/users/337106/nate","user_type":"registered"},"created_at":"2026-09-05T18:00:15+00:00","raw_file":"raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json","raw_sha256":"18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04","revision_guid":"20C1E059-9409-4237-A047-3AC90CDF12F1","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/20C1E059-9409-4237-A047-3AC90CDF12F1/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nate","profile_url":"https://stats.stackexchange.com/users/337106/nate","user_type":"registered"},"created_at":"2026-09-06T11:10:30+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"218741D1-87E1-45D3-9356-2175B506F115","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/218741D1-87E1-45D3-9356-2175B506F115/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nate","profile_url":"https://stats.stackexchange.com/users/337106/nate","user_type":"registered"},"created_at":"2026-09-06T16:02:30+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"68679B7E-46AA-465C-8DEB-E7300F26A45C","revision_number":4,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/68679B7E-46AA-465C-8DEB-E7300F26A45C/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-09-06T16:44:53+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"FCE33A0B-2FF0-443A-AAE5-C039C64F1D4A","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/FCE33A0B-2FF0-443A-AAE5-C039C64F1D4A/view-source"}],"source_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:677079","source_record_sha256":"fbd359dca8febbc21a6e921bd68ddbe855d864d52e811aaa65fcf915878120e0","source_url":"https://stats.stackexchange.com/questions/677079/dharma-are-long-tails-in-dispersion-plot-a-problem","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.

\n

Data here

\n
shiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = "no food")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n  full_model <- gam(total_count ~ \n              \n              offset(log(area_sampled)) +\n              \n              s(CYR, by = fSeason) +\n              fSeason + \n              \n              s(sal, bs="ts", k=5) +\n              s(DO, bs="ts", k=5) +\n\n              s(ave_sav, by = fDiet_presence) +\n              fDiet_presence +\n              \n              s(fSite, bs="re"),\n            \n            data = shiny_toad,\n            method = "REML", \n            family = nb(link = "log"),\n            select = FALSE, \n            \n            drop.unused.levels = FALSE, \n            control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n    DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n    simulated\n\ndata:  simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n
\n

\"enter

\n","question_title":"DHARMa: Are long tails in dispersion plot a problem?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677079/dharma-are-long-tails-in-dispersion-plot-a-problem","split":"train"} {"accepted_answer":{"answer_html":"

The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.

\n

My fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.

\n
fit_mle <- function(x, k) {\n  m1 <- mean(x)\n  \n  if (k == 1 || all(x == 0) || all(x == k)) {\n    a <- max(m1*100/k, 1e-5)\n    b <- max(100 - a, 1e-5)\n    V <- NA\n  } else {\n    n <- length(x)\n    z1 <- sort(unique(x))\n    n1 <- tabulate(match(x, z1))\n    z2 <- sort(unique(k - x))\n    n2 <- tabulate(match(k - x, z2))\n    m2 <- mean(x^2)\n    d <- 1/(k*(m2/m1 - m1) - k + m1)\n    a <- (k*m1 - m2)*d\n    b <- (k - m1)*(k - m2/m1)*d\n    \n    if (!is.finite(a) || d < 0) {\n      a <- max(m1*100/k, 1e-5)\n      b <- max(100 - a, 1e-5)\n    } else if (a <= 0 || b <= 0) {\n      a <- max(m1*0.1/k, 1e-5)\n      b <- max(0.1 - a, 1e-5)\n    }\n    \n    for (i in 1:100) {\n      ab <- a + b\n      t1 <- digamma(ab) - digamma(k + ab)\n      S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n      S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n      t2 <- trigamma(ab) - trigamma(k + ab)\n      J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n      J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n      J12 <- a*b*t2*n\n      if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n      step1 <- (J22*S1 - J12*S2)/detJ\n      step2 <- (J11*S2 - J12*S1)/detJ\n      if (abs(step1) + abs(step2) < 1e-8) break\n      step_norm <- 2/sqrt(step1^2 + step2^2)\n      \n      if (step_norm < 1) {\n        step1 <- step1*step_norm\n        step2 <- step2*step_norm\n      }\n      \n      a <- a*exp(-step1)\n      b <- b*exp(-step2)\n    }\n    \n    g <- a*b/(a + b)^2\n    V <- -(J11 + J22 + 2*J12)*g^2/detJ\n  }\n  \n  c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n
\n

\"enter

\n

\"enter

\n

Full code:

\n
library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true  <- 0.249\nn_vals  <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals  <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR       <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n  nu <- mu * (1 - mu) / v - 1\n  rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n  xx <<- x\n  kk <<- k\n  m1 <- mean(x)\n  \n  if (k == 1 || all(x == 0) || all(x == k)) {\n    a <- max(m1*100/k, 1e-5)\n    b <- max(100 - a, 1e-5)\n    V <- NA\n  } else {\n    n <- length(x)\n    z1 <- sort(unique(x))\n    n1 <- tabulate(match(x, z1))\n    z2 <- sort(unique(k - x))\n    n2 <- tabulate(match(k - x, z2))\n    m2 <- mean(x^2)\n    d <- 1/(k*(m2/m1 - m1) - k + m1)\n    a <- (k*m1 - m2)*d\n    b <- (k - m1)*(k - m2/m1)*d\n    \n    if (!is.finite(a) || d < 0) {\n      a <- max(m1*100/k, 1e-5)\n      b <- max(100 - a, 1e-5)\n    } else if (a <= 0 || b <= 0) {\n      a <- max(m1*0.1/k, 1e-5)\n      b <- max(0.1 - a, 1e-5)\n    }\n    \n    for (i in 1:100) {\n      ab <- a + b\n      t1 <- digamma(ab) - digamma(k + ab)\n      S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n      S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n      t2 <- trigamma(ab) - trigamma(k + ab)\n      J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n      J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n      J12 <- a*b*t2*n\n      if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n      step1 <- (J22*S1 - J12*S2)/detJ\n      step2 <- (J11*S2 - J12*S1)/detJ\n      if (abs(step1) + abs(step2) < 1e-8) break\n      step_norm <- 2/sqrt(step1^2 + step2^2)\n      \n      if (step_norm < 1) {\n        step1 <- step1*step_norm\n        step2 <- step2*step_norm\n      }\n      \n      a <- a*exp(-step1)\n      b <- b*exp(-step2)\n    }\n    \n    g <- a*b/(a + b)^2\n    V <- -(J11 + J22 + 2*J12)*g^2/detJ\n  }\n  \n  c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n  p <- x / k\n  c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n  s <- sqrt(V); ok <- is.finite(m)\n  data.frame(mean_estimate      = mean(m[ok]),\n             bias               = mean(m[ok]) - mu,\n             mc_se              = sd(m[ok]) / sqrt(sum(ok)),\n             sd_estimate        = sd(m[ok]),\n             variance_estimate  = mean(V, na.rm = TRUE),\n             length_of_interval = mean(2 * z * s, na.rm = TRUE),\n             coverage           = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n  cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n  e <- replicate(R, { x <- sim_data(n, k, mu, v)\n  rbind(fit_mom(x, k), fit_mle(x, k)) })\n  cat(sprintf("done (%.1fs elapsed)\\n",\n              as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n  cbind(true_mean = mu, true_variance = v, n = n, k = k,\n        true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n        method = c("moments", "mle"),\n        rbind(score(e[1, 1, ], e[1, 2, ], mu),\n              score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng  <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n                          MoreArgs = list(R = R), i = seq_len(nrow(g)),\n                          tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c("true_mean", "true_variance", "n", "k", "true_var_of_mean", \n              "mean_estimate", "bias", "mc_se", "sd_estimate", \n              "variance_estimate", "length_of_interval", "coverage")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == "moments")\ndf_mle <- subset(res_df, method == "mle")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n  p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n    geom_line(linewidth = 0.5) +\n    geom_point(size = 1.5) +\n    labs(title = title, subtitle = subtitle, x = "n", y = y_label, color = "k") +\n    theme_bw() +\n    theme(legend.position = "bottom",\n          plot.title = element_text(hjust = 0),\n          plot.subtitle = element_text(hjust = 0))\n  \n  if (!is.null(hline)) {\n    p <- p + geom_hline(yintercept = hline, linetype = "dashed", linewidth = 0.5)\n  }\n  return(p)\n}\n\np1 <- make_panel(df_mom, "bias", "Moments: bias of the estimated mean", \n                 "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np2 <- make_panel(df_mle, "bias", "MLE: bias of the estimated mean", \n                 "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np3 <- make_panel(df_mom, "sd_estimate", "Moments: SD of the estimated mean", \n                 "Spread of the estimate across studies.", "SD")\np4 <- make_panel(df_mle, "sd_estimate", "MLE: SD of the estimated mean", \n                 "Spread of the estimate across studies.", "SD")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n  geom_line(linewidth = 0.5) +\n  geom_point(size = 1.5) +\n  geom_hline(yintercept = 0.95, linetype = "dashed") +\n  facet_grid(~ k, labeller = label_both) +\n  labs(title = "Coverage of the nominal 95% interval",\n       subtitle = "Share of 1000 intervals containing the true mean. Dashed line at 0.95.",\n       x = "n",\n       y = "coverage",\n       color = "method") +\n  theme_bw() +\n  theme(legend.position = "bottom",\n        strip.background = element_rect(fill = "grey90"))\n\nprint(p_cov)\n
\n","answer_id":677117,"answer_text":"The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)","answer_url":"https://stats.stackexchange.com/a/677117","author":"jblood94","author_url":"https://stats.stackexchange.com/users/214015/jblood94","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-09T13:02:57+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677094,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jblood94","profile_url":"https://stats.stackexchange.com/users/214015/jblood94","user_type":"registered"},"created_at":"2026-09-09T13:02:57+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"09E52470-6B69-4568-A8B3-D52476EA341B","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-16T13:07:32+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"20C3E36B-1564-462F-9257-5BBE5B9B70EF","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}],"score":3,"updated_at":"2026-09-09T13:02:57+00:00"},"answer_scores":[{"answer_id":677117,"score":3}],"answers":[{"answer_html":"

The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.

\n

My fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.

\n
fit_mle <- function(x, k) {\n  m1 <- mean(x)\n  \n  if (k == 1 || all(x == 0) || all(x == k)) {\n    a <- max(m1*100/k, 1e-5)\n    b <- max(100 - a, 1e-5)\n    V <- NA\n  } else {\n    n <- length(x)\n    z1 <- sort(unique(x))\n    n1 <- tabulate(match(x, z1))\n    z2 <- sort(unique(k - x))\n    n2 <- tabulate(match(k - x, z2))\n    m2 <- mean(x^2)\n    d <- 1/(k*(m2/m1 - m1) - k + m1)\n    a <- (k*m1 - m2)*d\n    b <- (k - m1)*(k - m2/m1)*d\n    \n    if (!is.finite(a) || d < 0) {\n      a <- max(m1*100/k, 1e-5)\n      b <- max(100 - a, 1e-5)\n    } else if (a <= 0 || b <= 0) {\n      a <- max(m1*0.1/k, 1e-5)\n      b <- max(0.1 - a, 1e-5)\n    }\n    \n    for (i in 1:100) {\n      ab <- a + b\n      t1 <- digamma(ab) - digamma(k + ab)\n      S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n      S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n      t2 <- trigamma(ab) - trigamma(k + ab)\n      J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n      J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n      J12 <- a*b*t2*n\n      if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n      step1 <- (J22*S1 - J12*S2)/detJ\n      step2 <- (J11*S2 - J12*S1)/detJ\n      if (abs(step1) + abs(step2) < 1e-8) break\n      step_norm <- 2/sqrt(step1^2 + step2^2)\n      \n      if (step_norm < 1) {\n        step1 <- step1*step_norm\n        step2 <- step2*step_norm\n      }\n      \n      a <- a*exp(-step1)\n      b <- b*exp(-step2)\n    }\n    \n    g <- a*b/(a + b)^2\n    V <- -(J11 + J22 + 2*J12)*g^2/detJ\n  }\n  \n  c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n
\n

\"enter

\n

\"enter

\n

Full code:

\n
library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true  <- 0.249\nn_vals  <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals  <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR       <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n  nu <- mu * (1 - mu) / v - 1\n  rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n  xx <<- x\n  kk <<- k\n  m1 <- mean(x)\n  \n  if (k == 1 || all(x == 0) || all(x == k)) {\n    a <- max(m1*100/k, 1e-5)\n    b <- max(100 - a, 1e-5)\n    V <- NA\n  } else {\n    n <- length(x)\n    z1 <- sort(unique(x))\n    n1 <- tabulate(match(x, z1))\n    z2 <- sort(unique(k - x))\n    n2 <- tabulate(match(k - x, z2))\n    m2 <- mean(x^2)\n    d <- 1/(k*(m2/m1 - m1) - k + m1)\n    a <- (k*m1 - m2)*d\n    b <- (k - m1)*(k - m2/m1)*d\n    \n    if (!is.finite(a) || d < 0) {\n      a <- max(m1*100/k, 1e-5)\n      b <- max(100 - a, 1e-5)\n    } else if (a <= 0 || b <= 0) {\n      a <- max(m1*0.1/k, 1e-5)\n      b <- max(0.1 - a, 1e-5)\n    }\n    \n    for (i in 1:100) {\n      ab <- a + b\n      t1 <- digamma(ab) - digamma(k + ab)\n      S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n      S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n      t2 <- trigamma(ab) - trigamma(k + ab)\n      J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n      J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n      J12 <- a*b*t2*n\n      if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n      step1 <- (J22*S1 - J12*S2)/detJ\n      step2 <- (J11*S2 - J12*S1)/detJ\n      if (abs(step1) + abs(step2) < 1e-8) break\n      step_norm <- 2/sqrt(step1^2 + step2^2)\n      \n      if (step_norm < 1) {\n        step1 <- step1*step_norm\n        step2 <- step2*step_norm\n      }\n      \n      a <- a*exp(-step1)\n      b <- b*exp(-step2)\n    }\n    \n    g <- a*b/(a + b)^2\n    V <- -(J11 + J22 + 2*J12)*g^2/detJ\n  }\n  \n  c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n  p <- x / k\n  c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n  s <- sqrt(V); ok <- is.finite(m)\n  data.frame(mean_estimate      = mean(m[ok]),\n             bias               = mean(m[ok]) - mu,\n             mc_se              = sd(m[ok]) / sqrt(sum(ok)),\n             sd_estimate        = sd(m[ok]),\n             variance_estimate  = mean(V, na.rm = TRUE),\n             length_of_interval = mean(2 * z * s, na.rm = TRUE),\n             coverage           = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n  cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n  e <- replicate(R, { x <- sim_data(n, k, mu, v)\n  rbind(fit_mom(x, k), fit_mle(x, k)) })\n  cat(sprintf("done (%.1fs elapsed)\\n",\n              as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n  cbind(true_mean = mu, true_variance = v, n = n, k = k,\n        true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n        method = c("moments", "mle"),\n        rbind(score(e[1, 1, ], e[1, 2, ], mu),\n              score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng  <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n                          MoreArgs = list(R = R), i = seq_len(nrow(g)),\n                          tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c("true_mean", "true_variance", "n", "k", "true_var_of_mean", \n              "mean_estimate", "bias", "mc_se", "sd_estimate", \n              "variance_estimate", "length_of_interval", "coverage")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == "moments")\ndf_mle <- subset(res_df, method == "mle")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n  p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n    geom_line(linewidth = 0.5) +\n    geom_point(size = 1.5) +\n    labs(title = title, subtitle = subtitle, x = "n", y = y_label, color = "k") +\n    theme_bw() +\n    theme(legend.position = "bottom",\n          plot.title = element_text(hjust = 0),\n          plot.subtitle = element_text(hjust = 0))\n  \n  if (!is.null(hline)) {\n    p <- p + geom_hline(yintercept = hline, linetype = "dashed", linewidth = 0.5)\n  }\n  return(p)\n}\n\np1 <- make_panel(df_mom, "bias", "Moments: bias of the estimated mean", \n                 "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np2 <- make_panel(df_mle, "bias", "MLE: bias of the estimated mean", \n                 "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np3 <- make_panel(df_mom, "sd_estimate", "Moments: SD of the estimated mean", \n                 "Spread of the estimate across studies.", "SD")\np4 <- make_panel(df_mle, "sd_estimate", "MLE: SD of the estimated mean", \n                 "Spread of the estimate across studies.", "SD")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n  geom_line(linewidth = 0.5) +\n  geom_point(size = 1.5) +\n  geom_hline(yintercept = 0.95, linetype = "dashed") +\n  facet_grid(~ k, labeller = label_both) +\n  labs(title = "Coverage of the nominal 95% interval",\n       subtitle = "Share of 1000 intervals containing the true mean. Dashed line at 0.95.",\n       x = "n",\n       y = "coverage",\n       color = "method") +\n  theme_bw() +\n  theme(legend.position = "bottom",\n        strip.background = element_rect(fill = "grey90"))\n\nprint(p_cov)\n
\n","answer_id":677117,"answer_text":"The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)","answer_url":"https://stats.stackexchange.com/a/677117","author":"jblood94","author_url":"https://stats.stackexchange.com/users/214015/jblood94","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-09T13:02:57+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677094,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jblood94","profile_url":"https://stats.stackexchange.com/users/214015/jblood94","user_type":"registered"},"created_at":"2026-09-09T13:02:57+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"09E52470-6B69-4568-A8B3-D52476EA341B","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-16T13:07:32+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"20C3E36B-1564-462F-9257-5BBE5B9B70EF","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}],"score":3,"updated_at":"2026-09-09T13:02:57+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"jblood94","author_url":"https://stats.stackexchange.com/users/214015/jblood94","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jblood94","profile_url":"https://stats.stackexchange.com/users/214015/jblood94","user_type":"registered"},"created_at":"2026-09-09T13:02:57+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"09E52470-6B69-4568-A8B3-D52476EA341B","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-16T13:07:32+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"20C3E36B-1564-462F-9257-5BBE5B9B70EF","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}],"source_url":"https://stats.stackexchange.com/a/677117"}],"question_author":"adamkostanov","question_author_url":"https://stats.stackexchange.com/users/512554/adamkostanov"},"code_blocks":[{"block_index":0,"code_text":"library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n","post_id":"stats:677094","sha256":"748b8957c64ad9c882e5131628ded56e236fa132e526ea16319627b14f44d2e8","source_url":"https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases"},{"block_index":0,"code_text":"fit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n","post_id":677117,"sha256":"51cc539111e4e5bb9577cca7f1743154014577b6d727c2354ce8054c03f21b29","source_url":"https://stats.stackexchange.com/a/677117"},{"block_index":1,"code_text":"library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)\n","post_id":677117,"sha256":"b749e1889b6f66b0bc1acd992da72507b9cf5e17536a32c9b5d036efb773fd2a","source_url":"https://stats.stackexchange.com/a/677117"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"41398da8dbd1ebc9dcacb20a9bea5d02a6156e28f540d556ce602153656b8645","id":"SCT-edb642b23b7857840f0eca98","language":null,"library_or_tool":null,"problem_text":"Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):\n\n\n\n\n$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$\n\n\n\n\n$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$\n\n\n\n\n$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$\n\n\n\n\nFor a single unit,\n\n\n\n\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\nand\n\n\n\n\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$\n\n\n\n\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).\n\n\n\n\nThe first way is with moments (I can show the manipulations if needed):\n\n\n\n\n$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$\n\n\n\n\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\n$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$\n\n\n\n\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).\n\n\n\n\nHere is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\n\n\n\n\nHere are the results:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/kEDelnub.png] (https://i.sstatic.net/kEDelnub.png)\n[image: enter image description here; source: https://i.sstatic.net/H3ywscwO.png] (https://i.sstatic.net/H3ywscwO.png)\n\n\n\n\nPrior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).\n\n\n\n\nWhy is this happening?","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-07T06:07:31+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"BE06C153-8C52-4CC0-883B-294D30B035A1","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/BE06C153-8C52-4CC0-883B-294D30B035A1/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-07T06:17:50+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"E476317C-DD27-4C9B-AE2F-6BCDF9875E56","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/E476317C-DD27-4C9B-AE2F-6BCDF9875E56/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-07T06:25:11+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"30B3CCCA-ABFC-44BA-A8AA-62F762C98FC8","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/30B3CCCA-ABFC-44BA-A8AA-62F762C98FC8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-07T06:33:19+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"2E412836-177B-410E-B0A8-2FD925F88199","revision_number":4,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2E412836-177B-410E-B0A8-2FD925F88199/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-07T06:41:52+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"246BB9D4-0913-4A5D-BA26-19A883E71D2E","revision_number":5,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/246BB9D4-0913-4A5D-BA26-19A883E71D2E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-07T08:45:32+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"06091D8C-4AF4-44C7-A257-DDB59EE43D39","revision_number":6,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/06091D8C-4AF4-44C7-A257-DDB59EE43D39/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-09T06:13:57+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"4B6B337A-AB66-48A4-9852-835642560D4F","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/4B6B337A-AB66-48A4-9852-835642560D4F/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-09T06:13:57+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"FF6141BB-F0C5-4F25-80CC-121B75A68FE8","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/FF6141BB-F0C5-4F25-80CC-121B75A68FE8/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-16T13:07:32+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"398480DB-D18F-4C34-B57A-2901985CD8FF","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/398480DB-D18F-4C34-B57A-2901985CD8FF/view-source"},{"content_license":null,"contributor":{"display_name":"adamkostanov","profile_url":"https://stats.stackexchange.com/users/512554/adamkostanov","user_type":"registered"},"created_at":"2026-09-16T13:07:32+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"E442CC1D-1B8D-4B82-A247-1B52D8C54699","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/E442CC1D-1B8D-4B82-A247-1B52D8C54699/view-source"}],"source_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:677094","source_record_sha256":"d0fd28efee92839bbe609b77d8e0f372bcfbbe48ef8c84384e4f288e712929c1","source_url":"https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):

\n

$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$

\n

$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$

\n

$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$

\n

$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$

\n

For a single unit,

\n

$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$

\n

and

\n

$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$

\n

There are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).

\n

The first way is with moments (I can show the manipulations if needed):

\n

$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$

\n

$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$

\n

$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$

\n

And the second way is using MLE (delta method for variances and log/exp constraint for optimization).

\n

Here is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):

\n
library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true  <- 0.249\nn_vals  <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals  <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR       <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n  nu <- mu * (1 - mu) / v - 1\n  rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n  length(x) * lbeta(exp(q[1]), exp(q[2])) -\n  sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n  n <- length(x)\n  o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = "BFGS",\n                 hessian = TRUE), silent = TRUE)\n  if (inherits(o, "try-error")) return(c(NA, NA))\n  a <- exp(o$par[1]); b <- exp(o$par[2])\n  g <- a * b / (a + b)^2 * c(1, -1)\n  V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n  ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n        V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n  c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n  p <- x / k\n  c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n  s <- sqrt(V); ok <- is.finite(m)\n  data.frame(mean_estimate      = mean(m[ok]),\n             bias               = mean(m[ok]) - mu,\n             mc_se              = sd(m[ok]) / sqrt(sum(ok)),\n             sd_estimate        = sd(m[ok]),\n             variance_estimate  = mean(V, na.rm = TRUE),\n             length_of_interval = mean(2 * z * s, na.rm = TRUE),\n             coverage           = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n  cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n  e <- replicate(R, { x <- sim_data(n, k, mu, v)\n                      rbind(fit_mom(x, k), fit_mle(x, k)) })\n  cat(sprintf("done (%.1fs elapsed)\\n",\n              as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n  cbind(true_mean = mu, true_variance = v, n = n, k = k,\n        true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n        method = c("moments", "mle"),\n        rbind(score(e[1, 1, ], e[1, 2, ], mu),\n              score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng  <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n                          MoreArgs = list(R = R), i = seq_len(nrow(g)),\n                          tot = nrow(g), t0 = t0))\n
\n

Here are the results:

\n

\"enter\n\"enter

\n

Prior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).

\n

Why is this happening?

\n","question_title":"Can coverage probability decrease as sample size increases?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":677108,"score":1}],"answers":[{"answer_html":"

Welcome to CV!

\n

So you want to compare 2 proportions; e.g. “Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?”.

\n

Well, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (aka crosstab). And the “canonical” tests are either a chi-square test, or a Fisher-exact test (aka Fisher-0Irwin test).
\nNow, using binomial CI’s will not really answer your 2 questions, unless the answer is obvious” if the 2 CI’s do not overlap, you have a significant difference. And if they overlap to a large extent, you do not have a significant difference. But in between, you can not simply eyeball the CI’s.
\nNow, given that you are dealing with (very?) low proportions or counts (how many F’s in a given class? Maybe 2-3?), the chi-square test is not recommended (it is based on a normal approximation, which is not warranted for such low proportions/counts). Nor for that matter are CI’s based on normal approximations, a group the Wilson CI belongs to. And forget about continuity corrections, they do not work properly with very small proportions.
\nSo you are left with the Fisher-exact test, or some newer versions of it (which are less “conservative, while remaining “exact”, that is based on exactly the binomial distribution), such as the Blaker test.

\n

But there is a subtlety in what you are trying to compare. On one hand, you have the proportion of A’s in one class: easy. On the other hand you have the proportion of A’s in all other MA courses (the scenario is the same for the other question, so I will only address the first). How do you express that 2nd proportion?
\nOne option is to simply take the count of all A grades in all other MA courses, and the count of all students enrolled in all other MA classes. And then you can/should indeed use a Fisher-exact (or a Blaker-exact) test. But this will weight each student equally, but not each class (the classes with a large enrollment are more heavily weighted than the classes with a low enrollment). That may be what you want (as it reflects the experience of all students enrolled in all other MA classes), but it may not.\nAn alternative would be to look at all the proportions in all other MA classes, and take the average of these proportions. This weights all classes equally (but not all students). In that case, your test can be done with a single CI. You compute an binomial CI (again using an exact method given your possibly low proportions/counts), and simply see if the average proportion in included in that CI. If it is not, you have established a significant difference (at what ever significance level you chose for the CI).

\n

Last, you ask about multiple comparisons. The fact that you compute multiple CI’s is not relevant; multiple comparisons only occur when you are making a comparison to a significance level (or checking if a CI contains 0, or 1).. And since you seem to only have 2 questions, then you are only making 2 comparisons.
\nThe cautious thing to do would be to use a multiple comparison correction (MCC). Given only 2 comparisons, just use Bonferroni, and halve your significance level.
\nBut bolder statisticians could argue that your 2 hypotheses are different, and independent. And therefore, a MCC is not warranted... (should a researcher correct for all the various hypotheses he/she will test in their career?). So depending on your ultimate goal (why only these 2 questions? what are you really trying to show), you may be able to dispense with a MCC.

\n","answer_id":677108,"answer_text":"Welcome to CV!\n\n\n\n\nSo you want to compare 2 proportions; e.g. “Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?”.\n\n\n\n\nWell, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (https://en.wikipedia.org/wiki/Contingency_table) (aka crosstab). And the “canonical” tests are either a chi-square (https://en.wikipedia.org/wiki/Chi-squared_test) test, or a Fisher-exact (https://en.wikipedia.org/wiki/Fisher%27s_exact_test) test (aka Fisher-0Irwin test).\n\nNow, using binomial CI’s will not really answer your 2 questions, unless the answer is obvious” if the 2 CI’s do not overlap, you have a significant difference. And if they overlap to a large extent, you do not have a significant difference. But in between, you can not simply eyeball the CI’s.\n\nNow, given that you are dealing with (very?) low proportions or counts (how many F’s in a given class? Maybe 2-3?), the chi-square test is not recommended (it is based on a normal approximation, which is not warranted for such low proportions/counts). Nor for that matter are CI’s based on normal approximations, a group the Wilson CI belongs to. And forget about continuity corrections, they do not work properly with very small proportions.\n\nSo you are left with the Fisher-exact test, or some newer versions of it (which are less “conservative, while remaining “exact”, that is based on exactly the binomial distribution), such as the Blaker test (https://cran.r-universe.dev/exact2x2/doc/exact2x2.pdf).\n\n\n\n\nBut there is a subtlety in what you are trying to compare. On one hand, you have the proportion of A’s in one class: easy. On the other hand you have the proportion of A’s in all other MA courses (the scenario is the same for the other question, so I will only address the first). How do you express that 2nd proportion?\n\nOne option is to simply take the count of all A grades in all other MA courses, and the count of all students enrolled in all other MA classes. And then you can/should indeed use a Fisher-exact (or a Blaker-exact) test. But this will weight each student equally, but not each class (the classes with a large enrollment are more heavily weighted than the classes with a low enrollment). That may be what you want (as it reflects the experience of all students enrolled in all other MA classes), but it may not.\nAn alternative would be to look at all the proportions in all other MA classes, and take the average of these proportions. This weights all classes equally (but not all students). In that case, your test can be done with a single CI. You compute an binomial CI (again using an exact method given your possibly low proportions/counts), and simply see if the average proportion in included in that CI. If it is not, you have established a significant difference (at what ever significance level you chose for the CI).\n\n\n\n\nLast, you ask about multiple comparisons. The fact that you compute multiple CI’s is not relevant; multiple comparisons only occur when you are making a comparison to a significance level (or checking if a CI contains 0, or 1).. And since you seem to only have 2 questions, then you are only making 2 comparisons.\n\nThe cautious thing to do would be to use a multiple comparison correction (MCC). Given only 2 comparisons, just use Bonferroni, and halve your significance level.\n\nBut bolder statisticians could argue that your 2 hypotheses are different, and independent. And therefore, a MCC is not warranted... (should a researcher correct for all the various hypotheses he/she will test in their career?). So depending on your ultimate goal (why only these 2 questions? what are you really trying to show), you may be able to dispense with a MCC.","answer_url":"https://stats.stackexchange.com/a/677108","author":"jginestet","author_url":"https://stats.stackexchange.com/users/380096/jginestet","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-09T02:03:39+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677095,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-09-09T02:03:39+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE/view-source"}],"score":1,"updated_at":"2026-09-09T02:03:39+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"jginestet","author_url":"https://stats.stackexchange.com/users/380096/jginestet","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-09-09T02:03:39+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE/view-source"}],"source_url":"https://stats.stackexchange.com/a/677108"}],"question_author":"LST","question_author_url":"https://stats.stackexchange.com/users/516373/lst"},"code_blocks":[{"block_index":0,"code_text":"modules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n","post_id":"stats:677095","sha256":"1d618fa130fbed5952b989d4c334bd6f29b52043ec44b220abbe1a7348e72701","source_url":"https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"6067403de8d4d10c98e25e84e769ee976b9bd9419586ec57b09e70ad30f14367","id":"SCT-784a774b6763d0de5331e029","language":null,"library_or_tool":null,"problem_text":"I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.\n\n\n\n\nI have individual student data, but some aggregated dummy data would be:\n\n\n\n\nmodules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\n\n\n\n\nAnd the questions I would like to ask are\n\n\n\n\n\nIs the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?\n\n\n\n\nIs the proportion of students who get an F grade in FR202 the same as the proportion of students who get an F grade in other xx200 level courses?\n\n\n\n\n\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science (https://moderndive.com/8-confidence-intervals.html) started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).\n\n\n\n\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, (https://www.allendowney.com/blog/2024/10/15/bootstrapping-a-proportion/) Bootstrap intervals for the single proportion – corp.ling.stats (https://corplingstats.wordpress.com/2024/12/12/bootstrap-intervals/)) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.\n\n\n\n\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.\n\n\n\n\n\nAre Wilson intervals the right approach for these sorts of questions?\n\n\n\n\nGiven that I sometimes have small numbers (<30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (Correcting for continuity – corp.ling.stats (https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/)), is that right?\n\n\n\n\nAny pointers on how to adjust for multiple comparisons, given that I’ll be calculating two CIs each (prop A and prop F) for multiple courses (e.g. each of 7 MA courses against the other 6 MA courses)?\n\n\n\n\n\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.\n\n\n\n\nThank you.","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":"LST","profile_url":"https://stats.stackexchange.com/users/516373/lst","user_type":"registered"},"created_at":"2026-09-07T16:47:08+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"77370A41-A452-40D5-9FE9-E2D1C2A53F6B","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/77370A41-A452-40D5-9FE9-E2D1C2A53F6B/view-source"}],"source_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:677095","source_record_sha256":"024eb7eff7d18dacf072cca8f59943c40702d3b85cc2956093304361402edce1","source_url":"https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.

\n

I have individual student data, but some aggregated dummy data would be:

\n
modules <- c(\n  "MA101","MA102","MA103","MA201","MA202","MA301","MA302",\n  "FR101","FR102","FR104","FR201","FR202","FR203","FR301",\n  "EN101","EN102","EN201","EN202","EN203","EN301","EN302"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n  sapply(totals, function(n) {\n    as.vector(rmultinom(1, n, rep(1, 5)))\n  })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n  Module = modules,\n  grade_counts,\n  Total = totals\n)\n
\n

And the questions I would like to ask are

\n
    \n
  • Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?
  • \n
  • Is the proportion of students who get an F grade in FR202 the same as the proportion of students who get an F grade in other xx200 level courses?
  • \n
\n

I did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).

\n

However, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, Bootstrap intervals for the single proportion – corp.ling.stats) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.

\n

Before I go down the wrong path again, I’d love a sense check from some more experienced hands.

\n
    \n
  • Are Wilson intervals the right approach for these sorts of questions?
  • \n
  • Given that I sometimes have small numbers (<30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (Correcting for continuity – corp.ling.stats), is that right?
  • \n
  • Any pointers on how to adjust for multiple comparisons, given that I’ll be calculating two CIs each (prop A and prop F) for multiple courses (e.g. each of 7 MA courses against the other 6 MA courses)?
  • \n
\n

I have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.

\n

Thank you.

\n","question_title":"Testing differences in proportions - Wilson CIs, continuity corrections and multiple comparisons","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult","split":"test"} {"accepted_answer":{"answer_html":"

You are using R version 4.6.1. Well, since R 4.6.0, from R News:

\n
\n

wilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.

\n
\n

Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:

\n
\n

If there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.

\n
\n

[...]

\n
\n

Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.

\n

Streitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.

\n
\n","answer_id":677139,"answer_text":"You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).","answer_url":"https://stats.stackexchange.com/a/677139","author":"J-J-J","author_url":"https://stats.stackexchange.com/users/164936/j-j-j","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T07:32:22+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T07:32:22+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"23216BD3-49D3-422F-8020-02B7D9CD2B5A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T08:09:51+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CB4779A0-4EA1-4BB0-99F8-7FFB266F646D","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}],"score":16,"updated_at":"2026-09-11T08:09:51+00:00"},"answer_scores":[{"answer_id":677136,"score":5},{"answer_id":677139,"score":16},{"answer_id":677141,"score":7}],"answers":[{"answer_html":"

Can you provide a {reprex}? I'm getting a warning when I run your code

\n
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n                                  26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n                                                                 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n                                                                                                                          "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#>  Wilcoxon signed rank test with continuity correction\n#> \n#> data:  df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#>  4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#>       7.000049\n
\n

Created on 2026-09-10 with reprex v2.1.1

\n

EDIT: I was using an old version of R. Here is the reprex from using 4.6

\n
(R.version.string)\n#> [1] "R version 4.6.0 (2026-04-24)"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n                                  26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n                                                                 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n                                                                                                                          "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#>  Wilcoxon signed rank exact test\n#> \n#> data:  df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#>  4 9\n#> sample estimates:\n#> (pseudo)median \n#>            6.5\n
\n

Created on 2026-09-11 with reprex v2.1.1

\n

Note, no warning. See J-J-J's comment for an explanation.

\n","answer_id":677136,"answer_text":"Can you provide a {reprex} (https://reprex.tidyverse.org/)? I'm getting a warning when I run your code\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\n\n\n\n\nCreated on 2026-09-10 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nEDIT: I was using an old version of R. Here is the reprex from using 4.6\n\n\n\n\n(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\n\n\n\n\nCreated on 2026-09-11 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nNote, no warning. See J-J-J's comment for an explanation.","answer_url":"https://stats.stackexchange.com/a/677136","author":"Demetri Pananos","author_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T01:34:59+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Demetri Pananos","profile_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","user_type":"registered"},"created_at":"2026-09-11T01:34:59+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"3461E410-C604-4E94-BBD3-042259374DDF","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Demetri Pananos","profile_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","user_type":"registered"},"created_at":"2026-09-11T17:41:38+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"C692081B-A074-4F0B-985E-9AECEBE88DE5","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}],"score":5,"updated_at":"2026-09-11T17:41:38+00:00"},{"answer_html":"

You are using R version 4.6.1. Well, since R 4.6.0, from R News:

\n
\n

wilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.

\n
\n

Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:

\n
\n

If there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.

\n
\n

[...]

\n
\n

Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.

\n

Streitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.

\n
\n","answer_id":677139,"answer_text":"You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).","answer_url":"https://stats.stackexchange.com/a/677139","author":"J-J-J","author_url":"https://stats.stackexchange.com/users/164936/j-j-j","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T07:32:22+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T07:32:22+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"23216BD3-49D3-422F-8020-02B7D9CD2B5A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T08:09:51+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CB4779A0-4EA1-4BB0-99F8-7FFB266F646D","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}],"score":16,"updated_at":"2026-09-11T08:09:51+00:00"},{"answer_html":"

This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.

\n

Here is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.

\n

\"enter

\n

Here we range from evident to speculative:

\n
    \n
  1. Integer scores, so ties are more likely than otherwise.

    \n
  2. \n
  3. Is there an upper limit of 32?

    \n
  4. \n
  5. The observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.

    \n
  6. \n
\n

A Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?

\n","answer_id":677141,"answer_text":"This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.\n\n\n\n\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/7o9W87he.png] (https://i.sstatic.net/7o9W87he.png)\n\n\n\n\nHere we range from evident to speculative:\n\n\n\n\n\n\n\nInteger scores, so ties are more likely than otherwise.\n\n\n\n\n\n\n\n\n\nIs there an upper limit of 32?\n\n\n\n\n\n\n\n\n\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.\n\n\n\n\n\n\n\n\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?","answer_url":"https://stats.stackexchange.com/a/677141","author":"Nick Cox","author_url":"https://stats.stackexchange.com/users/22047/nick-cox","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T08:47:46+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-11T08:47:46+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"F5E781A6-F63A-4F3B-897E-03303213674F","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-11T09:20:25+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"2F24FDA3-AB03-426F-84C2-A097A0D37730","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}],"score":7,"updated_at":"2026-09-11T09:20:25+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Demetri Pananos","author_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Demetri Pananos","profile_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","user_type":"registered"},"created_at":"2026-09-11T01:34:59+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"3461E410-C604-4E94-BBD3-042259374DDF","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Demetri Pananos","profile_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","user_type":"registered"},"created_at":"2026-09-11T17:41:38+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"C692081B-A074-4F0B-985E-9AECEBE88DE5","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}],"source_url":"https://stats.stackexchange.com/a/677136"},{"author":"J-J-J","author_url":"https://stats.stackexchange.com/users/164936/j-j-j","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T07:32:22+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"23216BD3-49D3-422F-8020-02B7D9CD2B5A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T08:09:51+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CB4779A0-4EA1-4BB0-99F8-7FFB266F646D","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}],"source_url":"https://stats.stackexchange.com/a/677139"},{"author":"Nick Cox","author_url":"https://stats.stackexchange.com/users/22047/nick-cox","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-11T08:47:46+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"F5E781A6-F63A-4F3B-897E-03303213674F","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-11T09:20:25+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"2F24FDA3-AB03-426F-84C2-A097A0D37730","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}],"source_url":"https://stats.stackexchange.com/a/677141"}],"question_author":"DAVID PAUL CAPELLE","question_author_url":"https://stats.stackexchange.com/users/386267/david-paul-capelle"},"code_blocks":[{"block_index":0,"code_text":"df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n","post_id":"stats:677135","sha256":"d5c814c461b4b9343809a17c4edd3fbbe1bc940093edcb02ae766c0fbd63e802","source_url":"https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test"},{"block_index":1,"code_text":"\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```\n","post_id":"stats:677135","sha256":"62c4ef27f6977021d1af60c7700550f89ea035d044d29b3bff4641ab21fc10e6","source_url":"https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test"},{"block_index":0,"code_text":"df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n","post_id":677136,"sha256":"496b05ec45239bb68abbf4de00ba9a79c421d6cd74f3703e914e45742d127983","source_url":"https://stats.stackexchange.com/a/677136"},{"block_index":1,"code_text":"(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n","post_id":677136,"sha256":"3b004d026d68a8f11c9c562e695ca7fb83bb343024bf0b626d348d5f77c4bb42","source_url":"https://stats.stackexchange.com/a/677136"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"0104f45dbab9737f6409c77a6bc4a2e894b83ab23bd704361e79e00564d4ba71","id":"SCT-218133b3667b4e5daf2ee898","language":null,"library_or_tool":null,"problem_text":"I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n\n\n\n\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?\n\n\n\n\nHere is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.\n\n\n\n\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```","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":"DAVID PAUL CAPELLE","profile_url":"https://stats.stackexchange.com/users/386267/david-paul-capelle","user_type":"registered"},"created_at":"2026-09-11T01:14:02+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"93652C25-9FE3-4C77-B0E9-CF7DD58DC50A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/93652C25-9FE3-4C77-B0E9-CF7DD58DC50A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DAVID PAUL CAPELLE","profile_url":"https://stats.stackexchange.com/users/386267/david-paul-capelle","user_type":"registered"},"created_at":"2026-09-11T06:13:00+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"C7E16D39-DC10-460F-B943-B7547B90F63D","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/C7E16D39-DC10-460F-B943-B7547B90F63D/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-09-11T09:18:50+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"BC7129B7-4E28-49C0-8308-97D09DE31CA9","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/BC7129B7-4E28-49C0-8308-97D09DE31CA9/view-source"},{"content_license":null,"contributor":{"display_name":"M--","profile_url":"https://stats.stackexchange.com/users/154449/m","user_type":"registered"},"created_at":"2026-09-13T11:06:51+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"052E2710-AD21-4AFE-992F-D9FB54C17A14","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/052E2710-AD21-4AFE-992F-D9FB54C17A14/view-source"}],"source_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:677135","source_record_sha256":"ad82852ae225a17bd8d0058ffc0dcecec010104eb1814ee32fd3108da6ee62ee","source_url":"https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:

\n
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n"tbl", "data.frame"))\n
\n

As there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?

\n

Here is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.

\n
\nprepost <- structure(\n  list(\n    PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n    PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n  ),\n  row.names = c(NA, -13L),\n  class = c("tbl_df", "tbl", "data.frame")\n)\n\nwilcox.test(\n  prepost$PostScore,\n  prepost$PreScore,\n  conf.int = TRUE,\n  paired = TRUE,\n  exact = TRUE\n)\n#> \n#>  Wilcoxon signed rank exact test\n#> \n#> data:  prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#>  4 9\n#> sample estimates:\n#> (pseudo)median \n#>            6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS:   /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0  LAPACK version 3.12.0\n#> \n#> locale:\n#>  [1] LC_CTYPE=en_SG.UTF-8       LC_NUMERIC=C              \n#>  [3] LC_TIME=en_SG.UTF-8        LC_COLLATE=en_SG.UTF-8    \n#>  [5] LC_MONETARY=en_SG.UTF-8    LC_MESSAGES=en_SG.UTF-8   \n#>  [7] LC_PAPER=en_SG.UTF-8       LC_NAME=C                 \n#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C       \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats     graphics  grDevices utils     datasets  methods   base     \n#> \n#> loaded via a namespace (and not attached):\n#>  [1] digest_0.6.39     fastmap_1.2.0     xfun_0.60         glue_1.8.1       \n#>  [5] knitr_1.51        htmltools_0.5.9   rmarkdown_2.32    lifecycle_1.0.5  \n#>  [9] cli_3.6.6         reprex_2.1.1      withr_3.0.2       compiler_4.6.1   \n#> [13] rstudioapi_0.19.0 tools_4.6.1       evaluate_1.0.5    yaml_2.3.12      \n#> [17] otel_0.2.0        rlang_1.2.0       fs_2.1.0\n```\n
\n","question_title":"Why does R not warn about ties in wilcox.test()","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":677163,"score":2},{"answer_id":677165,"score":2}],"answers":[{"answer_html":"

Except for the comparison between mod_disp_constant and mod_disp_background, the p-values you show are based on Wald tests, which hold asymptotically in the limit of large numbers of cases. If you have only "a few observers," I'd first worry about that. Likelihood-ratio tests would be more reliable.

\n

That said, most of those p-values are so small (or so large) that some minor inflation of Type I error wouldn't seem likely to change any "statistical significance" conclusions. If you want to provide more evidence for "significant" results, you could consider some type of resampling test.

\n

I couldn't find that the post about elevated Type I errors specified the glmmTMB version used. I also haven't taken the time to see exactly which types of p-values were collected. I did note that the post seems to indicate elevated Type I error even with homoskedastic data and no dispformula.

\n

In terms of changes with software versions, that post provides code with specified random seeds. You thus could repeat the code with the latest glmmTMB version and see whether the results differ (first with the same seeds, then maybe with different seeds).

\n","answer_id":677163,"answer_text":"Except for the comparison between mod_disp_constant and mod_disp_background, the p-values you show are based on Wald tests, which hold asymptotically in the limit of large numbers of cases. If you have only \"a few observers,\" I'd first worry about that. Likelihood-ratio tests would be more reliable.\n\n\n\n\nThat said, most of those p-values are so small (or so large) that some minor inflation of Type I error wouldn't seem likely to change any \"statistical significance\" conclusions. If you want to provide more evidence for \"significant\" results, you could consider some type of resampling test (https://stats.stackexchange.com/a/104746/28500).\n\n\n\n\nI couldn't find that the post about elevated Type I errors (https://lgraz.com/posts/lmm-heteroskedastic/) specified the glmmTMB version used. I also haven't taken the time to see exactly which types of p-values were collected. I did note that the post seems to indicate elevated Type I error even with homoskedastic data and no dispformula (https://lgraz.com/posts/lmm-heteroskedastic/#glmmtmby-trt-1id-1).\n\n\n\n\nIn terms of changes with software versions, that post (https://lgraz.com/posts/lmm-heteroskedastic/) provides code with specified random seeds. You thus could repeat the code with the latest glmmTMB version and see whether the results differ (first with the same seeds, then maybe with different seeds).","answer_url":"https://stats.stackexchange.com/a/677163","author":"EdM","author_url":"https://stats.stackexchange.com/users/28500/edm","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-13T17:48:51+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":677147,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-09-13T17:48:51+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"3B7C67F5-C6E0-49EA-9E1D-9A76F8372905","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3B7C67F5-C6E0-49EA-9E1D-9A76F8372905/view-source"}],"score":2,"updated_at":"2026-09-13T17:48:51+00:00"},{"answer_html":"

The inflated type-1 errors in that example are due to the $p$-values being calculated based on asymptotic ($Z$-score) Wald statistics, rather than using some form of finite-size 'denominator degrees of freedom' correction (between-within/Sattherwaite/Kenward-Roger) to get $p$-values based on Student-$t$ distributions. I redid the analysis with ddf corrections (code here, here), with the following results (the binom.test p column tests whether the type-I error is significantly different from $\\alpha=0.05$, for 5000 simulations).

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
methodtestType‑I errorbinom.test p
glmmTMB_wald (asymptotic Wald χ², uncorrected — original post's test)anova0.0909e-32
glmmTMB_none (asymptotic LRT, uncorrected)anova0.0683e-8
glmmTMB_satterthwaiteanova0.0520.48
glmmTMB_kenward-rogeranova0.0530.40
lme_varIdentanova0.0520.44
lmerTest (no heteroscedasticity accommodation, baseline)anova0.0550.10
\n

So things look fine as long as you ddf-correct (specify summary(..., ddf = "satterthwaite")); the theory is a little shaky — it was developed for Gaussian models — but it should probably be OK. At the very least, you can compare asymptotic $p$-values (the default) with these results to see whether this is something you should be concerned about.

\n

For what it's worth I'm not sure there's much theory about the sampling distribution of GLM-type models with estimated scale parameters (e.g. Beta) ...

\n

@EdM is also right that with such large $t$-statistics, you probably don't need to worry — if for instance you were mainly concerned with whether $p<0.05$ or not, you would be fine as long as the denominator df was above 3: the two-tailed test for $t=-3.172, \\textrm{df}=3$ is 2*pt(-3.712, df = 3) $\\approx$ 0.03 ...

\n","answer_id":677165,"answer_text":"The inflated type-1 errors in that example are due to the $p$-values being calculated based on asymptotic ($Z$-score) Wald statistics, rather than using some form of finite-size 'denominator degrees of freedom' correction (between-within/Sattherwaite/Kenward-Roger) to get $p$-values based on Student-$t$ distributions. I redid the analysis with ddf corrections (code here (https://github.com/glmmTMB/glmmTMB/blob/master/misc/hetero_ddf_sim.R), here (https://github.com/glmmTMB/glmmTMB/blob/master/misc/hetero_ddf_sim_analysis.R)), with the following results (the binom.test p column tests whether the type-I error is significantly different from $\\alpha=0.05$, for 5000 simulations).\n\n\n\n\n\n\n\n\n\nmethod\ntest\nType‑I error\nbinom.test p\n\n\n\n\n\n\n\n\n\tglmmTMB_wald (asymptotic Wald χ², uncorrected — original post's test)\n\tanova\n\t0.090\n\t9e-32\n\n\n\n\n\n\n\tglmmTMB_none (asymptotic LRT, uncorrected)\n\tanova\n\t0.068\n\t3e-8\n\n\n\n\n\n\n\tglmmTMB_satterthwaite\n\tanova\n\t0.052\n\t0.48\n\n\n\n\n\n\n\tglmmTMB_kenward-roger\n\tanova\n\t0.053\n\t0.40\n\n\n\n\n\n\n\tlme_varIdent\n\tanova\n\t0.052\n\t0.44\n\n\n\n\n\n\n\tlmerTest (no heteroscedasticity accommodation, baseline)\n\tanova\n\t0.055\n\t0.10\n\n\n\n\n\n\n\n\n\nSo things look fine as long as you ddf-correct (specify summary(..., ddf = \"satterthwaite\")); the theory is a little shaky — it was developed for Gaussian models — but it should probably be OK. At the very least, you can compare asymptotic $p$-values (the default) with these results to see whether this is something you should be concerned about.\n\n\n\n\nFor what it's worth I'm not sure there's much theory about the sampling distribution of GLM-type models with estimated scale parameters (e.g. Beta) ...\n\n\n\n\n@EdM is also right that with such large $t$-statistics, you probably don't need to worry — if for instance you were mainly concerned with whether $p<0.05$ or not, you would be fine as long as the denominator df was above 3: the two-tailed test for $t=-3.172, \\textrm{df}=3$ is 2*pt(-3.712, df = 3) $\\approx$ 0.03 ...","answer_url":"https://stats.stackexchange.com/a/677165","author":"Ben Bolker","author_url":"https://stats.stackexchange.com/users/2126/ben-bolker","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-13T20:48: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":677147,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ben Bolker","profile_url":"https://stats.stackexchange.com/users/2126/ben-bolker","user_type":"registered"},"created_at":"2026-09-13T20:48:08+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"EF34FC87-9BFC-4047-982E-58C916319B81","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/EF34FC87-9BFC-4047-982E-58C916319B81/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ben Bolker","profile_url":"https://stats.stackexchange.com/users/2126/ben-bolker","user_type":"registered"},"created_at":"2026-09-14T13:13:51+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"825AC844-EA44-413D-A096-4C2D9BFC6EB4","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/825AC844-EA44-413D-A096-4C2D9BFC6EB4/view-source"}],"score":2,"updated_at":"2026-09-14T13:13:51+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"EdM","author_url":"https://stats.stackexchange.com/users/28500/edm","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-09-13T17:48:51+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"3B7C67F5-C6E0-49EA-9E1D-9A76F8372905","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3B7C67F5-C6E0-49EA-9E1D-9A76F8372905/view-source"}],"source_url":"https://stats.stackexchange.com/a/677163"},{"author":"Ben Bolker","author_url":"https://stats.stackexchange.com/users/2126/ben-bolker","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ben Bolker","profile_url":"https://stats.stackexchange.com/users/2126/ben-bolker","user_type":"registered"},"created_at":"2026-09-13T20:48:08+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"EF34FC87-9BFC-4047-982E-58C916319B81","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/EF34FC87-9BFC-4047-982E-58C916319B81/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ben Bolker","profile_url":"https://stats.stackexchange.com/users/2126/ben-bolker","user_type":"registered"},"created_at":"2026-09-14T13:13:51+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"825AC844-EA44-413D-A096-4C2D9BFC6EB4","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/825AC844-EA44-413D-A096-4C2D9BFC6EB4/view-source"}],"source_url":"https://stats.stackexchange.com/a/677165"}],"question_author":"Dodo","question_author_url":"https://stats.stackexchange.com/users/516003/dodo"},"code_blocks":[{"block_index":0,"code_text":"mod_disp_constant: hs ~ thr + bd + (1 | obs), zi=~0, disp=~1\nmod_disp_background: hs ~ thr + bd + (1 | obs), zi=~0, disp=~bd\n Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) \nmod_disp_constant 6 -421.04 -402.63 216.52 -433.04 \nmod_disp_background 8 -437.64 -413.09 226.82 -453.64 20.593 2 3.374e-05 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n df AICc\nmod_disp_constant 6 -420.4919\nmod_disp_background 8 -436.6780\n----------------------------------------------------------------------\n Family: beta ( logit )\nFormula: hs ~ thr + bd + (1 | obs)\nDispersion: ~bd\nData: data_long\n\n\nRandom effects:\n\nConditional model:\n Groups Name Variance Std.Dev.\n obs (Intercept) 0.04374 0.2091 \nNumber of obs: 159, groups: obs, 53\n\nConditional model:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 1.30199 0.05762 22.598 < 2e-16 ***\nthd -0.06437 0.00294 -21.899 < 2e-16 ***\nbdG -0.32972 0.05668 -5.817 6e-09 ***\nbdS -0.15651 0.04216 -3.712 0.000206 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nDispersion model:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 4.0702 0.2139 19.031 < 2e-16 ***\nbdG -0.1452 0.3023 -0.480 0.63113 \nbdS 1.9828 0.7153 2.772 0.00557 ** \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n","post_id":"stats:677147","sha256":"50084e67121284f03204988181e7eeca70ecf379b045ede4b50442bde0554d99","source_url":"https://stats.stackexchange.com/questions/677147/glmmtmb-with-beta-distribution-for-repeated-measures-with-varying-dispersion-a"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"aacf292e175a320ca92325922c73fb91d823bb8253b9ee26523b0d8db5360fe9","id":"SCT-6db02b30844b68ff4b69f28a","language":["R"],"library_or_tool":null,"problem_text":"I need a mixed effects beta regression. I have used glmmTMB with beta distribution, logit link, to assess the relation between hit scores and threshold of a few observers repeated across three backgrounds (a fourth background was used, but it presented the stimuli differently, so I am running a betareg on it instead). Hit scores are proportions in the open interval (0,1), without 0 or 1.\nI read in a previous question that dispformula from glmmTMB inflates Type I error, making the p-values not valid. Does this still hold for the current glmmTMB package version?\n\n\n\n\nQuestion: Varying dispersion parameter (=dispformula) in glmmTMB in R to account for heteroscedasticity that originates from one predictor (https://stats.stackexchange.com/questions/518013/varying-dispersion-parameter-dispformula-in-glmmtmb-in-r-to-account-for-heter)\n\n\n\n\nBlog Post: https://lgraz.com/posts/lmm-heteroskedastic/ (https://lgraz.com/posts/lmm-heteroskedastic/)\n\n\n\n\nCurrent Model output:\n\n\n\n\nmod_disp_constant: hs ~ thr + bd + (1 | obs), zi=~0, disp=~1\nmod_disp_background: hs ~ thr + bd + (1 | obs), zi=~0, disp=~bd\n Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) \nmod_disp_constant 6 -421.04 -402.63 216.52 -433.04 \nmod_disp_background 8 -437.64 -413.09 226.82 -453.64 20.593 2 3.374e-05 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n df AICc\nmod_disp_constant 6 -420.4919\nmod_disp_background 8 -436.6780\n----------------------------------------------------------------------\n Family: beta ( logit )\nFormula: hs ~ thr + bd + (1 | obs)\nDispersion: ~bd\nData: data_long\n\n\nRandom effects:\n\nConditional model:\n Groups Name Variance Std.Dev.\n obs (Intercept) 0.04374 0.2091 \nNumber of obs: 159, groups: obs, 53\n\nConditional model:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 1.30199 0.05762 22.598 < 2e-16 ***\nthd -0.06437 0.00294 -21.899 < 2e-16 ***\nbdG -0.32972 0.05668 -5.817 6e-09 ***\nbdS -0.15651 0.04216 -3.712 0.000206 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nDispersion model:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 4.0702 0.2139 19.031 < 2e-16 ***\nbdG -0.1452 0.3023 -0.480 0.63113 \nbdS 1.9828 0.7153 2.772 0.00557 ** \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1","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":"Dodo","profile_url":"https://stats.stackexchange.com/users/516003/dodo","user_type":"registered"},"created_at":"2026-09-12T01:15:13+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"6B585FAD-32F7-4AB7-8609-8A14FD5C6F8A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/6B585FAD-32F7-4AB7-8609-8A14FD5C6F8A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lukas Lohse","profile_url":"https://stats.stackexchange.com/users/341520/lukas-lohse","user_type":"registered"},"created_at":"2026-09-12T16:14:36+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"C41A8C0D-BD77-4EB7-849E-FEBEFC1EFBE3","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/C41A8C0D-BD77-4EB7-849E-FEBEFC1EFBE3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dodo","profile_url":"https://stats.stackexchange.com/users/516003/dodo","user_type":"registered"},"created_at":"2026-09-12T17:07:05+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"DE7C429C-8ACF-4C04-86D2-C436353A28D0","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/DE7C429C-8ACF-4C04-86D2-C436353A28D0/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-09-14T01:21:02+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"CC727907-664B-41EC-A824-0AEB29F60F2C","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/CC727907-664B-41EC-A824-0AEB29F60F2C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dodo","profile_url":"https://stats.stackexchange.com/users/516003/dodo","user_type":"registered"},"created_at":"2026-09-18T15:29:25+00:00","raw_file":"raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json","raw_sha256":"2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119","revision_guid":"8B78E92E-9DD1-49AD-B92C-A0DE26764BD4","revision_number":4,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/8B78E92E-9DD1-49AD-B92C-A0DE26764BD4/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:677147","source_record_sha256":"3cc717fd51f6009e38a24d657c65f4af16d84df474a2d6fd89dc1823661f8d50","source_url":"https://stats.stackexchange.com/questions/677147/glmmtmb-with-beta-distribution-for-repeated-measures-with-varying-dispersion-a","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I need a mixed effects beta regression. I have used glmmTMB with beta distribution, logit link, to assess the relation between hit scores and threshold of a few observers repeated across three backgrounds (a fourth background was used, but it presented the stimuli differently, so I am running a betareg on it instead). Hit scores are proportions in the open interval (0,1), without 0 or 1.\nI read in a previous question that dispformula from glmmTMB inflates Type I error, making the p-values not valid. Does this still hold for the current glmmTMB package version?

\n

Question: Varying dispersion parameter (=dispformula) in glmmTMB in R to account for heteroscedasticity that originates from one predictor

\n

Blog Post: https://lgraz.com/posts/lmm-heteroskedastic/

\n

Current Model output:

\n
mod_disp_constant: hs ~ thr + bd + (1 | obs), zi=~0, disp=~1\nmod_disp_background: hs ~ thr + bd + (1 | obs), zi=~0, disp=~bd\n                    Df     AIC     BIC logLik deviance  Chisq Chi Df Pr(>Chisq)    \nmod_disp_constant    6 -421.04 -402.63 216.52  -433.04                             \nmod_disp_background  8 -437.64 -413.09 226.82  -453.64 20.593      2  3.374e-05 ***\n---\nSignif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n                    df      AICc\nmod_disp_constant    6 -420.4919\nmod_disp_background  8 -436.6780\n----------------------------------------------------------------------\n Family: beta  ( logit )\nFormula:          hs ~ thr + bd + (1 | obs)\nDispersion:                ~bd\nData: data_long\n\n\nRandom effects:\n\nConditional model:\n Groups Name        Variance Std.Dev.\n obs    (Intercept) 0.04374  0.2091  \nNumber of obs: 159, groups:  obs, 53\n\nConditional model:\n                    Estimate Std. Error z value Pr(>|z|)    \n(Intercept)          1.30199    0.05762  22.598  < 2e-16 ***\nthd                 -0.06437    0.00294 -21.899  < 2e-16 ***\nbdG                 -0.32972    0.05668  -5.817    6e-09 ***\nbdS                 -0.15651    0.04216  -3.712 0.000206 ***\n---\nSignif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nDispersion model:\n                    Estimate Std. Error z value Pr(>|z|)    \n(Intercept)           4.0702     0.2139  19.031  < 2e-16 ***\nbdG                   -0.1452     0.3023  -0.480  0.63113    \nbdS                   1.9828     0.7153   2.772  0.00557 ** \n---\nSignif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n
\n","question_title":"glmmTMB with beta distribution for repeated measures with varying dispersion - Are p-values from dispersion model unreliable?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677147/glmmtmb-with-beta-distribution-for-repeated-measures-with-varying-dispersion-a","split":"train"} {"accepted_answer":{"answer_html":"

I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$

\n

Since $\\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

For given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.

\n

So 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

Here is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$

\n
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
\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":"

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

If I had a sample $\\{y_{ij}\\}$ I would estimate it like this:

\n
    \n
  1. Have 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)$
  2. \n
  3. $\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$
  4. \n
\n

Optimise jointly $u,v$ (maximum likelihood).

\n

So 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

If you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable

\n","answer_id":677267,"answer_text":"I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.\n\n\n\n\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:\n\n\n\n\n\nHave variables $u$, $v$, and take $\\frac{\\alpha}{\\alpha+\\beta}=expit\\left(u\\right)=\\frac{1}{1+\\exp\\left(-u\\right)}$, $\\alpha=softplus(v)=\\log\\left(1+\\exp(v)\\right)$\n\n\n\n\n$\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$\n\n\n\n\n\nOptimise jointly $u,v$ (maximum likelihood).\n\n\n\n\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).\n\n\n\n\n\n\n\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable","answer_url":"https://stats.stackexchange.com/a/677267","author":"Cryo","author_url":"https://stats.stackexchange.com/users/275239/cryo","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-26T12:24:08+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:08.569053+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json","raw_sha256":"a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=2&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677266,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Cryo","profile_url":"https://stats.stackexchange.com/users/275239/cryo","user_type":"registered"},"created_at":"2026-09-26T12:24:08+00:00","raw_file":"raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json","raw_sha256":"4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e","revision_guid":"D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Cryo","profile_url":"https://stats.stackexchange.com/users/275239/cryo","user_type":"registered"},"created_at":"2026-09-26T12:33:54+00:00","raw_file":"raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json","raw_sha256":"4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e","revision_guid":"24348886-EE3F-4779-9F2E-6DF7895E9D85","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/24348886-EE3F-4779-9F2E-6DF7895E9D85/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"User1865345","profile_url":"https://stats.stackexchange.com/users/362671/user1865345","user_type":"registered"},"created_at":"2026-09-26T13:34:16+00:00","raw_file":"raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json","raw_sha256":"4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e","revision_guid":"57B9D992-5586-4BC1-9973-DD3482A5AA98","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/57B9D992-5586-4BC1-9973-DD3482A5AA98/view-source"}],"score":5,"updated_at":"2026-09-26T13:34:16+00:00"},{"answer_html":"

I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$

\n

Since $\\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

For given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.

\n

So 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

Here is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$

\n
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
\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":"

Here is a hierarchical data generating process (DGP):

\n
\n

(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$

\n

(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$

\n
\n

$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$

\n

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 $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

After 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

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):

\n
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
\n

When 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

\n

The 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

I am looking for feedback on my methodology. Should I have done this a different way?

\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":45174,"score":5}],"answers":[{"answer_html":"

Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.
\nHence one might get steps where the objective is not minimized.

\n

There are monotonic versions of some of the methods.
\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (Code) and Monotonicity and Restart in Fast Gradient Methods.

\n","answer_id":45174,"answer_text":"Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.\n\nHence one might get steps where the objective is not minimized.\n\n\n\n\nThere are monotonic versions of some of the methods.\n\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (https://ieeexplore.ieee.org/document/8542689) (Code (https://cai2r.net/resources/mfista-va-monotone-fista-with-variable-acceleration-for-compressed-sensing-mri/)) and Monotonicity and Restart in Fast Gradient Methods (https://ieeexplore.ieee.org/document/7040179).","answer_url":"https://scicomp.stackexchange.com/a/45174","author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-07-18T21:15:51+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":45100,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-07-18T21:15:51+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"F055CC80-CD8E-4E95-819B-09F748F619C0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F055CC80-CD8E-4E95-819B-09F748F619C0/view-source"}],"score":5,"updated_at":"2025-07-18T21:15:51+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-07-18T21:15:51+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"F055CC80-CD8E-4E95-819B-09F748F619C0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F055CC80-CD8E-4E95-819B-09F748F619C0/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45174"}],"question_author":"Sid Meka","question_author_url":"https://scicomp.stackexchange.com/users/51369/sid-meka"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n","post_id":"scicomp:45100","sha256":"c2c40b470711cdaff8fdd07d388ca7dbff1238a76bfd60220b44fdb4267ddeeb","source_url":"https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"a838ff81220dac73b873c13c7ae53e4a20046fce148c7af45566ce7891132f64","id":"SCT-bbc9d5db164ec5f7c4add66f","language":["python"],"library_or_tool":["numpy","scipy"],"problem_text":"I have this Exercise in my Numerical Optimization class and here it is:\n\n\n\n\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:\n\n\n\n\n\nthe underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$\n\n\n\n\nthe measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$\n\n\n\n\nthe observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$\n\n\n\n\n\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:\n\n\n\n\n\nGradient descent\n\n\n\n\nAccelerated gradient descent\n\n\n\n\n\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.\n\n\n\n\nThis is my code in Python:\n\n\n\n\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm (https://ibb.co/KjKshhKm) , https://ibb.co/2DN3bnV (https://ibb.co/2DN3bnV) , and https://ibb.co/Zpn0JY7z (https://ibb.co/Zpn0JY7z) .\n\n\n\n\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.","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":"Sid Meka","profile_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","user_type":"registered"},"created_at":"2025-06-07T03:14:18+00:00","raw_file":"raw/codex_api_v1/18019c65cead443968e23d401a2956091deb8b40ada648e04bed5e2f03ce54b5_1790825348716030900_0.json","raw_sha256":"05729e3e9dd3f73dae19eda7639475c736dfb4d5818353d669924bc12ddae880","revision_guid":"211F9448-16A8-4E36-8763-3B16D1CD1986","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/211F9448-16A8-4E36-8763-3B16D1CD1986/view-source"}],"source_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":"45100","source_record_sha256":"d4fe84fbbd309c9a7cac9d6596d6b8e2962d6900a058dc6a0b69b66623194c11","source_url":"https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have this Exercise in my Numerical Optimization class and here it is:

\n

In this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:

\n
    \n
  • the underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$
  • \n
  • the measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$
  • \n
  • the observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$
  • \n
\n

Note that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:

\n
    \n
  1. Gradient descent
  2. \n
  3. Accelerated gradient descent
  4. \n
\n

For each algorithm, plot the function value over the first $50$ iterations on a semilog plot.

\n

This is my code in Python:

\n
import numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n    return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n    n = A.shape[1]\n    x = np.zeros(n)\n    f_values = []\n    alpha = 1 / beta  #Step size\n\n    for k in range(num_iters):\n        grad = A.T @ (A @ x - y) + lmbda * x\n        x = x - alpha * grad\n        f_values.append(ridge_objective(x, A, y, lmbda))\n    return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n    n = A.shape[1]\n    x = np.zeros(n)\n    z = np.zeros(n)\n    f_values = []\n    alpha = 1 / beta  #Step size\n    gamma = 0\n    for k in range(num_iters):\n        prev_x = x.copy()\n        grad = A.T @ (A @ z - y) + lmbda * z\n        x = z - alpha * grad\n        if k == 0:\n            gamma = 0\n        else:\n            gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n        z = x + gamma * (x - prev_x)\n        f_values.append(ridge_objective(x, A, y, lmbda))\n    return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n    n = 100\n    m = 80\n    lmbda = 1\n    x_opt = np.random.randn(n)\n    A = np.random.randn(m, n)\n    myVariance = 0.25\n    mySTD = math.sqrt(myVariance)\n    epsilon = np.random.normal(0, mySTD, m)\n    y = A @ x_opt + epsilon\n    beta = 4*(m+n) + lmbda\n    \n    gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n    agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n    plt.figure(figsize=(8, 5))\n    plt.semilogy(gd_values, label = "Gradient Descent")\n    plt.semilogy(agd_values, label = "Accelerated Gradient Descent")\n    plt.xlabel("Iteration")\n    plt.ylabel("Objective Value with Logarithmic Scale")\n    plt.title("Ridge Regression: Objective Value vs Iteration "+str(i+1))\n    plt.legend()\n    plt.grid(True)\n    plt.show()\n\n
\n

Additionally, here are the plots I have: https://ibb.co/KjKshhKm , https://ibb.co/2DN3bnV , and https://ibb.co/Zpn0JY7z .

\n

I would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.

\n","question_title":"Gradient Descent vs Accelerated Gradient Descent","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45106,"score":2}],"answers":[{"answer_html":"

The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).

\n","answer_id":45106,"answer_text":"The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).","answer_url":"https://scicomp.stackexchange.com/a/45106","author":"Sid Meka","author_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-06-09T04:54:27+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":45105,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Sid Meka","profile_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","user_type":"registered"},"created_at":"2025-06-09T04:54:27+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"4BE2F813-B6A1-42CA-AF94-8C73E7F87D02","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4BE2F813-B6A1-42CA-AF94-8C73E7F87D02/view-source"}],"score":2,"updated_at":"2025-06-09T04:54:27+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Sid Meka","author_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Sid Meka","profile_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","user_type":"registered"},"created_at":"2025-06-09T04:54:27+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"4BE2F813-B6A1-42CA-AF94-8C73E7F87D02","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4BE2F813-B6A1-42CA-AF94-8C73E7F87D02/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45106"}],"question_author":"Sid Meka","question_author_url":"https://scicomp.stackexchange.com/users/51369/sid-meka"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n","post_id":"scicomp:45105","sha256":"b1990766f774a1d5b850c3adb758d23b68bc5ef84affbe8978c36bc7ea02fb03","source_url":"https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"f46358692375a1bc1521ff214400c2f1681299587aeec4691a525e2f56b7a9bb","id":"SCT-231c5d77bc675dfac0f80857","language":null,"library_or_tool":["numpy"],"problem_text":"Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.\n\n\n\n\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:\n\n\n\n\n\n$\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$\n\n\n\n\n$X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$\n\n\n\n\n$z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$\n\n\n\n\n$y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$\n\n\n\n\n$\\theta_0$ has independent and identically distributed standard normal entries\n\n\n\n\n\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.\n\n\n\n\nHere is my code and these are the images that generate:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\nThese are the plots that generate:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/M60t0s9p.png] (https://i.sstatic.net/M60t0s9p.png)\n\n\n\n\nWhy are my plots increasing in general and not generally decreasing?\n\n\n\n\nWhat line of code do I need to fix?","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":"Sid Meka","profile_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","user_type":"registered"},"created_at":"2025-06-09T03:53:39+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"6C5B17A4-CCFF-4791-B573-A3BEFEA6E971","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6C5B17A4-CCFF-4791-B573-A3BEFEA6E971/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Anton Menshov","profile_url":"https://scicomp.stackexchange.com/users/20688/anton-menshov","user_type":"moderator"},"created_at":"2025-06-10T17:23:33+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"04CCF3DF-8003-43DC-8B20-604199CED7CE","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/04CCF3DF-8003-43DC-8B20-604199CED7CE/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"M. A.","profile_url":"https://scicomp.stackexchange.com/users/54367/m-a","user_type":"registered"},"created_at":"2025-08-03T03:10:56+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"432A63F6-E7D4-4894-AE88-DA68EC44307B","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/432A63F6-E7D4-4894-AE88-DA68EC44307B/view-source"}],"source_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":"45105","source_record_sha256":"35c351099a43859f9204894f051363e82b9bc668dfd14fc544c7117b6d7110af","source_url":"https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.

\n

Implement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:

\n
    \n
  1. $\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$
  2. \n
  3. $X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$
  4. \n
  5. $z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$
  6. \n
  7. $y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$
  8. \n
  9. $\\theta_0$ has independent and identically distributed standard normal entries
  10. \n
\n

Implement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.

\n

Here is my code and these are the images that generate:

\n
import numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n    return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n    yz = y * (X @ theta)\n    my_loss = np.log(1 + np.exp(-yz)).sum()\n    r = 0.5 * lmbda * np.linalg.norm(theta)**2\n    return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n    yz = y * (X @ theta)\n    ja = 1 / (1+np.exp(-yz))\n    toRETURN = -((y * ja) @ X) + lmbda * theta\n    return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n    n = X.shape[1]\n    theta = np.random.randn(n)\n    f_values = []\n    alpha = 1 / beta\n    for k in range(num_iters):\n        g = logistic_gradient(theta, X, y, lmbda)\n        theta = theta - alpha * g\n        f_values.append(logistic_objective(theta, X, y, lmbda))\n    return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n    n = X.shape[1]\n    theta = np.random.randn(n)\n    yk = theta.copy()\n    f_values = []\n    alpha = 1 / beta\n    jf = 1 # Used for strong convexity\n    for k in range(num_iters):\n        previous_theta = theta.copy()\n        gr = logistic_gradient(yk, X, y, lmbda)\n        theta = yk - alpha * gr\n        if k == 0:\n            gamma = 0\n        else:\n            gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n        yk = theta + gamma * (theta - previous_theta)\n        f_values.append(logistic_objective(theta, X, y, lmbda))\n    return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n    n = 50\n    m = 100\n    lmbda = 1\n    beta = 100\n\n    theta_opt = np.ones(n)\n    X = np.random.randn(m, n)\n    z = X @ theta_opt\n    p1857 = 1 / (1+np.exp(-z))\n\n    y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n    gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n    agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n    plt.figure(figsize=(8, 5))\n    plt.semilogy(gd_values, label="Gradient Descent")\n    plt.semilogy(agd_values, label="Accelerated Gradient Descent")\n    plt.xlabel("Iteration")\n    plt.ylabel("Objective Value with Logarithmic Scale")\n    plt.title("Logistic Regression: Objective Value vs Iteration "+str(i+1))\n    plt.legend()\n    plt.grid(True)\n    plt.show()\n
\n

These are the plots that generate:

\n

\"enter

\n

Why are my plots increasing in general and not generally decreasing?

\n

What line of code do I need to fix?

\n","question_title":"Logistic Regression: Gradient Descent and Accelerated Version Thereof not acting as intended","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45119,"score":3}],"answers":[{"answer_html":"

There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.

\n

$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$

\n

Approximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n\"wave

\n

If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n\"nonlinear

\n

My python code used to compute this and make the animation is below:

\n
import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n    return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n    # setup derivative approximation stencils using the fact\n    # we are using periodic BCs\n    dx = x[1] - x[0]\n    c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n    c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n    idx_upwind = np.array([-2, -1, 0], dtype=int)\n    idx_downwind = np.array([0, 1, 2], dtype=int)\n\n    # extract the two fields\n    n = len(x)\n    u = q[:n]\n    v = q[n:]\n\n    # compute time derivatives of both fields\n    dudt = np.zeros((n,))\n    dvdt = np.zeros((n,))\n    for i in range(n):\n        idu = i + idx_upwind\n        idd = i + idx_downwind\n        dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n        dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n    # return the concatenation of the two time derivative vectors\n    return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n    k1 = f(t, q)\n    k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n    k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n    k4 = f(t + dt, q + dt * k3)\n    return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n    # setup the function to compute time derivatives\n    f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n    # solve the PDE\n    nx = len(x_values)\n    nt = len(t_values)\n    dt = t_values[1] - t_values[0]\n    q_soln = np.zeros((2 * nx, nt))\n    q_soln[:, 0] = initial_condition(x_values)\n    for i in range(1, nt):\n        q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n    # return the solution to the PDE\n    return q_soln\n\ndef plot_solution(t, x, q_soln):\n    nv, nt = q_soln.shape\n    nu = nv // 2\n\n    # setup basics of figure\n    fig, ax = plt.subplots(figsize=(10, 6))\n    fig.set_dpi(80)\n    line, = ax.plot(x, q_soln[:nu, 0])\n    ax.set_xlim(x.min(), x.max())\n    ax.set_ylim(-1.5, 1.5)  # Set limits slightly wider\n    ax.set_xlabel('X-coordinate')\n    ax.set_ylabel(r"$\\phi(t)$", size=16)\n    ax.set_title('Solution over Time: Time = 0.00')\n\n    def update(frame):\n        print(f"Updating frame{frame}")\n        line.set_ydata(q_soln[:nu, frame])\n        ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n        return line,\n\n    # Create the animation\n    ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n    # To save the animation (requires ffmpeg or imagemagick installed)\n    #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n    ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n    #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n    # setup the time and space grid\n    t_values = np.linspace(0.0, t_final, num_times)\n    x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n    # compute solution to PDE\n    mu = 0.0*0.8\n    lmda = 0.0*1e-1/6.0\n    q_soln = simulation(x_values, t_values, mu, lmda)\n\n    # plot solution to PDE\n    plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n    main()\n
\n","answer_id":45119,"answer_text":"There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45119","author":"spektr","author_url":"https://scicomp.stackexchange.com/users/9804/spektr","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-06-17T21:04:45+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45112,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2025-06-17T21:04:45+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"E3F7E841-70B0-4D84-AA38-D0BBD92FA08E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}],"score":3,"updated_at":"2025-06-17T21:04:45+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"spektr","author_url":"https://scicomp.stackexchange.com/users/9804/spektr","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2025-06-17T21:04:45+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"E3F7E841-70B0-4D84-AA38-D0BBD92FA08E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45119"}],"question_author":"Peter","question_author_url":"https://scicomp.stackexchange.com/users/46677/peter"},"code_blocks":[{"block_index":0,"code_text":"256\n1000\n0.2\n0.05\n0.0\n0.0\n","post_id":"scicomp:45112","sha256":"c43dff7e9d58d182decb42a471797c4d7bdb82afbc85e00eeb68741e075be64c","source_url":"https://scicomp.stackexchange.com/questions/45112/phi4-theory-simulation"},{"block_index":1,"code_text":"64\n1000\n0.2\n0.05\n0.0\n0.0\n","post_id":"scicomp:45112","sha256":"8d4bf4005079f939f4cb141c5c49264cd8290255de334ab9e272cd180ffe615d","source_url":"https://scicomp.stackexchange.com/questions/45112/phi4-theory-simulation"},{"block_index":2,"code_text":"#include \n#include \n#include \nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin(\"input.txt\");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = new int[nx];\n double *phi = new double[nx];\n double *pi = new double[nx];\n double *psi = new double[nx];\n double *chi = new double[nx];\n for (int x = 0; x < nx; ++x) {\n if (x == 0) {\n sup[x] = x+1;\n sdn[x] = nx-1;\n }\n else if (x == nx-1) {\n sup[x] = 0;\n sdn[x] = x-1;\n }\n else {\n sup[x] = x+1;\n sdn[x] = x-1;\n }\n phi[x] = cos(x*dx);\n pi[x] = sin(x*dx);\n }\n std::ofstream fout;\n for (int t = 0; t < nt; ++t) {\n fout.open(\"output_\"+std::to_string(t)+\".txt\");\n for (int x = 0; x < nx; ++x) {\n psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n fout << x*dx << '\\t' << phi[x] << '\\n';\n }\n for (int x = 0; x < nx; ++x) {\n phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n }\n for (int x = 0; x < nx; ++x) {\n chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n }\n for (int x = 0; x < nx; ++x) {\n pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n }\n fout.close();\n }\n delete[] psi;\n delete[] chi;\n delete[] pi;\n delete[] phi;\n delete[] sup;\n delete[] sdn;\n}\n\n","post_id":"scicomp:45112","sha256":"2f05d5b975803e7185929f282da8d39c464edda9afab56f7c6e3ad6648fc4315","source_url":"https://scicomp.stackexchange.com/questions/45112/phi4-theory-simulation"},{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n","post_id":45119,"sha256":"faca96ee9ebdc2f00842d222df15e3cf8efccaaa302bfc5a3379c58534009c2a","source_url":"https://scicomp.stackexchange.com/a/45119"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"4555d610a0fd7865fc6bc1fd40e9cf827a05635eaa81a324122ca259e071f6ba","id":"SCT-77e900835afb430617db7ac9","language":null,"library_or_tool":null,"problem_text":"i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog (https://en.wikipedia.org/wiki/Leapfrog_integration) method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.\n\n\n\n\nBelow i listed some input files\n\n\n\n\nUnstable simulation (https://jumpshare.com/s/zPqlo3o0AGXPfadHQmxG)\n\n\n\n\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nHere is much more stable simulation (https://jumpshare.com/s/IyNNcFdCeCTAcpIShWLY) with this input file\n\n\n\n\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nThis is my C++ code.\n\n\n\n\nsimulation.cpp\n\n\n\n\n#include \n#include \n#include \nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin(\"input.txt\");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = new int[nx];\n double *phi = new double[nx];\n double *pi = new double[nx];\n double *psi = new double[nx];\n double *chi = new double[nx];\n for (int x = 0; x < nx; ++x) {\n if (x == 0) {\n sup[x] = x+1;\n sdn[x] = nx-1;\n }\n else if (x == nx-1) {\n sup[x] = 0;\n sdn[x] = x-1;\n }\n else {\n sup[x] = x+1;\n sdn[x] = x-1;\n }\n phi[x] = cos(x*dx);\n pi[x] = sin(x*dx);\n }\n std::ofstream fout;\n for (int t = 0; t < nt; ++t) {\n fout.open(\"output_\"+std::to_string(t)+\".txt\");\n for (int x = 0; x < nx; ++x) {\n psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n fout << x*dx << '\\t' << phi[x] << '\\n';\n }\n for (int x = 0; x < nx; ++x) {\n phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n }\n for (int x = 0; x < nx; ++x) {\n chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n }\n for (int x = 0; x < nx; ++x) {\n pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n }\n fout.close();\n }\n delete[] psi;\n delete[] chi;\n delete[] pi;\n delete[] phi;\n delete[] sup;\n delete[] sdn;\n}","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":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-06-13T14:05:56+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"E3F1692B-284D-429A-BB81-9E43CBC81415","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E3F1692B-284D-429A-BB81-9E43CBC81415/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-06-13T14:51:56+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"7D26CDF1-CAE4-41CD-8AEB-80E95CA1C767","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/7D26CDF1-CAE4-41CD-8AEB-80E95CA1C767/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-06-13T18:24:34+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"0FFC68D5-683F-4BAF-8E15-7AEF3DBF0FAB","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0FFC68D5-683F-4BAF-8E15-7AEF3DBF0FAB/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-06-14T00:00:14+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"DA618E30-DA8A-417B-B48F-EAE300C8A4FD","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DA618E30-DA8A-417B-B48F-EAE300C8A4FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-06-14T16:05:01+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"8615C30E-9A24-4D94-B6BE-0A97751FBB3F","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/8615C30E-9A24-4D94-B6BE-0A97751FBB3F/view-source"},{"content_license":null,"contributor":{"display_name":"hardmath","profile_url":"https://scicomp.stackexchange.com/users/651/hardmath","user_type":"moderator"},"created_at":"2025-06-17T16:02:03+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"DE456A75-099D-4EE5-BC89-98121EAF212A","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/DE456A75-099D-4EE5-BC89-98121EAF212A/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":"45112","source_record_sha256":"06cc26502ad59e03f6fb85890bf12a68b11f4976dc714b0591e421959a245013","source_url":"https://scicomp.stackexchange.com/questions/45112/phi4-theory-simulation","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.

\n

Below i listed some input files

\n

Unstable simulation

\n
256\n1000\n0.2\n0.05\n0.0\n0.0\n
\n

Here is much more stable simulation with this input file

\n
64\n1000\n0.2\n0.05\n0.0\n0.0\n
\n

This is my C++ code.

\n

simulation.cpp

\n
#include <iostream>\n#include <fstream>\n#include <cmath>\nint main() {\n    int nx, nt;\n    double dx, dt, mu, lambda;\n    std::ifstream fin("input.txt");\n    fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n    fin.close();\n    int *sup = new int[nx];\n    int *sdn = new int[nx];\n    double *phi = new double[nx];\n    double *pi = new double[nx];\n    double *psi = new double[nx];\n    double *chi = new double[nx];\n    for (int x = 0; x < nx; ++x) {\n        if (x == 0) {\n            sup[x] = x+1;\n            sdn[x] = nx-1;\n        }\n        else if (x == nx-1) {\n            sup[x] = 0;\n            sdn[x] = x-1;\n        }\n        else {\n            sup[x] = x+1;\n            sdn[x] = x-1;\n        }\n        phi[x] = cos(x*dx);\n        pi[x] = sin(x*dx);\n    }\n    std::ofstream fout;\n    for (int t = 0; t < nt; ++t) {\n        fout.open("output_"+std::to_string(t)+".txt");\n        for (int x = 0; x < nx; ++x) {\n            psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n            fout << x*dx << '\\t' << phi[x] << '\\n';\n        }\n        for (int x = 0; x < nx; ++x) {\n            phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n        }\n        for (int x = 0; x < nx; ++x) {\n            chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n        }\n        for (int x = 0; x < nx; ++x) {\n            pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n        }\n        fout.close();\n    }\n    delete[] psi;\n    delete[] chi;\n    delete[] pi;\n    delete[] phi;\n    delete[] sup;\n    delete[] sdn;\n}\n\n
\n","question_title":"Phi^4 theory simulation","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45112/phi4-theory-simulation","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45115,"score":1}],"answers":[{"answer_html":"

In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:

\n\n","answer_id":45115,"answer_text":"In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:\n\n\n\n\n\nAI Feynman: A physics-inspired method for symbolic regression (https://doi.org/10.1126/sciadv.aay2631)\n\n\n\n\nAI feynman 2.0: pareto-optimal symbolic regression exploiting graph modularity (https://dl.acm.org/doi/10.5555/3495724.3496132)\n\n\n\n\"our method has the potential\nto discover any graph modularity involving any functions of n = 2, 3, ... variables, by examining gradients of the neural network fit\"","answer_url":"https://scicomp.stackexchange.com/a/45115","author":"Robert Haas","author_url":"https://scicomp.stackexchange.com/users/54121/robert-haas","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-06-15T19:46:07+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":45114,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Robert Haas","profile_url":"https://scicomp.stackexchange.com/users/54121/robert-haas","user_type":"registered"},"created_at":"2025-06-15T19:46:07+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"D68F9BD0-0317-4F81-BD4D-EB38F889776C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D68F9BD0-0317-4F81-BD4D-EB38F889776C/view-source"}],"score":1,"updated_at":"2025-06-15T19:46:07+00:00"}],"attempted_method_if_explicit":"I tried scipy.curve_fit instead of random and it does not work so much. Here is the code:","author_attribution":{"answers":[{"author":"Robert Haas","author_url":"https://scicomp.stackexchange.com/users/54121/robert-haas","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Robert Haas","profile_url":"https://scicomp.stackexchange.com/users/54121/robert-haas","user_type":"registered"},"created_at":"2025-06-15T19:46:07+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"D68F9BD0-0317-4F81-BD4D-EB38F889776C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D68F9BD0-0317-4F81-BD4D-EB38F889776C/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45115"}],"question_author":"P'tit Ju","question_author_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n \"abs\": (sympy.Abs, operator.abs),\n \"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n \"sin\": (sympy.sin, np.sin),\n \"exp\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n \"exp\": (sympy.exp, np.exp),\n \"sinh\": (sympy.sinh, np.sinh),\n \"cosh\": (sympy.cosh, np.cosh),\n \"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n \"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor)}\n\nbinary_operators = {\"+\": (operator.add, operator.add),\n \"-\": (operator.sub, operator.sub),\n \"*\": (operator.mul, operator.mul),\n \"/\": (operator.truediv, operator.truediv),\n \"//\": (operator.floordiv, operator.floordiv),\n \"%\": (operator.mod, operator.mod),\n \"**\": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False}\nsymbols = sympy.symbols(\"x1 x2\")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint(\"Top 10 features les plus corrélées (Pearson):\\n\")\nfor name in correlations_sorted.head(10).index:\n print(f\"{name:30} corr: {correlations[name]:+.4f}\")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint(\"Top 10 features les plus utiles :\\n\")\nfor name, score, r in features_sorted[:10]:\n print(f\"{name:30} importance: {score:.4f} {r:.4f}\")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint(\"un_ops\", un_ops)\nprint(\"bin_ops\", bin_ops)\n","post_id":"scicomp:45114","sha256":"78dba7885a20e63643a6554b8a60c6ad8737f2dd107bf9d921e8d7a62059b281","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression"},{"block_index":1,"code_text":"Top 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n","post_id":"scicomp:45114","sha256":"436033790f67132be0f91d3067b8e83d9f8b7b82232e8b72111f2789002bbfc9","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression"},{"block_index":2,"code_text":"import numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = \"a\" + str(self.index)\n b = \"b\" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + \"*\" + str(self.leaf1) + \"+\" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr())) + \")+\" + b)\n \n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + \")+\" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, \"\", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n #\"abs\": (sympy.Abs, operator.abs),\n #\"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n #\"sin\": (sympy.sin, np.sin),\n #\"tan\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n #\"exp\": (sympy.exp, np.exp),\n #\"sinh\": (sympy.sinh, np.sinh),\n #\"cosh\": (sympy.cosh, np.cosh),\n #\"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n #\"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor),\n }\n\nbinary_operators = {#\"+\": (operator.add, operator.add),\n #\"-\": (operator.sub, operator.sub),\n #\"*\": (operator.mul, operator.mul),\n #\"/\": (operator.truediv, operator.truediv),\n #\"//\": (operator.floordiv, operator.floordiv),\n #\"%\": (operator.mod, operator.mod),\n #\"**\": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False, \"fmin\": True, \"fmax\": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol(\"x1\")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols(\"x1 x2\"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n","post_id":"scicomp:45114","sha256":"a998555823461bb09e342955554a0bd3139d8a6a6afe1a182db78b95a52a38d1","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression"},{"block_index":3,"code_text":"def fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == \"a\"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n","post_id":"scicomp:45114","sha256":"7d2230fd237590c084f5c8b12fbe40cae4b8e510307bfc56c850884f26d233c4","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression"},{"block_index":4,"code_text":"[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]\n","post_id":"scicomp:45114","sha256":"2a6232f2e851aefdf67dde31b8fb436cb7dbef1e2ae75b9f79ffd8ddff2c93fa","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"ae6a85a6483b17c13bf3bcdf99b2d049b7f274b0a8e001245a6ace6d8dde1bab","id":"SCT-3dcba773b06428799c42255e","language":["python"],"library_or_tool":["numpy","pandas","scipy"],"problem_text":"I wrote a symbolic regression tool (https://github.com/Julien-Livet/SymbolicRegression) in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?\n\n\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n \"abs\": (sympy.Abs, operator.abs),\n \"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n \"sin\": (sympy.sin, np.sin),\n \"exp\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n \"exp\": (sympy.exp, np.exp),\n \"sinh\": (sympy.sinh, np.sinh),\n \"cosh\": (sympy.cosh, np.cosh),\n \"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n \"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor)}\n\nbinary_operators = {\"+\": (operator.add, operator.add),\n \"-\": (operator.sub, operator.sub),\n \"*\": (operator.mul, operator.mul),\n \"/\": (operator.truediv, operator.truediv),\n \"//\": (operator.floordiv, operator.floordiv),\n \"%\": (operator.mod, operator.mod),\n \"**\": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False}\nsymbols = sympy.symbols(\"x1 x2\")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint(\"Top 10 features les plus corrélées (Pearson):\\n\")\nfor name in correlations_sorted.head(10).index:\n print(f\"{name:30} corr: {correlations[name]:+.4f}\")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint(\"Top 10 features les plus utiles :\\n\")\nfor name, score, r in features_sorted[:10]:\n print(f\"{name:30} importance: {score:.4f} {r:.4f}\")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint(\"un_ops\", un_ops)\nprint(\"bin_ops\", bin_ops)\n\n\n\n\n\nThe corresponding output is:\n\n\n\n\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\n\n\n\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.\n\n\n\n\nThe corresponding code could approach this:\n\n\n\n\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = \"a\" + str(self.index)\n b = \"b\" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + \"*\" + str(self.leaf1) + \"+\" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr())) + \")+\" + b)\n \n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + \")+\" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, \"\", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n #\"abs\": (sympy.Abs, operator.abs),\n #\"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n #\"sin\": (sympy.sin, np.sin),\n #\"tan\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n #\"exp\": (sympy.exp, np.exp),\n #\"sinh\": (sympy.sinh, np.sinh),\n #\"cosh\": (sympy.cosh, np.cosh),\n #\"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n #\"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor),\n }\n\nbinary_operators = {#\"+\": (operator.add, operator.add),\n #\"-\": (operator.sub, operator.sub),\n #\"*\": (operator.mul, operator.mul),\n #\"/\": (operator.truediv, operator.truediv),\n #\"//\": (operator.floordiv, operator.floordiv),\n #\"%\": (operator.mod, operator.mod),\n #\"**\": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False, \"fmin\": True, \"fmax\": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol(\"x1\")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols(\"x1 x2\"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\n\n\n\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:\n\n\n\n\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == \"a\"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\n\n\n\n\nAnd the associated output (cos(log) optimization failed):\n\n\n\n\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]","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":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-15T09:46:23+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"6EC977E1-3082-4152-AE79-21C738DBF959","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6EC977E1-3082-4152-AE79-21C738DBF959/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-15T17:29:07+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"B4A3E844-33AB-4467-864F-D74942286C5A","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B4A3E844-33AB-4467-864F-D74942286C5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-16T18:01:50+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"4E41E649-9940-470F-BD64-37949F9902D3","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4E41E649-9940-470F-BD64-37949F9902D3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-17T08:11:19+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"C61EE61B-3C64-482A-BAC2-3A48B78BE0AE","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C61EE61B-3C64-482A-BAC2-3A48B78BE0AE/view-source"}],"source_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":"45114","source_record_sha256":"4d14ccdfe0a7e04d90e39efba3a4ca5bf83ae241e3ffdcc9f72d41e57fe8aaf0","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I wrote a symbolic regression tool in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?

\n
import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n                   "abs": (sympy.Abs, operator.abs),\n                   "inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n                   "sqrt": (sympy.sqrt, np.sqrt),\n                   "cos": (sympy.cos, np.cos),\n                   "sin": (sympy.sin, np.sin),\n                   "exp": (sympy.tan, np.tan),\n                   "log": (sympy.log, np.log),\n                   "exp": (sympy.exp, np.exp),\n                   "sinh": (sympy.sinh, np.sinh),\n                   "cosh": (sympy.cosh, np.cosh),\n                   "floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n                   "ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor)}\n\nbinary_operators = {"+": (operator.add, operator.add),\n                    "-": (operator.sub, operator.sub),\n                    "*": (operator.mul, operator.mul),\n                    "/": (operator.truediv, operator.truediv),\n                    "//": (operator.floordiv, operator.floordiv),\n                    "%": (operator.mod, operator.mod),\n                    "**": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False}\nsymbols = sympy.symbols("x1 x2")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n        \nfor i in range(0, len(symbols)):\n    X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n    sym_op, num_op = v\n\n    for var in symbols:\n        feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n        ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n    sym_op, num_op = v\n    \n    indices1 = list(range(0, len(symbols)))\n\n    for i1 in indices1:\n        indices2 = list(range(0, len(symbols)))\n\n        if (k in list(symmetric_binary_operators.keys())):\n            indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n                        \n        for i2 in indices2:\n            feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n            ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint("Top 10 features les plus corrélées (Pearson):\\n")\nfor name in correlations_sorted.head(10).index:\n    print(f"{name:30}  corr: {correlations[name]:+.4f}")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n    features_sorted[i] = list(features_sorted[i])\n    x = features_sorted[i]\n    imp_ = x[1]\n    x.append(abs(x[1] - imp))\n    imp = imp_\n\nprint("Top 10 features les plus utiles :\\n")\nfor name, score, r in features_sorted[:10]:\n    print(f"{name:30}  importance: {score:.4f} {r:.4f}")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n    #if (score > min_score):\n    if (r > min_r):\n        if (ops[name] in unary_operators):\n            un_ops.add(ops[name])\n        elif (ops[name] in binary_operators):\n            bin_ops.add(ops[name])  \n\nprint("un_ops", un_ops)\nprint("bin_ops", bin_ops)\n
\n

The corresponding output is:

\n
Top 10 features les plus corrélées (Pearson):\n\nx1*x2                           corr: -0.9480\nx1 + x2                         corr: -0.8527\nneg(x1)                         corr: +0.8298\nAbs(x1)                         corr: -0.8298\nceil(x1)                        corr: -0.8244\nfloor(x1)                       corr: -0.8244\nsqrt(x1)                        corr: -0.8170\nlog(x1)                         corr: -0.7880\ninv_(x1)                        corr: +0.6826\nsinh(x1)                        corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2                           importance: 0.7583 0.7583\nx1 + x2                         importance: 0.0850 0.6734\nlog(x1)                         importance: 0.0192 0.0658\ninv_(x1)                        importance: 0.0170 0.0022\nsinh(x1)                        importance: 0.0164 0.0007\nneg(x1)                         importance: 0.0162 0.0002\nsqrt(x1)                        importance: 0.0159 0.0003\nexp(x1)                         importance: 0.0159 0.0001\ncosh(x1)                        importance: 0.0151 0.0008\nAbs(x1)                         importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n
\n

Another approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.

\n

The corresponding code could approach this:

\n
import numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n    l = np.sum((x - y) ** 2)\n\n    if (np.isnan(l)):\n        return np.inf\n\n    return l\n\ndef num_modules(unary_ops, binary_ops):\n    modules = ['numpy']\n\n    for name, op in unary_ops.items():\n        sym_op, num_op = op\n\n        #if (type(sym_op) == sympy.Function):\n        if (name.isidentifier()):\n            modules.append({name: num_op})\n\n    for name, op in binary_ops.items():\n        sym_op, num_op = op\n\n        #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n        if (name.isidentifier()):\n            modules.append({name: num_op})\n\n    return modules\n\nclass Node:\n    def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n        self.symnet = symnet\n        self.index = symnet.add_param()\n        self.name = name\n        self.op = op\n        self.leaf1 = leaf1\n        self.leaf2 = leaf2\n        self.sym_x1 = sym_x1\n        self.num_x1 = num_x1\n        self.sym_x2 = sym_x2\n        self.num_x2 = num_x2\n\n    def evalf(self, modules):\n        leaf1 = copy.deepcopy(self.leaf1)\n        x = 0\n        \n        if (isinstance(leaf1, sympy.Symbol)):\n            f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n            x = f(self.num_x1)\n        else:\n            x = leaf1.evalf(modules)\n\n        leaf2 = copy.deepcopy(self.leaf2)\n\n        if (leaf2 == None):\n            if (self.op):\n                return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n            else:\n                return x\n        \n        y = 0\n        \n        if (isinstance(leaf2, sympy.Symbol)):\n            f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n            y = f(self.num_x2)\n        else:\n            y = leaf2.evalf(modules)\n        \n        return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n    \n    def expr(self):\n        a = "a" + str(self.index)\n        b = "b" + str(self.index)\n    \n        if (isinstance(self.leaf1, sympy.Symbol)):\n            return sympy.sympify(a + "*" + str(self.leaf1) + "+" + b)\n            \n        if (self.leaf2 == None):\n            if (self.op):\n                return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr())) + ")+" + b)\n                \n        return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + ")+" + b)\n\nclass SymNet:\n    def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n        self.X = X\n        self.symbols = symbols\n        self.un_ops = un_ops\n        self.bin_ops = bin_ops\n        self.un_ops_index = 0\n        self.bin_ops_index = 0\n        self.symm_bin_ops = symm_bin_ops\n        self.a = []\n        self.b = []\n        self.nodes = []\n        \n        assert(len(X) == len(symbols))\n        \n        for i in range(0, len(X)):\n            self.nodes.append(Node(self, "", None, symbols[i], symbols[i], X[i]))\n\n    def add_param(self):\n        self.a = np.array(list(self.a) + [0])\n        self.b = np.array(list(self.b) + [0])\n        \n        return len(self.a) - 1\n\n    def add_layer(self):    \n        new_nodes = []\n    \n        for k, v in self.un_ops.items():\n            for n in self.nodes[self.un_ops_index:]:\n                new_nodes.append(Node(self, k, v, n))\n\n        self.un_ops_index = len(self.nodes)\n        self.nodes += new_nodes\n        \n        new_nodes = []\n        nodes = self.nodes#[self.bin_ops_index:]\n    \n        for k, v in self.bin_ops.items():\n            indices1 = list(range(0, len(nodes)))\n\n            for i1 in indices1:\n                indices2 = list(range(0, len(nodes)))\n\n                for key, value in self.symm_bin_ops.items():\n                    if (k == key):\n                        indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n                        break\n                                \n                for i2 in indices2:\n                    new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n        #self.bin_ops_index = len(self.nodes)\n        self.nodes += new_nodes\n\n    def compute_outputs(self, a, b):\n        assert(len(a) == len(self.a))\n        assert(len(b) == len(self.b))\n        \n        self.a = a\n        self.b = b\n        \n        outputs = []\n        modules = num_modules(self.un_ops, self.bin_ops)\n\n        for n in self.nodes:\n            outputs.append(n.evalf(modules))\n\n        return outputs\n\n    def expressions(self):\n        exprs = []\n    \n        for n in self.nodes:\n            exprs.append(n.expr())\n\n        return exprs\n\n    def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n        outputs = None\n\n        for i in range(0, N):\n            o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n                                              np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n            \n            if (outputs is None):\n                outputs = np.zeros(len(o))\n\n            for j in range(0, len(o)):\n                outputs[j] += loss_func(o[j], y)\n\n        outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n        l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n        \n        #print([(x[0].expr(), x[1]) for x in l])\n        #print([(x[0].expr(), np.log(x[1])) for x in l])\n        \n        m = l[-1][1]\n        #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n        d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n        print(0.75 * d[0])\n        z = zip([x[0].expr() for x in l], d)\n        print(list((x, y) for x, y in z))\n\nunary_operators = {#"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n                   #"abs": (sympy.Abs, operator.abs),\n                   #"inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n                   "sqrt": (sympy.sqrt, np.sqrt),\n                   "cos": (sympy.cos, np.cos),\n                   #"sin": (sympy.sin, np.sin),\n                   #"tan": (sympy.tan, np.tan),\n                   "log": (sympy.log, np.log),\n                   #"exp": (sympy.exp, np.exp),\n                   #"sinh": (sympy.sinh, np.sinh),\n                   #"cosh": (sympy.cosh, np.cosh),\n                   #"floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n                   #"ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor),\n                   }\n\nbinary_operators = {#"+": (operator.add, operator.add),\n                    #"-": (operator.sub, operator.sub),\n                    #"*": (operator.mul, operator.mul),\n                    #"/": (operator.truediv, operator.truediv),\n                    #"//": (operator.floordiv, operator.floordiv),\n                    #"%": (operator.mod, operator.mod),\n                    #"**": (sympy.Pow, operator.pow),\n                    }\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False, "fmin": True, "fmax": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol("x1")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols("x1 x2"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n
\n

I tried scipy.curve_fit instead of random and it does not work so much. Here is the code:

\n
def fit(self, y, loss_func = mse_loss):\n    a_s = []\n    b_s = []\n    losses = []\n    exprs = self.expressions()\n    modules = num_modules(self.un_ops, self.bin_ops)\n    maxfev = 10000\n     \n    for expr in exprs:\n        a = np.zeros(len(symnet.a))\n        b = np.zeros(len(symnet.b))\n         \n        ab_syms = list(expr.free_symbols - set(self.symbols))\n        f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n        func = model_func(f)\n         \n        params = np.zeros(len(ab_syms))\n         \n        try:\n            params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n        except RuntimeError as e:\n            print(e)\n \n        for i in range(0, len(ab_syms)):\n            index = int(str(ab_syms[i])[1:])\n \n            if (str(ab_syms[i])[0] == "a"):\n                a[index] = params[i]\n            else:\n                b[index] = params[i]\n                 \n        l = loss_func(func(self.X, *params), y)\n         \n        a_s.append(a)\n        b_s.append(b)\n        losses.append(l)\n         \n    losses = np.array(losses)\n    losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n    losses = np.nan_to_num(losses, neginf = np.max(losses))\n    losses = 1 - losses / np.max(losses)\n         \n    print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n
\n

And the associated output (cos(log) optimization failed):

\n
[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]\n
\n","question_title":"Find necessary operators for symbolic regression","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45267,"score":3}],"answers":[{"answer_html":"
\n

Poincaré section obtained by conditions in the code

\n
\n

I very much cannot reproduce what you've generated, after refactoring - I suspect due to moving to the more sophisticated LSODA and its accompanying parameters. I get results more similar to the resonances seen in e.g. Leo Stein's Poincaré sections.

\n
\n

The code can also be improved, so if anyone has any suggestions

\n
\n

Well... There's a lot. Since this is the Computational Science site and not the Code Review site, I will elide much of my feedback by saying "improve your Python". For the numerics:

\n
    \n
  • Your g is both wrong and unnecessary; get the correct value from Scipy instead
  • \n
  • Don't use the math module; stick to Numpy
  • \n
  • f() is both pretty slow and wholly illegible. It can be somewhat sped up by identifying common expressions, and should be broken up into many more lines. The same applies to E().
  • \n
  • The current parameters to solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.
  • \n
  • For plotting, only call plt.show() once.
  • \n
\n

\"poincare\"

\n
import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n    E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -> tuple[\n    np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n    theta_1_0 = np.zeros(n_initial_conditions)\n    theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n    theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n    abs_t10 = np.sqrt(\n        2*(\n            (\n                E + l_2*m_2*g*np.cos(theta_2_0)\n            )/(m_1 + m_2)\n            - l_2*g\n        )\n    )/l_1\n\n    theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n    return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -> tuple[\n    float, float, float, float,\n]:\n    y0, y1, y2, y3 = y\n    sin_y01 = 2*np.sin(y0 - y1)\n    cos_y01 = np.cos(y0 - y1)\n    m12m2 = 2*m_1 + m_2\n    den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n    y22l1 = y2**2*l_1\n    y32l2 = l_2*y3**2\n\n    res = (\n        y2,\n        y3,\n        (\n            -g*np.sin(y0)*m12m2 - m_2*(\n                g*np.sin(y0 - 2*y1)\n                + sin_y01*(\n                    y22l1*cos_y01 + y32l2\n                )\n            )\n        ) / (l_1*den),\n        (\n            sin_y01*(\n                (m_1 + m_2)*(\n                    np.cos(y0)*g + y22l1\n                )\n                + m_2*y32l2*cos_y01\n            )\n        ) / (l_2*den),\n    )\n    return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -> float:\n    """energy of the system"""\n    total_energy = (\n        0.5*l_1**2*y_3**2*(m_1 + m_2)\n        + 0.5*m_2*l_2**2*y_4**2\n        + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n        - l_1*g*np.cos(y_1)*(m_1 + m_2)\n        - l_2*m_2*g*np.cos(y_2)\n        + (l_1 + l_2)*g*(m_1 + m_2)\n    )\n    return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -> plt.Figure:\n    theta_2 = []\n    theta_2_dot = []\n    colors = []\n\n    color = (\n        "#2C3E50", "#3A3F64", "#484078", "#56428D", "#6B469E",\n        "#804AAF", "#954EBF", "#A753C4", "#BA58C8", "#CE5DCD",\n        "#E062C9", "#E971B4", "#F1809F", "#F98F8A", "#FFA07A",\n        "#FF9C65", "#FF9850", "#FF943B", "#FF9026", "#FF8C11",\n        "#F97F0D", "#F3730A", "#ED6606", "#E75A03", "#E04E00",\n        "#D4431E", "#C8383C", "#BC2D5A", "#B02178", "#A41596",\n        "#9710A3", "#880EA7", "#790CAB", "#6A0AAF", "#5C08B2",\n        "#4D06B6", "#3E04BA", "#2F02BD", "#2000C1", "#1800B8",\n        "#1000AF", "#0800A6", "#00009D", "#00008F", "#000081",\n        "#0B006C", "#160057", "#210043", "#2C002E", "#37001A"\n    )\n\n    for solution, colori in zip(solutions, color):\n        n_points = len(solution.t)\n        y0, y1, y2, y3 = solution.y\n\n        for j in range(n_points - 1):\n            if y0[j] <= 0 <= y0[j + 1]:\n                colors.append(colori)\n                theta_2.append(y1[j + 1])\n                theta_2_dot.append(y3[j + 1])\n\n    fig, ax = plt.subplots()\n\n    for m in range(len(theta_2)):\n        ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n    ax.set_xlabel(r"$\\theta_2\\ [rad]$")\n    ax.set_ylabel(r"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$")\n    return fig\n\n\ndef solve_motion_equations(\n    theta_1_0: np.ndarray,\n    theta_2_0: np.ndarray,\n    theta_1_dot_0: np.ndarray,\n    theta_2_dot_0: np.ndarray,\n    strict: bool = True,\n    error_max: float = 1e-3,\n    rtol: float = 1e-4, atol: float = 1e-6,\n) -> list[OdeResult]:\n    """solving the equations of motion"""\n    solutions = []\n\n    # defining time interval\n    t_span = (0, 750)\n    jac_sparsity = np.array((  # All methods but LSODA\n        (0, 0, 1, 0),\n        (0, 0, 0, 1),\n        (1, 1, 1, 1),\n        (1, 1, 1, 1),\n    ))\n    # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n    for i in range(len(theta_1_0)):\n        y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n        t0 = time.perf_counter()\n        solutions.append(solve_ivp(\n            fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n            # jac_sparsity=jac_sparsity,\n            rtol=rtol, atol=atol,\n        ))\n        t1 = time.perf_counter()\n        print(t1 - t0)\n\n        system_energy = E(*y0)\n        for y in solutions[i].y.T:\n            solution_energy = E(*y)\n            error = np.abs(solution_energy - system_energy)\n            if strict and error > error_max:\n                message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n                raise ValueError(message)\n\n    return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -> tuple[\n    np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n    x_1 = l_1*np.sin(solutions[0].y[0])\n    x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n    y_1 = -l_1*np.cos(solutions[0].y[0])\n    y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n    return x_1, x_2, y_1, y_2\n\n\ndef plot(\n    solutions: list[OdeSolution],\n    x_1: np.ndarray, x_2: np.ndarray,\n    y_1: np.ndarray, y_2: np.ndarray,\n) -> None:\n    fig, ax = plt.subplots()\n    ax.plot(solutions[0].y[0], solutions[0].y[1])\n    ax.set_xlabel(r"$\\theta_1\\ [rad]$")\n    ax.set_ylabel(r"$\\theta_2\\ [rad]$")\n\n    fig, ax = plt.subplots()\n    ax.plot(x_1, y_1)\n    ax.set_xlabel('x_1')\n    ax.set_ylabel('y_1')\n\n    fig, ax = plt.subplots()\n    ax.plot(x_2, y_2)\n    ax.set_xlabel('x_2')\n    ax.set_ylabel('y_2')\n\n    fig, ax = plt.subplots()\n    ax.plot(x_1, y_1, label='y_1')\n    ax.plot(x_2, y_2, label='y_2')\n    ax.legend()\n\n\ndef main() -> None:\n    n_initial_conditions = 3  # 50\n    rand = np.random.default_rng(seed=0)\n\n    theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n        E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n    )\n    solutions = solve_motion_equations(\n        theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n        theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n        error_max=0.1,\n    )\n    plot_poincaré_section(solutions)\n    x_1, x_2, y_1, y_2 = fill_xy(solutions)\n    plot(solutions, x_1, x_2, y_1, y_2)\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n
\n","answer_id":45267,"answer_text":"Poincaré section obtained by conditions in the code\n\n\n\n\n\n\n\nI very much cannot reproduce what you've generated, after refactoring - I suspect due to moving to the more sophisticated LSODA and its accompanying parameters. I get results more similar to the resonances seen in e.g. Leo Stein's Poincaré sections (https://duetosymmetry.com/tool/poincare-section-clicker-toy/).\n\n\n\n\n\n\n\nThe code can also be improved, so if anyone has any suggestions\n\n\n\n\n\n\n\nWell... There's a lot. Since this is the Computational Science site and not the Code Review site, I will elide much of my feedback by saying \"improve your Python\". For the numerics:\n\n\n\n\n\nYour g is both wrong and unnecessary; get the correct value from Scipy instead\n\n\n\n\nDon't use the math module; stick to Numpy\n\n\n\n\nf() is both pretty slow and wholly illegible. It can be somewhat sped up by identifying common expressions, and should be broken up into many more lines. The same applies to E().\n\n\n\n\nThe current parameters to solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.\n\n\n\n\nFor plotting, only call plt.show() once.\n\n\n\n\n\n[image: poincare; source: https://i.sstatic.net/INKhjIWk.png] (https://i.sstatic.net/INKhjIWk.png)\n\n\n\n\nimport time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -> tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -> float:\n \"\"\"energy of the system\"\"\"\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -> plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] <= 0 <= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r\"$\\theta_2\\ [rad]$\")\n ax.set_ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -> list[OdeResult]:\n \"\"\"solving the equations of motion\"\"\"\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error > error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -> None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r\"$\\theta_1\\ [rad]$\")\n ax.set_ylabel(r\"$\\theta_2\\ [rad]$\")\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -> None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45267","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-26T03:59:29+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":45171,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-26T03:59:29+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9/view-source"}],"score":3,"updated_at":"2025-10-26T03:59:29+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-26T03:59:29+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45267"}],"question_author":"Dávid Jopek","question_author_url":"https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek"},"code_blocks":[{"block_index":0,"code_text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n for i in range(number_of_initial_conditions):\n theta_1_0.append(0)\n # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n theta_2_dot_0.append(0)\n bucket = []\n bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n return [y[2], \n y[3], \n (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n theta_2 = []\n theta_2_dot = []\n\n colors = []\n\n color = [\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n ]\n\n for i in range(total_numbers_of_initial_conditions):\n # color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n # for s in range(1)]\n\n number_of_points = len(solutions[i].t)\n\n for j in range(number_of_points-1):\n if solutions[i].y[0][j] <= 0 and solutions[i].y[0][j+1] >= 0:\n colors.append(color[i])\n theta_2.append(solutions[i].y[1][j+1])\n theta_2_dot.append(solutions[i].y[3][j+1])\n\n for m in range(len(theta_2)):\n plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n plt.xlabel(r\"$\\theta_2\\ [rad]$\")\n plt.ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n system_energy = E(y0[0], y0[1], y0[2], y0[3])\n print(y0)\n print(system_energy)\n solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n number_of_points = len(solutions[i].t)\n \n for j in range(number_of_points):\n solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n if np.abs(solution_energy - system_energy) > error:\n sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r\"$\\theta_1\\ [rad]$\")\nplt.ylabel(r\"$\\theta_2\\ [rad]$\")\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n","post_id":"scicomp:45171","sha256":"1d67820d96c570166fb54e56067d4cef4f8c2e54fa592f7764a9d6f5c940d00b","source_url":"https://scicomp.stackexchange.com/questions/45171/poincar%c3%a9-section-for-double-pendulum-code-improvement"},{"block_index":0,"code_text":"import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -> tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -> float:\n \"\"\"energy of the system\"\"\"\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -> plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] <= 0 <= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r\"$\\theta_2\\ [rad]$\")\n ax.set_ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -> list[OdeResult]:\n \"\"\"solving the equations of motion\"\"\"\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error > error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -> None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r\"$\\theta_1\\ [rad]$\")\n ax.set_ylabel(r\"$\\theta_2\\ [rad]$\")\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -> None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","post_id":45267,"sha256":"ae3ad9e84c6f094fe7cfe99f0f34dd3421a235cc15f4e45eab8309949d15b321","source_url":"https://scicomp.stackexchange.com/a/45267"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"ed2a9d2587e3f69c6a3c4267804faeb1efbf2972fe158867e4407c039f990596","id":"SCT-b6ddc6069d6bcd18b99d1056","language":["python"],"library_or_tool":["numpy","scipy"],"problem_text":"I wanted to try numerical analysis of a chaotic system. So I decided to write my own code for the Poincaré section of a double pendulum in Python. The code works and the Poincaré section should be correct, but I can't get a nice picture of the section, like you see in textbooks or on the internet. I don't know if the problem is in the choice of energies, the (number of) initial conditions, or the integration \"time interval\" and steps. Can someone more experienced advise me on a good approach to obtaining nice Poincaré sections? The code can also be improved, so if anyone has any suggestions for improvements, I would be very happy to hear them!\n\n\n\n\nHere is the code: https://github.com/DJopek/chaos/blob/main/double_pendulum.py (https://github.com/DJopek/chaos/blob/main/double_pendulum.py)\n\n\n\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n for i in range(number_of_initial_conditions):\n theta_1_0.append(0)\n # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n theta_2_dot_0.append(0)\n bucket = []\n bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n return [y[2], \n y[3], \n (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n theta_2 = []\n theta_2_dot = []\n\n colors = []\n\n color = [\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n ]\n\n for i in range(total_numbers_of_initial_conditions):\n # color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n # for s in range(1)]\n\n number_of_points = len(solutions[i].t)\n\n for j in range(number_of_points-1):\n if solutions[i].y[0][j] <= 0 and solutions[i].y[0][j+1] >= 0:\n colors.append(color[i])\n theta_2.append(solutions[i].y[1][j+1])\n theta_2_dot.append(solutions[i].y[3][j+1])\n\n for m in range(len(theta_2)):\n plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n plt.xlabel(r\"$\\theta_2\\ [rad]$\")\n plt.ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n system_energy = E(y0[0], y0[1], y0[2], y0[3])\n print(y0)\n print(system_energy)\n solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n number_of_points = len(solutions[i].t)\n \n for j in range(number_of_points):\n solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n if np.abs(solution_energy - system_energy) > error:\n sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r\"$\\theta_1\\ [rad]$\")\nplt.ylabel(r\"$\\theta_2\\ [rad]$\")\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n\n\n\n\n\nPoincaré section obtained by conditions in the code:\n[image: Poincaré section obtained by conditions in the code; source: https://i.sstatic.net/U0nOulED.png] (https://i.sstatic.net/U0nOulED.png)\n\n\n\n\nEDIT:\nPoincaré section obtained by conditions in the code with labels[image: Poincaré section obtained by conditions in the code with labels; source: https://i.sstatic.net/oJaBUfA4.png] (https://i.sstatic.net/oJaBUfA4.png)","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":"Dávid Jopek","profile_url":"https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek","user_type":"registered"},"created_at":"2025-07-15T18:16:26+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"650653BB-F748-411A-AA5A-3EB629C84696","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/650653BB-F748-411A-AA5A-3EB629C84696/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Dávid Jopek","profile_url":"https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek","user_type":"registered"},"created_at":"2025-07-15T20:05:50+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"95B2D6D6-09DE-443D-9C99-ED7070A24120","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/95B2D6D6-09DE-443D-9C99-ED7070A24120/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-26T02:04:23+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"9709635F-9F4A-425B-AB66-BE60E6D8B46F","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9709635F-9F4A-425B-AB66-BE60E6D8B46F/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":"45171","source_record_sha256":"08652437b2d82d41bb11aa486c3f39893ff230772f628f36d067c93191bf3d13","source_url":"https://scicomp.stackexchange.com/questions/45171/poincar%c3%a9-section-for-double-pendulum-code-improvement","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I wanted to try numerical analysis of a chaotic system. So I decided to write my own code for the Poincaré section of a double pendulum in Python. The code works and the Poincaré section should be correct, but I can't get a nice picture of the section, like you see in textbooks or on the internet. I don't know if the problem is in the choice of energies, the (number of) initial conditions, or the integration "time interval" and steps. Can someone more experienced advise me on a good approach to obtaining nice Poincaré sections? The code can also be improved, so if anyone has any suggestions for improvements, I would be very happy to hear them!

\n

Here is the code: https://github.com/DJopek/chaos/blob/main/double_pendulum.py

\n
import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n    for i in range(number_of_initial_conditions):\n        theta_1_0.append(0)\n        # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n        theta_2_dot_0.append(0)\n        bucket = []\n        bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n        bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n        theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n    initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n    return [y[2], \n            y[3], \n            (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n            (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n    total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n    return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n    theta_2 = []\n    theta_2_dot = []\n\n    colors = []\n\n    color = [\n    "#2C3E50", "#3A3F64", "#484078", "#56428D", "#6B469E",\n    "#804AAF", "#954EBF", "#A753C4", "#BA58C8", "#CE5DCD",\n    "#E062C9", "#E971B4", "#F1809F", "#F98F8A", "#FFA07A",\n    "#FF9C65", "#FF9850", "#FF943B", "#FF9026", "#FF8C11",\n    "#F97F0D", "#F3730A", "#ED6606", "#E75A03", "#E04E00",\n    "#D4431E", "#C8383C", "#BC2D5A", "#B02178", "#A41596",\n    "#9710A3", "#880EA7", "#790CAB", "#6A0AAF", "#5C08B2",\n    "#4D06B6", "#3E04BA", "#2F02BD", "#2000C1", "#1800B8",\n    "#1000AF", "#0800A6", "#00009D", "#00008F", "#000081",\n    "#0B006C", "#160057", "#210043", "#2C002E", "#37001A"\n    ]\n\n    for i in range(total_numbers_of_initial_conditions):\n        # color = ["#"+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n        #             for s in range(1)]\n\n        number_of_points = len(solutions[i].t)\n\n        for j in range(number_of_points-1):\n            if solutions[i].y[0][j] <= 0 and solutions[i].y[0][j+1] >= 0:\n                colors.append(color[i])\n                theta_2.append(solutions[i].y[1][j+1])\n                theta_2_dot.append(solutions[i].y[3][j+1])\n\n    for m in range(len(theta_2)):\n        plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n    plt.xlabel(r"$\\theta_2\\ [rad]$")\n    plt.ylabel(r"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$")\n    plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n    y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n    system_energy = E(y0[0], y0[1], y0[2], y0[3])\n    print(y0)\n    print(system_energy)\n    solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n    number_of_points = len(solutions[i].t)\n    \n    for j in range(number_of_points):\n        solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n        if np.abs(solution_energy - system_energy) > error:\n            sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n    x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n    x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n    y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n    y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r"$\\theta_1\\ [rad]$")\nplt.ylabel(r"$\\theta_2\\ [rad]$")\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n
\n

Poincaré section obtained by conditions in the code:\n\"Poincaré

\n

EDIT:\nPoincaré section obtained by conditions in the code with labels\"Poincaré

\n","question_title":"Poincaré section for double pendulum code improvement","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45171/poincar%c3%a9-section-for-double-pendulum-code-improvement","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45186,"score":3}],"answers":[{"answer_html":"

I might have found the solution, of which I'm listing the main points/observations here below:

\n
    \n
  • the FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok
  • \n
  • the dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output
  • \n
  • SPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)
  • \n
  • a spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)
  • \n
\n

Of course, if you have any further comments or observations let me know!

\n","answer_id":45186,"answer_text":"I might have found the solution, of which I'm listing the main points/observations here below:\n\n\n\n\n\nthe FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok\n\n\n\n\nthe dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output\n\n\n\n\nSPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)\n\n\n\n\na spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)\n\n\n\n\n\nOf course, if you have any further comments or observations let me know!","answer_url":"https://scicomp.stackexchange.com/a/45186","author":"Lorenzo Iori","author_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-07-29T14:07:20+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45185,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-29T14:07:20+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"163AA634-CBFB-456A-AD54-8FFDF16B1F6A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}],"score":3,"updated_at":"2025-07-29T14:07:20+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Lorenzo Iori","author_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-29T14:07:20+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"163AA634-CBFB-456A-AD54-8FFDF16B1F6A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45186"}],"question_author":"Lorenzo Iori","question_author_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori"},"code_blocks":[{"block_index":0,"code_text":"# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n","post_id":"scicomp:45185","sha256":"0d2b3403abb149f3932d554d6c2486b994277a374004385ddffc9f133673e9b4","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything"},{"block_index":1,"code_text":"GDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n","post_id":"scicomp:45185","sha256":"ede79eca3b653fe963abc5472095cd3c0de51969188b65b546e86f4f30cabf88","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"bd5fd699490a197c46453cd6248b87ba2e8c956fa8b9f71ad9a2f50b5a440c08","id":"SCT-906af7b675a6b310cac98ed7","language":["python"],"library_or_tool":null,"problem_text":"I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.\n\n\n\n\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).\n\n\n\n\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.\n\n\n\n\nHere are the fundamental cells of the notebook:\n\n\n\n\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\n\n\n\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention\n\n\n\n\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\n\n\n\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...","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":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T09:04:03+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T09:15:52+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"BE26735D-FCBC-47F1-A566-F341DD41F55C","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BE26735D-FCBC-47F1-A566-F341DD41F55C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T14:07:20+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"67CC67B8-AC93-4C69-9C21-0E6BDBF43102","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/67CC67B8-AC93-4C69-9C21-0E6BDBF43102/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T14:32:46+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"3BBDD6A2-8D30-430A-8EAF-A458144119BA","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3BBDD6A2-8D30-430A-8EAF-A458144119BA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-29T14:04:04+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"B35F7AAE-2953-45D0-AD16-97CC9997095D","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B35F7AAE-2953-45D0-AD16-97CC9997095D/view-source"}],"source_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":"45185","source_record_sha256":"5223204980616f3e7438fe5ec2e2fc70fc28a4270ef10902b49578dee783c8e3","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.

\n

The issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).

\n

My question basically is if the implementation is correct or if there are any inconsistencies in the code below.

\n

Here are the fundamental cells of the notebook:

\n
# freq to time:\ndef ifft(A_w):\n    return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n    return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n    \n    A_w = fft(A)\n    A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n    A = ifft(A_w)\n    \n    gamma = (w0 / c) * n2 / eff_area\n    I = abs(A)**2\n    # without self-steepening\n    A = A * np.exp(- 1j * gamma * dz * I)\n    # with self-steepening\n    # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n        \n    A_w = fft(A)\n    A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n    A = ifft(A_w)\n    \n    return A\n
\n

Moreover, when introducing GDD<0 with chirped mirrors, I use the convention

\n
GDD_mirror = -45e-30    # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n
\n

Edit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...

\n","question_title":"Split-step Fourier method for ultrashort pulse propagation predicts everything, but not the spectral phase","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything","split":"test"} {"accepted_answer":null,"answer_scores":[{"answer_id":45249,"score":3}],"answers":[{"answer_html":"

The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:

\n
import operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n    return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n    sign = 2*(j%2) - 1\n    num = Pi(j+1, 660)*P656\n    p656j = Pi(656-j, 660-j)\n    den = p656j*Pi(1, 655-j)*(P656 - p656j)\n    return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n
\n
930.8341950323121\n
\n","answer_id":45249,"answer_text":"The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121","answer_url":"https://scicomp.stackexchange.com/a/45249","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-05T23:39:31+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45236,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-05T23:39:31+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"75229101-2A2D-4D73-B2A6-80096500FF72","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-05T23:51:10+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"11E4EE0D-659A-4B05-9326-A45AF5CAE292","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}],"score":3,"updated_at":"2025-10-05T23:51:10+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-05T23:39:31+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"75229101-2A2D-4D73-B2A6-80096500FF72","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-05T23:51:10+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"11E4EE0D-659A-4B05-9326-A45AF5CAE292","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45249"}],"question_author":"gregb","question_author_url":"https://scicomp.stackexchange.com/users/54734/gregb"},"code_blocks":[{"block_index":0,"code_text":"import math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")\n\n","post_id":"scicomp:45236","sha256":"a635a3b792dcc184f0c00b72996f91bef2185154972e2cde57e2134986e16b37","source_url":"https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere"},{"block_index":0,"code_text":"import operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n","post_id":45249,"sha256":"e4d397e8c08b33a0a68cb32ae1237aaa1b2c1f7aef510dd3dbb955639a59e4c1","source_url":"https://scicomp.stackexchange.com/a/45249"},{"block_index":1,"code_text":"930.8341950323121\n","post_id":45249,"sha256":"b3a5f68d31046441804550f332a2947539b56961ce3e7563135fcdf702982c39","source_url":"https://scicomp.stackexchange.com/a/45249"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"7322237dffe0cb72ec65ab677c86dad026f7124b703d5b1ddc30735cc81be0bc","id":"SCT-d0b5524e516902b23358bb9b","language":["python"],"library_or_tool":null,"problem_text":"I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)\n\n\n\n\nOn page 4 I am trying to turn this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)\n\n\n\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'\n\n\n\n\nHere is my code, where am I going wrong? Thanks.\n\n\n\n\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")","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":"gregb","profile_url":"https://scicomp.stackexchange.com/users/54734/gregb","user_type":"registered"},"created_at":"2025-09-15T21:46:02+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"67059698-6CDA-4CFD-903D-00B6A505C963","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/67059698-6CDA-4CFD-903D-00B6A505C963/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"gregb","profile_url":"https://scicomp.stackexchange.com/users/54734/gregb","user_type":"registered"},"created_at":"2025-09-15T22:34:16+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"D1E2F3BD-4E46-4D76-9C39-8BDE6F9F73EC","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D1E2F3BD-4E46-4D76-9C39-8BDE6F9F73EC/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"gregb","profile_url":"https://scicomp.stackexchange.com/users/54734/gregb","user_type":"registered"},"created_at":"2025-09-16T10:52:22+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"9212784D-B74F-41A1-8936-363A81039240","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9212784D-B74F-41A1-8936-363A81039240/view-source"}],"source_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":"45236","source_record_sha256":"229e9229742eb26a013d72362257c79f7e2e4cfe8857604720e82a0692477ead","source_url":"https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf

\n

On page 4 I am trying to turn this:

\n

\"enter

\n

into python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'

\n

Here is my code, where am I going wrong? Thanks.

\n
import math\n\ndef calculate_expression():\n    n = 660\n    k = 5\n\n    # Calculate the outer binomial coefficient (660 choose 5)\n    outer_binomial_coefficient = math.comb(n, k)\n\n    sum_terms = 0\n\n    # Iterate for the summation from j = 1 to 660\n    for j in range(1, n + 1):\n        # Calculate the alternating sign term\n        alternating_sign = (-1)**(j + 1)\n\n        # Calculate the inner binomial coefficient (660 choose j)\n        inner_binomial_coefficient = math.comb(n, j)\n\n        # Calculate the denominator term\n        # The denominator is (660 choose 5) - ((660 - j) choose 5)\n        denominator = math.comb(n, k) - math.comb((n - j), k)\n        \n        # Calculate the term inside the summation\n        term = alternating_sign * (inner_binomial_coefficient / denominator)\n        \n        # Add to the sum\n        sum_terms += term\n    \n    # Calculate the final result by multiplying the outer binomial coefficient with the sum\n    final_result = outer_binomial_coefficient * sum_terms\n    \n    return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f"The result of the expression is: {result}")\n\n
\n","question_title":"Panini sticker python coding problem - bug in my code somewhere","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45250,"score":2}],"answers":[{"answer_html":"

Dear Lutz Lehmann and community,

\n

Thank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.

\n

For reference, here is the corresponding code.

\n
import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05  # Pipe radius (m)\nAcan = np.pi * Rcan ** 2  # Pipe cross-sectional area (m²)\nL = 10  # Pipe length (m)\nnx = 50  # Number of spatial points\ndx = L / nx  # Spatial step (m)\nT = 10*60  # Total simulation time (s)\nR = 8.31446261815324   # J/(mol·K)\nMair = 0.029  # Molar mass of air (kg/mol)\nPatm = 101325  # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text)  # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair  # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx  # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx  # Initial velocity\nT0 = [Text] * nx  # Initial temperature (K)\nPin0 = Patm  # Pression initiale (Pa)\nPin_des0 = Pin0  # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1  # Characteristic time of the compressor (s)\nKp = 4  # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75  # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n   # T en Kelvin\nmu0 = 1.716e-5  # viscosité à T0 (Pa·s)\nT0 = 273.15     # température de référence (K)\nC = 111         # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n    Qcomp_des = rho_0 * v_des * Acan  # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan  # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan  # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt  # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n    return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n    drhodx = [None] * nx\n    drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n        drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx)  # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n    dPdx = [None] * nx\n    dPdx[0] = (P[1] - P[0]) / (2 * dx)  # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n        dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx)  # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n    dvdx = [None] * nx\n    drhodt_0 = dPindt * Mair / (R * Text)\n    dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0]  # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n        dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx)  # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n    d2vdx2 = [None] * nx\n    drhodt_0 = dPindt * Mair / (R * Text)\n    d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n    for i in range(1, nx - 1):\n        d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n    return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n    drhodt = [None] * nx\n    drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n        drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0  # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n    dvdt = [None] * nx\n    for i in range(0, nx):\n        dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n    rho = y[:nx]\n    v = y[nx:2*nx]\n    P = rho * R * T / Mair  # Perfect gas law\n   P[0] = y[2*nx]\n    Pin_des = y[2*nx + 1]\n\n    dPindt = calculate_dPindt(P[0], Pin_des)\n\n    drhodx = calculate_drhodx(rho)\n    dPdx = calculate_dPdx(P)\n    dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n    d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n    drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n    dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n    dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n    return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label="Velocity (m/s) at pipe center")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity at the middle of the pipe (m/s)")\nplt.title("Velocity evolution at the middle of the pipe")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n    plt.plot(x, v_all[:, idx], label=f"t = {temps_selectionnes[i]:.1f} s")\nplt.xlabel("Position x (m)")\nplt.ylabel("Velocity (m/s)")\nplt.title("Velocity profile along the pipe at different times")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n
\n

Best regards,\nRaphaël

\n","answer_id":45250,"answer_text":"Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël","answer_url":"https://scicomp.stackexchange.com/a/45250","author":"Ev0Cation","author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-07T14:19:16+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45246,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-07T14:19:16+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C3CA863F-650C-4C2D-BD76-4C6863DC85E0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}],"score":2,"updated_at":"2025-10-07T14:19:16+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Ev0Cation","author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-07T14:19:16+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C3CA863F-650C-4C2D-BD76-4C6863DC85E0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45250"}],"question_author":"Ev0Cation","question_author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","post_id":"scicomp:45246","sha256":"8be5b8d21acaa3124f11278e9e1956344bcf0077a81fcffd51aa290ed3d02098","source_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation"},{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n","post_id":45250,"sha256":"e4c81797aebb0183f7ae202e8f40018f8a8f8af8534cea97bd44225f2587483d","source_url":"https://scicomp.stackexchange.com/a/45250"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"a8391bf268b878b5f0507e4b8ceaa7dd72acf2050e6871341b748edaa1f683f8","id":"SCT-6cdeb4f7cbdb46096754005c","language":["python"],"library_or_tool":["numpy","scipy"],"problem_text":"I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)","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":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-03T16:37:31+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"10D2B924-C266-46E3-844E-A857A83DB2A0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/10D2B924-C266-46E3-844E-A857A83DB2A0/view-source"}],"source_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":"45246","source_record_sha256":"d392eef5e8e0fbd252e6464ae9c2ab947aaba148870ac1dd4589cfc442431a56","source_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.

\n

I strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.

\n

Here is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.

\n

Could you please give me some guidance on how to solve this problem please?

\n

I will include my current code and figure below for reference.

\n
import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05  # Pipe radius (m)\nAcan = np.pi * Rcan ** 2  # Pipe cross-sectional area (m²)\nL = 1.0  # Pipe length (m)\nnx = 4  # Number of spatial points\ndx = L / (nx - 1)  # Spatial step (m)\nT = 30  # Total simulation time (s)\nR = 8.31446261815324   # J/(mol·K)\nMair = 0.029  # Molar mass of air (kg/mol)\nPatm = 101325  # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5  # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx  # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1)  # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n    drhodx = np.zeros_like(rho)\n    drhodx[0] = 0 # Neumann condition at inlet\n    for i in range(1, nx-1):\n        drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n    return drhodx\n\ndef calculate_dvdx(v):\n    dvdx = np.zeros_like(v)\n    for i in range(1, nx - 1):\n        dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n    dvdx[-1] = 0 # Neumann condition at outlet\n    return dvdx\n\ndef calculate_d2vdx2(v):\n    d2vdx2 = np.zeros_like(v)\n    for i in range(1, nx - 1):\n        d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n    d2vdx2[-1] = 0 # Neumann condition at outlet\n    return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n    drhodt = np.zeros_like(rho)\n    drhodt[-1] = 0 # Dirichlet condition at outlet\n    for i in range(0, nx - 1):\n        drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n    return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n    dvdt = np.zeros_like(v)\n    dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n    for i in range(1, nx):\n        dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n    return dvdt\n\n\ndef dydt(t, y):\n    rho = y[:nx]\n    v = y[nx:2*nx]\n\n    drhodx = calculate_drhodx(rho)\n    dPdx = drhodx * R * Text / Mair   # Perfect gas law + isotherm\n    dvdx = calculate_dvdx(v)\n    d2vdx2 = calculate_d2vdx2(v)\n\n    drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n    dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n    return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label="Velocity (m/s)")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity")\nplt.title("Velocity evolution")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n
\n

\"Results\"

\n","question_title":"Oscillations in 1D compressible Navier–Stokes simulation","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation","split":"holdout"} {"accepted_answer":null,"answer_scores":[{"answer_id":45279,"score":2}],"answers":[{"answer_html":"

The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.

\n

This builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.

\n","answer_id":45279,"answer_text":"The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.","answer_url":"https://scicomp.stackexchange.com/a/45279","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-11-11T08:18:46+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45261,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-11T08:18:46+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-11T08:58:34+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A797FC73-4FE4-442D-9FE9-D187BC73817D","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}],"score":2,"updated_at":"2025-11-11T08:58:34+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-11T08:18:46+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-11T08:58:34+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A797FC73-4FE4-442D-9FE9-D187BC73817D","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45279"}],"question_author":"Peter","question_author_url":"https://scicomp.stackexchange.com/users/46677/peter"},"code_blocks":[{"block_index":0,"code_text":"x_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n","post_id":"scicomp:45261","sha256":"3471081f6e65e7949efa1293170f808a6afcb2cb0f27ac5eca09596f2da1991d","source_url":"https://scicomp.stackexchange.com/questions/45261/numerical-simulation-of-path-integral"},{"block_index":1,"code_text":"#include \n#include \n#include \nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n for (int i = 0; i < size; ++i) {\n for (int j = 0; j < size; ++j) {\n B[i][j] = 0.0+I*0.0;\n for (int k = 0; k < size; ++k) {\n B[i][j] += A[i][k]*A[k][j];\n }\n B[i][j] *= pow(dx,n+1);\n }\n }\n printf(\"step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n\",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n complex A[size][size];\n complex B[size][size];\n double x_a = 0;\n double x_b = 0;\n for (int i = 0; i < size; ++i) {\n double xi = -xmax+i*dx;\n for (int j = 0; j < size; ++j) {\n double xj = -xmax+j*dx;\n A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n if (i == 0 && j == 6) {\n x_a = xi;\n x_b = xj;\n printf(\"x_a = %f, x_b = %f\\n\",xi,xj);\n }\n }\n }\n printf(\"step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n\",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n for (int n = 0; n < 4; ++n) {\n if (n % 2 == 0) {\n mult(A,B,x_a,x_b,n);\n }\n else {\n mult(B,A,x_a,x_b,n);\n }\n }\n}\n\n","post_id":"scicomp:45261","sha256":"857768ca40c2b8c1a30d0fb3519245f703c4dbfd89c3d8a42393df53c8c8cd58","source_url":"https://scicomp.stackexchange.com/questions/45261/numerical-simulation-of-path-integral"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"468c3936b940a399f0e5d1b0206222bc374c06c85f5aeabbb8e6eb4e0a60c684","id":"SCT-774ec80811d6c834ad76ec4e","language":null,"library_or_tool":null,"problem_text":"I'm trying to code the path integral simulation described in this (https://arxiv.org/pdf/quant-ph/9511042) article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?\n\n\n\n\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.\n\n\n\n\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:\n\n\n\n\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\n\n\n\n\nAs you can see the matrix elements match the propagator at first time step.\n\n\n\n\nHere i my code written in C.\n\n\n\n\n#include \n#include \n#include \nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n for (int i = 0; i < size; ++i) {\n for (int j = 0; j < size; ++j) {\n B[i][j] = 0.0+I*0.0;\n for (int k = 0; k < size; ++k) {\n B[i][j] += A[i][k]*A[k][j];\n }\n B[i][j] *= pow(dx,n+1);\n }\n }\n printf(\"step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n\",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n complex A[size][size];\n complex B[size][size];\n double x_a = 0;\n double x_b = 0;\n for (int i = 0; i < size; ++i) {\n double xi = -xmax+i*dx;\n for (int j = 0; j < size; ++j) {\n double xj = -xmax+j*dx;\n A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n if (i == 0 && j == 6) {\n x_a = xi;\n x_b = xj;\n printf(\"x_a = %f, x_b = %f\\n\",xi,xj);\n }\n }\n }\n printf(\"step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n\",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n for (int n = 0; n < 4; ++n) {\n if (n % 2 == 0) {\n mult(A,B,x_a,x_b,n);\n }\n else {\n mult(B,A,x_a,x_b,n);\n }\n }\n}","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":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-19T14:49:08+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"54865F0B-989C-4F21-904D-02A719DFFFD0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/54865F0B-989C-4F21-904D-02A719DFFFD0/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-20T08:52:16+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"67A32A94-305A-48EE-BA79-2352C97959DA","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/67A32A94-305A-48EE-BA79-2352C97959DA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-20T09:04:29+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"DDBCAF29-884A-4949-9491-3C984257EF1B","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DDBCAF29-884A-4949-9491-3C984257EF1B/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-23T14:08:40+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C150CBB9-BDB6-45C2-AE62-09839E780BEC","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C150CBB9-BDB6-45C2-AE62-09839E780BEC/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-23T14:14:22+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"FFA990B4-C708-43F7-BB23-618905B571BB","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FFA990B4-C708-43F7-BB23-618905B571BB/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-23T15:37:37+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C1701815-C382-4BDB-91C0-B801F612B091","revision_number":6,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C1701815-C382-4BDB-91C0-B801F612B091/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-10-26T13:36:05+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"161FF2F2-CB04-46D3-BA86-DF6443494F31","revision_number":7,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/161FF2F2-CB04-46D3-BA86-DF6443494F31/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Peter","profile_url":"https://scicomp.stackexchange.com/users/46677/peter","user_type":"registered"},"created_at":"2025-11-04T15:20:29+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"AAF4A896-26B2-4627-943A-DB9FB582A321","revision_number":8,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AAF4A896-26B2-4627-943A-DB9FB582A321/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":"45261","source_record_sha256":"f6985158efd75221f2940f1f333ad625b57ccf3ca921bcb4c4b54646c10e9c4d","source_url":"https://scicomp.stackexchange.com/questions/45261/numerical-simulation-of-path-integral","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I'm trying to code the path integral simulation described in this article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?

\n

In my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.

\n

Now, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:

\n
x_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n
\n

As you can see the matrix elements match the propagator at first time step.

\n

Here i my code written in C.

\n
#include <stdio.h>\n#include <complex.h>\n#include <math.h>\nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n    for (int i = 0; i < size; ++i) {\n        for (int j = 0; j < size; ++j) {\n            B[i][j] = 0.0+I*0.0;\n            for (int k = 0; k < size; ++k) {\n                B[i][j] += A[i][k]*A[k][j];\n            }\n            B[i][j] *= pow(dx,n+1);\n        }\n    }\n    printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n    complex A[size][size];\n    complex B[size][size];\n    double x_a = 0;\n    double x_b = 0;\n    for (int i = 0; i < size; ++i) {\n        double xi = -xmax+i*dx;\n        for (int j = 0; j < size; ++j) {\n            double xj = -xmax+j*dx;\n            A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n            if (i == 0 && j == 6) {\n                x_a = xi;\n                x_b = xj;\n                printf("x_a = %f, x_b = %f\\n",xi,xj);\n            }\n        }\n    }\n    printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n    for (int n = 0; n < 4; ++n) {\n        if (n % 2 == 0) {\n            mult(A,B,x_a,x_b,n);\n        }\n        else {\n            mult(B,A,x_a,x_b,n);\n        }\n    }\n}\n\n
\n","question_title":"Numerical Simulation of Path Integral","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45261/numerical-simulation-of-path-integral","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45264,"score":0},{"answer_id":45265,"score":1},{"answer_id":45266,"score":2}],"answers":[{"answer_html":"

The Dykstra Projection Algorithm is basically the ADMM Framework.
\nHence my idea is to use adaptive $\\rho$ parameter according to the different relative errors as in Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers in part 3.4.

\n","answer_id":45264,"answer_text":"The Dykstra Projection Algorithm (https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm) is basically the ADMM Framework.\n\nHence my idea is to use adaptive $\\rho$ parameter according to the different relative errors as in Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers (https://web.stanford.edu/%7Eboyd/papers/admm_distr_stats.html) in part 3.4.","answer_url":"https://scicomp.stackexchange.com/a/45264","author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-25T08:06:52+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":45263,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T08:06:52+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"CB7599F6-93BC-4F4B-AEE5-1088862B4D12","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/CB7599F6-93BC-4F4B-AEE5-1088862B4D12/view-source"}],"score":0,"updated_at":"2025-10-25T08:06:52+00:00"},{"answer_html":"

Assuming the matrix $\\boldsymbol{A}$ is dense:

\n
function SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T <: AbstractFloat}\n\n    numElements = length(vY);\n    vX = copy(vY);\n    vZ = zeros(T, numElements);\n    vP = zeros(T, numElements);\n    vQ = zeros(T, numElements);\n    vT = zeros(T, numElements);\n\n    sSvd = svd(mA);\n    mVV = sSvd.V * sSvd.Vt;\n    # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n    vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n    \n    for _ in 1:numIterations\n\n        vZ .= vX .+ vP;\n        # Project `vZ` onto the Linear Equality\n        mul!(vT, mVV, vZ);\n        # vZ .= vZ .- vT .+ vBB;\n        vZ .+= vBB .- vT;\n\n        vP .+= vX .- vZ;\n\n        vX .= vZ .+ vQ;\n        # Project `vX` onto the Box Constraints\n        vX .= clamp.(vX, vL, vU);\n        vQ .+= vZ .- vX;\n\n    end\n\n    return vX;\n\nend\n
\n

Remark: I'd be happy to see an efficient case of the Sparse case.

\n","answer_id":45265,"answer_text":"Assuming the matrix $\\boldsymbol{A}$ is dense:\n\n\n\n\nfunction SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T <: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n\n\n\n\n\nRemark: I'd be happy to see an efficient case of the Sparse case.","answer_url":"https://scicomp.stackexchange.com/a/45265","author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-25T12:41:28+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":45263,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T12:41:28+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"DEFDA34D-10C0-48A1-B4C0-85196E02AF64","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DEFDA34D-10C0-48A1-B4C0-85196E02AF64/view-source"}],"score":1,"updated_at":"2025-10-25T12:41:28+00:00"},{"answer_html":"

Read (if you're lucky, from your university's library)\nTrust Region Methods, Conn, Gould, and Toint [SIAM (2000)] and its associated implementation in scipy.optimize.minimize(method='trust-constr'). It will run for both the sparse and dense cases, though it may or may not be the most efficient approach in the dense case.

\n

Set:

\n
    \n
  • sparse_jacobian = True
  • \n
  • factorization_method = 'AugmentedSystem'
  • \n
  • Your jac and hess to functions where you provide the analytic Jacobian and Hessian of the cost function. Very simply, the Jacobian is $x - y$, and the Hessian is the (sparse) identity matrix.
  • \n
  • In the upper-level minimize interface, bounds by your $l$ and $u$
  • \n
  • constraints to a LinearConstraint by your $A$ and using a scipy sparse array
  • \n
  • x0 to a sensible initial estimate
  • \n
\n

In my testing, this converges to an optimality of $2.7 \\times 10^{-5}$ within 14 calls to the cost function for a problem size of 15x200 and density 15%.

\n

\"convergence\"

\n","answer_id":45266,"answer_text":"Read (if you're lucky, from your university's library)\nTrust Region Methods, Conn, Gould, and Toint [SIAM (2000)] (https://epubs.siam.org/doi/book/10.1137/1.9780898719857) and its associated implementation in scipy.optimize.minimize(method='trust-constr') (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html). It will run for both the sparse and dense cases, though it may or may not be the most efficient approach in the dense case.\n\n\n\n\nSet:\n\n\n\n\n\nsparse_jacobian = True\n\n\n\n\nfactorization_method = 'AugmentedSystem'\n\n\n\n\nYour jac and hess to functions where you provide the analytic Jacobian and Hessian of the cost function. Very simply, the Jacobian is $x - y$, and the Hessian is the (sparse) identity matrix.\n\n\n\n\nIn the upper-level minimize (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) interface, bounds by your $l$ and $u$\n\n\n\n\nconstraints to a LinearConstraint (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html) by your $A$ and using a scipy sparse array\n\n\n\n\nx0 to a sensible initial estimate\n\n\n\n\n\nIn my testing, this converges to an optimality of $2.7 \\times 10^{-5}$ within 14 calls to the cost function for a problem size of 15x200 and density 15%.\n\n\n\n\n[image: convergence; source: https://i.sstatic.net/YJ8UEXx7.png] (https://i.sstatic.net/YJ8UEXx7.png)","answer_url":"https://scicomp.stackexchange.com/a/45266","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-25T13:17:14+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":45263,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T13:17:14+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"77444703-E320-475F-B89E-303773BDEE64","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/77444703-E320-475F-B89E-303773BDEE64/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T19:40:38+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C04032E9-FCDC-40CF-857D-605E6541C00E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C04032E9-FCDC-40CF-857D-605E6541C00E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T19:54:56+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"09D74CCF-7C0C-4138-9B77-B959EBA73CBB","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/09D74CCF-7C0C-4138-9B77-B959EBA73CBB/view-source"}],"score":2,"updated_at":"2025-10-25T19:54:56+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T08:06:52+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"CB7599F6-93BC-4F4B-AEE5-1088862B4D12","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/CB7599F6-93BC-4F4B-AEE5-1088862B4D12/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45264"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T12:41:28+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"DEFDA34D-10C0-48A1-B4C0-85196E02AF64","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DEFDA34D-10C0-48A1-B4C0-85196E02AF64/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45265"},{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T13:17:14+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"77444703-E320-475F-B89E-303773BDEE64","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/77444703-E320-475F-B89E-303773BDEE64/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T19:40:38+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C04032E9-FCDC-40CF-857D-605E6541C00E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C04032E9-FCDC-40CF-857D-605E6541C00E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T19:54:56+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"09D74CCF-7C0C-4138-9B77-B959EBA73CBB","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/09D74CCF-7C0C-4138-9B77-B959EBA73CBB/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45266"}],"question_author":"Royi","question_author_url":"https://scicomp.stackexchange.com/users/7951/royi"},"code_blocks":[{"block_index":0,"code_text":"function SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T <: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n","post_id":45265,"sha256":"c49ef47f96ab84381961c2e6489a86e35d441ba6449536f790984a9a44cb1dd9","source_url":"https://scicomp.stackexchange.com/a/45265"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"2c6ebf38e138ce240e23a4814fe7244ece48507a09ffc93576c9682cc4deaf0a","id":"SCT-ebb508eddefb9188a2c2c2fa","language":["python","matlab","julia"],"library_or_tool":["matlab","julia"],"problem_text":"Solve the following problem:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A} \\boldsymbol{x} = \\boldsymbol{b} \\\\\n& \\quad & \\boldsymbol{x} \\leq \\boldsymbol{u} \\\\\n& \\quad & \\boldsymbol{x} \\geq \\boldsymbol{l} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$ with independent rows.\n\n\n\n\nI want to solve it for the cases:\n\n\n\n\n\nThe matrix $\\boldsymbol{A}$ is dense.\n\n\n\n\nThe matrix $\\boldsymbol{A}$ is sparse.\n\n\n\n\n\nIn most efficient way without using high level solvers.\n\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.\n\n\n\n\nCurrently my approach is to use Dykstra Projection Algorithm (https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm).\n\nI wonder if there are some acceleration tricks.","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":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T07:56:29+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"DF5239D1-D290-4E4D-8617-75F92FF57C54","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DF5239D1-D290-4E4D-8617-75F92FF57C54/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T08:26:46+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"2BF9CB7D-E76F-4860-A4F6-A56EC7531A4A","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2BF9CB7D-E76F-4860-A4F6-A56EC7531A4A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2025-10-25T13:00:20+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"2EBDE250-18A1-48AB-86D2-B3F738B95AF9","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2EBDE250-18A1-48AB-86D2-B3F738B95AF9/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-25T14:18:00+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A9C67614-2757-42FE-A099-DC88CD488EA4","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A9C67614-2757-42FE-A099-DC88CD488EA4/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2025-10-25T16:07:18+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"317E066A-AF61-43AC-9D80-48169DD78101","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/317E066A-AF61-43AC-9D80-48169DD78101/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":"45263","source_record_sha256":"7ac970d430c83a369ed3345c9d0d0a893f0d160038e180c11744e1d2944b306a","source_url":"https://scicomp.stackexchange.com/questions/45263/solve-projection-problem-with-linear-equality-and-box-constraints","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Solve the following problem:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A} \\boldsymbol{x} = \\boldsymbol{b} \\\\\n& \\quad & \\boldsymbol{x} \\leq \\boldsymbol{u} \\\\\n& \\quad & \\boldsymbol{x} \\geq \\boldsymbol{l} \\\\\n\\end{alignat*}\n$$

\n

Where $\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$ with independent rows.

\n

I want to solve it for the cases:

\n
    \n
  • The matrix $\\boldsymbol{A}$ is dense.
  • \n
  • The matrix $\\boldsymbol{A}$ is sparse.
  • \n
\n

In most efficient way without using high level solvers.
\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.

\n

Currently my approach is to use Dykstra Projection Algorithm.
\nI wonder if there are some acceleration tricks.

\n","question_title":"Solve Projection Problem with Linear Equality and Box Constraints","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45263/solve-projection-problem-with-linear-equality-and-box-constraints","split":"train"} {"accepted_answer":{"answer_html":"

In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.

\n

Here is the fixed code:

\n
def schur_hessenberg(a: Tensor, output: OutputType,\n                     num_iters: int) -> tuple[Tensor, Tensor]:\n    n = a.shape[0]\n\n    # Before: h, q = hessenberg(a)\n    h, q_hess = hessenberg(a)\n\n    z = ops.eye(n)\n    for m in range(n - 1, 0, -1):\n        for _ in range(num_iters):\n            sigma = h[m, m]\n            q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n            h = r @ q + sigma * ops.eye(n)\n            z = z @ q\n\n    if output == "complex" or str(a.dtype).startswith("complex"):\n        return ops.triu(h), q_hess @ z\n    else:\n        return quasi_triu(h), q_hess @ z\n
\n

I hope this implementation ends up being useful to someone else.

\n","answer_id":45271,"answer_text":"In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.\n\n\n\n\nHere is the fixed code:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\n\n\n\n\nI hope this implementation ends up being useful to someone else.","answer_url":"https://scicomp.stackexchange.com/a/45271","author":"DMDemon","author_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-29T14:17:07+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45269,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-29T14:17:07+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"6DF5DE67-1926-4793-AE81-11365490B04C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6DF5DE67-1926-4793-AE81-11365490B04C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-29T14:44:53+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"523EE8E6-85AA-4379-AC21-CD84C363A498","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/523EE8E6-85AA-4379-AC21-CD84C363A498/view-source"}],"score":2,"updated_at":"2025-10-29T14:44:53+00:00"},"answer_scores":[{"answer_id":45271,"score":2}],"answers":[{"answer_html":"

In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.

\n

Here is the fixed code:

\n
def schur_hessenberg(a: Tensor, output: OutputType,\n                     num_iters: int) -> tuple[Tensor, Tensor]:\n    n = a.shape[0]\n\n    # Before: h, q = hessenberg(a)\n    h, q_hess = hessenberg(a)\n\n    z = ops.eye(n)\n    for m in range(n - 1, 0, -1):\n        for _ in range(num_iters):\n            sigma = h[m, m]\n            q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n            h = r @ q + sigma * ops.eye(n)\n            z = z @ q\n\n    if output == "complex" or str(a.dtype).startswith("complex"):\n        return ops.triu(h), q_hess @ z\n    else:\n        return quasi_triu(h), q_hess @ z\n
\n

I hope this implementation ends up being useful to someone else.

\n","answer_id":45271,"answer_text":"In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.\n\n\n\n\nHere is the fixed code:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\n\n\n\n\nI hope this implementation ends up being useful to someone else.","answer_url":"https://scicomp.stackexchange.com/a/45271","author":"DMDemon","author_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-29T14:17:07+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45269,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-29T14:17:07+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"6DF5DE67-1926-4793-AE81-11365490B04C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6DF5DE67-1926-4793-AE81-11365490B04C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-29T14:44:53+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"523EE8E6-85AA-4379-AC21-CD84C363A498","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/523EE8E6-85AA-4379-AC21-CD84C363A498/view-source"}],"score":2,"updated_at":"2025-10-29T14:44:53+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"DMDemon","author_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-29T14:17:07+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"6DF5DE67-1926-4793-AE81-11365490B04C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6DF5DE67-1926-4793-AE81-11365490B04C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-29T14:44:53+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"523EE8E6-85AA-4379-AC21-CD84C363A498","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/523EE8E6-85AA-4379-AC21-CD84C363A498/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45271"}],"question_author":"DMDemon","question_author_url":"https://scicomp.stackexchange.com/users/55920/dmdemon"},"code_blocks":[{"block_index":0,"code_text":"from math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal[\"real\", \"complex\"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n mod_idxs = ops.stack([\n ops.arange(1, len(a), 2),\n ops.arange(1, len(a), 2) - 1\n ], axis=1)\n return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n while cnt < num_iters:\n a0, cnt = a1, cnt + 1\n q, r = ops.qr(a0)\n a1 = r @ q\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(a1), z\n else:\n return quasi_triu(a1), z\n","post_id":"scicomp:45269","sha256":"291468312e2229f4836baf338c916aee498dcdae95d01a6230f4c2d80ff4c8aa","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"},{"block_index":1,"code_text":"def hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n a = ops.convert_to_tensor(a)\n n = a.shape[0]\n u = ops.eye(n)\n\n for k in range(n - 2):\n aux_coeff = ops.where(\n a[k + 1, k] == 0,\n -1,\n a[k + 1, k] / ops.abs(a[k + 1, k])\n )\n\n w = ops.norm(\n a[k + 1:, k], 2\n ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n v_householder = ops.eye(\n n - (k + 1)\n ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n u_k = ops.slice_update(\n ops.eye(n, dtype=v_householder.dtype),\n (k + 1, k + 1),\n v_householder\n )\n\n a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n u = u @ u_k\n\n assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n return a, u\n","post_id":"scicomp:45269","sha256":"0bdcbf88c1c2d64d4086c0191fc71f52af820620bb0ca546cf33a2659b059f99","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"},{"block_index":2,"code_text":"def schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n h, q = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n))\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q @ z\n else:\n return quasi_triu(h), q @ z\n","post_id":"scicomp:45269","sha256":"3c453ecb8764caf83c0a5c66b6e147a8ccdb6e91faca3869f7a2b99b40480e2e","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"},{"block_index":3,"code_text":"test_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, \"real\", 100000)\nt1, z1 = schur(test_matrix, \"real\", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n","post_id":"scicomp:45269","sha256":"797aa53ef8db34d58cd42cb9469f4c1d5ec921c011caff56be4a075f234f49bf","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"},{"block_index":4,"code_text":"[[0.02052921 0.62834513 1.0401626 0.08546968 0.50802547]\n [1.2145011 0.47686994 0.14543009 0.77371585 0.44549757]\n [1.7762737 0.04462999 0.84596455 0.12113664 0.42194515]\n [0.6079759 0.8015515 0.0135076 0.07646421 0.00241762]\n [0.12112255 0.72910243 0.5631428 0.03763434 1.2257423 ]]\n\n[[6.2525272e-05 4.6223402e-05 5.9843063e-05 6.6056848e-05 1.8805265e-05]\n [2.8496981e-04 1.1801720e-05 1.1438131e-04 3.2186508e-06 2.9633939e-04]\n [8.8214874e-06 2.5629997e-05 1.8000603e-05 3.6358833e-05 2.2232533e-05]\n [1.5932322e-04 3.5166740e-05 2.1210406e-05 9.1180205e-05 1.7516315e-04]\n [2.7435273e-04 5.5968761e-05 3.5285950e-05 8.4638596e-06 1.6790628e-04]]\n","post_id":"scicomp:45269","sha256":"926d5f97f012243b6ee2cd5893006f0651be142ded4b145607ff9c7989d75877","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"},{"block_index":0,"code_text":"def schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n","post_id":45271,"sha256":"db75e4470031d50ac0978f0be16e45c7272de2bec10b784552cdc41c74d9ff97","source_url":"https://scicomp.stackexchange.com/a/45271"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"15cf8b3eb0212dfab5685ec20a35c33fff4fe2294345714b78c1770dbdd46c77","id":"SCT-e90c057c702bd6542fa368fc","language":null,"library_or_tool":["numpy","scipy"],"problem_text":"I am trying to implement the Complex and Real Schur Decompositions using only the Keras Ops API, so I can utilize it to impose some eigenvalue constraints on a weight matrix. I am also using the JAX backend, which further limits what I can actually do with the input matrix:\n\n\n\n\n\nAll operations are done using single-precision floating-point operations, and no in-place modifications are allowed.\n\n\n\n\nThe stopping criterion has to be static (e.g., an argument of the decomposition function, as I am currently doing) or a function of the input shape (similar to the max-iteration heuristic used by the LAPACK implementation (https://www.netlib.org/lapack/explore-html/d8/df4/group__lahqr_ga797fe3b28e02bea7dd5762dbaa28277e.html#ga797fe3b28e02bea7dd5762dbaa28277e)), as the execution graph is pre-compiled using a traced array.\n\n\n\nThis also means that conversion to a numpy ndarray is not allowed.\n\n\n\n\n\n\n\n\nI could, in theory, use JAX-specific functions, since the Keras tensors are just JAX arrays in disguise. However, I want to keep the code backend-agnostic if possible.\n\n\n\nIt is worth noting that JAX currently has a CPU-only implementation (https://docs.jax.dev/en/latest/_autosummary/jax.scipy.linalg.schur.html) of the Schur algorithm; however, my code requires GPU execution, so I cannot use it.\n\n\n\n\n\n\n\n\n\nWith that being said, I've already made some progress using these (https://people.inf.ethz.ch/arbenz/ewp/Lnotes/chapter4.pdf) lecture notes from ETH Zürich. More specifically, I got algorithm 4.1 (Basic QR algorithm) working (variable-naming conventions from Scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.schur.html)):\n\n\n\n\nfrom math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal[\"real\", \"complex\"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n mod_idxs = ops.stack([\n ops.arange(1, len(a), 2),\n ops.arange(1, len(a), 2) - 1\n ], axis=1)\n return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n while cnt < num_iters:\n a0, cnt = a1, cnt + 1\n q, r = ops.qr(a0)\n a1 = r @ q\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(a1), z\n else:\n return quasi_triu(a1), z\n\n\n\n\n\nHowever, as expected, the convergence rate is so low that I have to choose between preemptively setting an absurd number of iterations or risking instability due to non-convergence. Thus, I'm now trying to get algorithm 4.4 (Hessenberg QR algorithm with Rayleigh quotient shift) to work. So far, I have implemented the reduction to the Hessenberg matrix through Householder transformations following the theory in Wikipedia (https://en.wikipedia.org/wiki/Hessenberg_matrix#Householder_transformations), with some modifications to preserve compatibility with the Scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.hessenberg.html) version ($A = QHQ^*$ instead of $H = QAQ^*$):\n\n\n\n\ndef hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n a = ops.convert_to_tensor(a)\n n = a.shape[0]\n u = ops.eye(n)\n\n for k in range(n - 2):\n aux_coeff = ops.where(\n a[k + 1, k] == 0,\n -1,\n a[k + 1, k] / ops.abs(a[k + 1, k])\n )\n\n w = ops.norm(\n a[k + 1:, k], 2\n ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n v_householder = ops.eye(\n n - (k + 1)\n ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n u_k = ops.slice_update(\n ops.eye(n, dtype=v_householder.dtype),\n (k + 1, k + 1),\n v_householder\n )\n\n a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n u = u @ u_k\n\n assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n return a, u\n\n\n\n\n\nHowever, I haven't been able to get the actual algorithm working. So far, I have the following function:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n h, q = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n))\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q @ z\n else:\n return quasi_triu(h), q @ z\n\n\n\n\n\nHowever, when I test both methods using a random real matrix (similar results for the complex case) and measure the matrix reconstruction absolute error as\n\n\n\n\ntest_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, \"real\", 100000)\nt1, z1 = schur(test_matrix, \"real\", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n\n\n\n\n\nI get the following results:\n\n\n\n\n[[0.02052921 0.62834513 1.0401626 0.08546968 0.50802547]\n [1.2145011 0.47686994 0.14543009 0.77371585 0.44549757]\n [1.7762737 0.04462999 0.84596455 0.12113664 0.42194515]\n [0.6079759 0.8015515 0.0135076 0.07646421 0.00241762]\n [0.12112255 0.72910243 0.5631428 0.03763434 1.2257423 ]]\n\n[[6.2525272e-05 4.6223402e-05 5.9843063e-05 6.6056848e-05 1.8805265e-05]\n [2.8496981e-04 1.1801720e-05 1.1438131e-04 3.2186508e-06 2.9633939e-04]\n [8.8214874e-06 2.5629997e-05 1.8000603e-05 3.6358833e-05 2.2232533e-05]\n [1.5932322e-04 3.5166740e-05 2.1210406e-05 9.1180205e-05 1.7516315e-04]\n [2.7435273e-04 5.5968761e-05 3.5285950e-05 8.4638596e-06 1.6790628e-04]]\n\n\n\n\n\nClearly, the decomposition is not properly implemented. I already checked the Hessenberg decomposition reconstruction error and, numerical precision aside, it seems to be working. Furthermore, the $H$ matrix generated by the Hessenberg QR iterations seems to be (at least) quasi-upper triangular. Thus, I have either a) incorrectly implemented the Hessenberg QR iterations, or b) failed to properly combine the Hessenberg and Schur factors.\n\n\n\n\nI've already gone over the code and reference material several times, but I cannot spot where I'm screwing up, so I'd really appreciate any pointers.","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":"DMDemon","profile_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","user_type":"registered"},"created_at":"2025-10-28T18:12:37+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"28BA02D1-48B0-4A5E-B0C4-2D9EB5079696","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/28BA02D1-48B0-4A5E-B0C4-2D9EB5079696/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":"45269","source_record_sha256":"72dc1b9fb7db0f3773ad7ec57d3a6764c05f40ca925ffbc3444fde903f3aa1c6","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am trying to implement the Complex and Real Schur Decompositions using only the Keras Ops API, so I can utilize it to impose some eigenvalue constraints on a weight matrix. I am also using the JAX backend, which further limits what I can actually do with the input matrix:

\n
    \n
  1. All operations are done using single-precision floating-point operations, and no in-place modifications are allowed.
  2. \n
  3. The stopping criterion has to be static (e.g., an argument of the decomposition function, as I am currently doing) or a function of the input shape (similar to the max-iteration heuristic used by the LAPACK implementation), as the execution graph is pre-compiled using a traced array.\n
      \n
    • This also means that conversion to a numpy ndarray is not allowed.
    • \n
    \n
  4. \n
  5. I could, in theory, use JAX-specific functions, since the Keras tensors are just JAX arrays in disguise. However, I want to keep the code backend-agnostic if possible.\n
      \n
    • It is worth noting that JAX currently has a CPU-only implementation of the Schur algorithm; however, my code requires GPU execution, so I cannot use it.
    • \n
    \n
  6. \n
\n

With that being said, I've already made some progress using these lecture notes from ETH Zürich. More specifically, I got algorithm 4.1 (Basic QR algorithm) working (variable-naming conventions from Scipy):

\n
from math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal["real", "complex"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n    mod_idxs = ops.stack([\n        ops.arange(1, len(a), 2),\n        ops.arange(1, len(a), 2) - 1\n    ], axis=1)\n    return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n          num_iters: int) -> tuple[Tensor, Tensor]:\n    a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n    while cnt < num_iters:\n        a0, cnt = a1, cnt + 1\n        q, r = ops.qr(a0)\n        a1 = r @ q\n        z = z @ q\n\n    if output == "complex" or str(a.dtype).startswith("complex"):\n        return ops.triu(a1), z\n    else:\n        return quasi_triu(a1), z\n
\n

However, as expected, the convergence rate is so low that I have to choose between preemptively setting an absurd number of iterations or risking instability due to non-convergence. Thus, I'm now trying to get algorithm 4.4 (Hessenberg QR algorithm with Rayleigh quotient shift) to work. So far, I have implemented the reduction to the Hessenberg matrix through Householder transformations following the theory in Wikipedia, with some modifications to preserve compatibility with the Scipy version ($A = QHQ^*$ instead of $H = QAQ^*$):

\n
def hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n    a = ops.convert_to_tensor(a)\n    n = a.shape[0]\n    u = ops.eye(n)\n\n    for k in range(n - 2):\n        aux_coeff = ops.where(\n            a[k + 1, k] == 0,\n            -1,\n            a[k + 1, k] / ops.abs(a[k + 1, k])\n        )\n\n        w = ops.norm(\n            a[k + 1:, k], 2\n        ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n        v_householder = ops.eye(\n            n - (k + 1)\n        ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n        u_k = ops.slice_update(\n            ops.eye(n, dtype=v_householder.dtype),\n            (k + 1, k + 1),\n            v_householder\n        )\n\n        a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n        u = u @ u_k\n\n    assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n    return a, u\n
\n

However, I haven't been able to get the actual algorithm working. So far, I have the following function:

\n
def schur_hessenberg(a: Tensor, output: OutputType,\n                   num_iters: int) -> tuple[Tensor, Tensor]:\n    n = a.shape[0]\n\n    h, q = hessenberg(a)\n\n    z = ops.eye(n)\n    for m in range(n - 1, 0, -1):\n        for _ in range(num_iters):\n            sigma = h[m, m]\n            q, r = ops.qr(h - sigma * ops.eye(n))\n            h = r @ q + sigma * ops.eye(n)\n            z = z @ q\n\n    if output == "complex" or str(a.dtype).startswith("complex"):\n        return ops.triu(h), q @ z\n    else:\n        return quasi_triu(h), q @ z\n
\n

However, when I test both methods using a random real matrix (similar results for the complex case) and measure the matrix reconstruction absolute error as

\n
test_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, "real", 100000)\nt1, z1 = schur(test_matrix, "real", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n
\n

I get the following results:

\n
[[0.02052921 0.62834513 1.0401626  0.08546968 0.50802547]\n [1.2145011  0.47686994 0.14543009 0.77371585 0.44549757]\n [1.7762737  0.04462999 0.84596455 0.12113664 0.42194515]\n [0.6079759  0.8015515  0.0135076  0.07646421 0.00241762]\n [0.12112255 0.72910243 0.5631428  0.03763434 1.2257423 ]]\n\n[[6.2525272e-05 4.6223402e-05 5.9843063e-05 6.6056848e-05 1.8805265e-05]\n [2.8496981e-04 1.1801720e-05 1.1438131e-04 3.2186508e-06 2.9633939e-04]\n [8.8214874e-06 2.5629997e-05 1.8000603e-05 3.6358833e-05 2.2232533e-05]\n [1.5932322e-04 3.5166740e-05 2.1210406e-05 9.1180205e-05 1.7516315e-04]\n [2.7435273e-04 5.5968761e-05 3.5285950e-05 8.4638596e-06 1.6790628e-04]]\n
\n

Clearly, the decomposition is not properly implemented. I already checked the Hessenberg decomposition reconstruction error and, numerical precision aside, it seems to be working. Furthermore, the $H$ matrix generated by the Hessenberg QR iterations seems to be (at least) quasi-upper triangular. Thus, I have either a) incorrectly implemented the Hessenberg QR iterations, or b) failed to properly combine the Hessenberg and Schur factors.

\n

I've already gone over the code and reference material several times, but I cannot spot where I'm screwing up, so I'd really appreciate any pointers.

\n","question_title":"Help implementing the Hessenberg QR algorithm using the Keras Ops API","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45293,"score":4},{"answer_id":45294,"score":2},{"answer_id":45295,"score":7}],"answers":[{"answer_html":"

An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.

\n

However, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.

\n

The issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.

\n

However, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.

\n

With FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.

\n","answer_id":45293,"answer_text":"An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.\n\n\n\n\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.\n\n\n\n\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.\n\n\n\n\nHowever, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.\n\n\n\n\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.","answer_url":"https://scicomp.stackexchange.com/a/45293","author":"njuffa","author_url":"https://scicomp.stackexchange.com/users/20458/njuffa","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-11-26T23:33:21+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45291,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"njuffa","profile_url":"https://scicomp.stackexchange.com/users/20458/njuffa","user_type":"registered"},"created_at":"2025-11-26T23:33:21+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"B6ACA9A9-61E5-4827-8876-77505A1EE621","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B6ACA9A9-61E5-4827-8876-77505A1EE621/view-source"}],"score":4,"updated_at":"2025-11-26T23:33:21+00:00"},{"answer_html":"

One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.

\n

That way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.

\n

\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}

\n

Note that the expansion looses precision the further away you are from 0.

\n","answer_id":45294,"answer_text":"One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.\n\n\n\n\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.\n\n\n\n\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}\n\n\n\n\nNote that the expansion looses precision the further away you are from 0.","answer_url":"https://scicomp.stackexchange.com/a/45294","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-11-27T07:31:18+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45291,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-27T07:31:18+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"968C67F8-16E6-40D8-80A4-8E5335D3FC2C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/968C67F8-16E6-40D8-80A4-8E5335D3FC2C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-27T07:36:23+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"1885B799-B6E4-4653-BEFB-37E50B86F7E6","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/1885B799-B6E4-4653-BEFB-37E50B86F7E6/view-source"}],"score":2,"updated_at":"2025-11-27T07:36:23+00:00"},{"answer_html":"

Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$

\n

We can use the Chebyshev polynomial of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$

\n

Plugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$

\n

Therefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$

\n

and

\n

$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$

\n

Therefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$

\n

where $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$

\n

So instead of computing $\\sin(k x_n)$ for every $k$, we can:

\n
    \n
  • Compute $s = \\sin(x_n)$ once,
  • \n
  • Compute $c = \\cos(x_n)$ once,
  • \n
  • Evaluate the polynomial $P_m(c)$.
  • \n
\n

Example

\n

We start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$

\n

Thus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$

\n

Simplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$

\n

Now collect like powers of $t$.

\n

$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$

\n

$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$

\n

$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$

\n

$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$

\n

Constant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$

\n

So we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$

\n

Factoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$

\n

Test Case

\n

For $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$

\n
from mpmath import mp\nimport time\n\nmp.dps = 1000  # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n    """\n    m = 5 iteration:\n        x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n    where\n        P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n    """\n    s = mp.sin(x)\n    c = mp.cos(x)\n    P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n    return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4):  # a few iterations are enough because order = 11\n    x = step_m5(x)\nend = time.perf_counter()\n\nprint("Approximate pi (m=5):")\nprint(mp.nstr(x, 1000))\nprint(f"\\nTime Taken: {end - start:.6f} seconds")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint("\\nError x - pi:")\nprint(mp.nstr(err, 5))\n
\n
\n

Approximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199

\n

Time Taken: 0.001180 seconds

\n

Error x - pi:\n0.0

\n","answer_id":45295,"answer_text":"Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$\n\n\n\n\nWe can use the Chebyshev polynomial (https://en.wikipedia.org/wiki/Chebyshev_polynomials) of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$\n\n\n\n\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$\n\n\n\n\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$\n\n\n\n\nand\n\n\n\n\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$\n\n\n\n\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:\n\n\n\n\n\nCompute $s = \\sin(x_n)$ once,\n\n\n\n\nCompute $c = \\cos(x_n)$ once,\n\n\n\n\nEvaluate the polynomial $P_m(c)$.\n\n\n\n\n\nExample\n\n\n\n\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$\n\n\n\n\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$\n\n\n\n\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$\n\n\n\n\nNow collect like powers of $t$.\n\n\n\n\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$\n\n\n\n\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$\n\n\n\n\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$\n\n\n\n\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$\n\n\n\n\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$\n\n\n\n\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$\n\n\n\n\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$\n\n\n\n\nTest Case\n\n\n\n\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n\n\n\n\n\n\n\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199\n\n\n\n\nTime Taken: 0.001180 seconds\n\n\n\n\nError x - pi:\n0.0","answer_url":"https://scicomp.stackexchange.com/a/45295","author":"vengy","author_url":"https://scicomp.stackexchange.com/users/56070/vengy","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-11-27T16:01:03+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45291,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-27T16:01:03+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"12F528C5-3339-4BD9-82C4-1F98C0E30ABD","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F528C5-3339-4BD9-82C4-1F98C0E30ABD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-27T16:46:02+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"94F6BA8F-8639-48FE-844B-374EC8092EC7","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/94F6BA8F-8639-48FE-844B-374EC8092EC7/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-27T17:19:25+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C72508F8-E2C5-4479-B135-70BE30A2F07C","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C72508F8-E2C5-4479-B135-70BE30A2F07C/view-source"}],"score":7,"updated_at":"2025-11-27T17:19:25+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"njuffa","author_url":"https://scicomp.stackexchange.com/users/20458/njuffa","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"njuffa","profile_url":"https://scicomp.stackexchange.com/users/20458/njuffa","user_type":"registered"},"created_at":"2025-11-26T23:33:21+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"B6ACA9A9-61E5-4827-8876-77505A1EE621","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B6ACA9A9-61E5-4827-8876-77505A1EE621/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45293"},{"author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-27T07:31:18+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"968C67F8-16E6-40D8-80A4-8E5335D3FC2C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/968C67F8-16E6-40D8-80A4-8E5335D3FC2C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-27T07:36:23+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"1885B799-B6E4-4653-BEFB-37E50B86F7E6","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/1885B799-B6E4-4653-BEFB-37E50B86F7E6/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45294"},{"author":"vengy","author_url":"https://scicomp.stackexchange.com/users/56070/vengy","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-27T16:01:03+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"12F528C5-3339-4BD9-82C4-1F98C0E30ABD","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F528C5-3339-4BD9-82C4-1F98C0E30ABD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-27T16:46:02+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"94F6BA8F-8639-48FE-844B-374EC8092EC7","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/94F6BA8F-8639-48FE-844B-374EC8092EC7/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-27T17:19:25+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C72508F8-E2C5-4479-B135-70BE30A2F07C","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C72508F8-E2C5-4479-B135-70BE30A2F07C/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45295"}],"question_author":"vengy","question_author_url":"https://scicomp.stackexchange.com/users/56070/vengy"},"code_blocks":[{"block_index":0,"code_text":"from mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n","post_id":"scicomp:45291","sha256":"986e2bb7e76ea41218a3f1e6b7c67a6ca5385c0dc9eb4b9bb4c49ee3fe19b82d","source_url":"https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms"},{"block_index":0,"code_text":"from mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n","post_id":45295,"sha256":"b2c96936281d10430ccaf43e37df226edf2465e0445a080363a43be285aeda8c","source_url":"https://scicomp.stackexchange.com/a/45295"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"8ebc87fc80ab0256e887e3b030a8fc47704fa114b6e7b1c8ac8af70b3bea033b","id":"SCT-b75755f0787a79526b6ec835","language":null,"library_or_tool":null,"problem_text":"I have this recurrence formula for $\\pi$ with convergence order $2m+1$:\n\n\n\n\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$\n\n\n\n\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$\n\n\n\n\nAfter four iterations, $\\pi$ is accurate to $761$ digits:\n\n\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n\n\n\n\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.\n\n\n\n\nQuestion\n\n\n\n\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?\n\n\n\n\nUpdate\n\n\n\n\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:\n\n\n\n\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$\n\n\n\n\nThanks!","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":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-26T20:12:50+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"E62E0A8C-8E01-4C14-B7C2-285A89EF1CC1","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E62E0A8C-8E01-4C14-B7C2-285A89EF1CC1/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vengy","profile_url":"https://scicomp.stackexchange.com/users/56070/vengy","user_type":"registered"},"created_at":"2025-11-28T14:23:44+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"38B727A1-9571-4258-B34C-572EA2A4CA69","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/38B727A1-9571-4258-B34C-572EA2A4CA69/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-27T13:30:00+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"26017B5A-7A85-4984-8B51-2083CED200D4","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/26017B5A-7A85-4984-8B51-2083CED200D4/view-source"}],"source_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":"45291","source_record_sha256":"1606edd6df81cc0540a4c2920be4c072c45f5fbe30eced982b6b0eb03002de6e","source_url":"https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have this recurrence formula for $\\pi$ with convergence order $2m+1$:

\n

$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$

\n

For example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$

\n

After four iterations, $\\pi$ is accurate to $761$ digits:

\n

3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131

\n
from mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n    return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n    x = step_m2(x)\nend = time.perf_counter()\n\nprint("Approximate pi:", mp.nstr(x, 1000))\nprint(f"Time Taken: {end - start:.6f} seconds")\n
\n

However, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.

\n

Question

\n

Are there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?

\n

Update

\n

Based on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:

\n

$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$

\n

Thanks!

\n","question_title":"Efficient computation of $\\sin(k x_n)$ in iterative algorithms","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45353,"score":-1}],"answers":[{"answer_html":"

Actually, I turned to vasp later and I found it more simple to get good wannier functions via the SCDM method.\"enter

\n","answer_id":45353,"answer_text":"Actually, I turned to vasp later and I found it more simple to get good wannier functions via the SCDM method.[image: enter image description here; source: https://i.sstatic.net/4ajnfKiL.png] (https://i.sstatic.net/4ajnfKiL.png)","answer_url":"https://scicomp.stackexchange.com/a/45353","author":"user","author_url":"https://scicomp.stackexchange.com/users/56092/user","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-27T16:22:51+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":45300,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"user","profile_url":"https://scicomp.stackexchange.com/users/56092/user","user_type":"registered"},"created_at":"2026-01-27T16:22:51+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"FE733163-7CAA-4C1E-BB4C-A96B2C822461","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FE733163-7CAA-4C1E-BB4C-A96B2C822461/view-source"}],"score":-1,"updated_at":"2026-01-27T16:22:51+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"user","author_url":"https://scicomp.stackexchange.com/users/56092/user","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"user","profile_url":"https://scicomp.stackexchange.com/users/56092/user","user_type":"registered"},"created_at":"2026-01-27T16:22:51+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"FE733163-7CAA-4C1E-BB4C-A96B2C822461","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FE733163-7CAA-4C1E-BB4C-A96B2C822461/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45353"}],"question_author":"user","question_author_url":"https://scicomp.stackexchange.com/users/56092/user"},"code_blocks":[{"block_index":0,"code_text":"num_wann = 52 \nnum_bands = 92 \n\nwrite_hr = true\nwrite_rmn = true\nwrite_tb = true\n\nfermi_energy = 12.1450\n\ndis_num_iter = 150\n\ndis_win_min = 5.3 \ndis_win_max = 15.3 \ndis_froz_max = 13.3 \ndis_froz_min= 5.3 \n\nspinors = .true. \nwrite_xyz = .true. \n!restart = plot \nbands_plot = true \n\nbegin projections\nMnA: d\nMnB: d \nCu: d\nAs: p\nend projections\n\nbegin kpoint_path\nG 0.0000 0.0000 0.0000 Y 0.5000 0.0000 0.0000\nY 0.5000 0.0000 0.0000 M 0.5000 0.5000 0.0000\nM 0.5000 0.5000 0.0000 G 0.0000 0.0000 0.0000\nG 0.0000 0.0000 0.0000 Z 0.0000 0.0000 0.5000\nZ 0.0000 0.0000 0.5000 R 0.5000 0.0000 0.5000\nR 0.5000 0.0000 0.5000 A 0.5000 0.5000 0.5000\nA 0.5000 0.5000 0.5000 Z 0.0000 0.0000 0.5000\nend kpoint_path\n\nbegin unit_cell_cart\nangstrom\n 3.6994910000 0.0000000000 0.0000000000\n 0.0000000000 3.6994910000 0.0000000000\n 0.0000000000 0.0000000000 6.4084220000\nend unit_cell_cart\n\nbegin atoms_frac\n MnA 0.0000000000 0.5000000000 0.1640200000\n MnB 0.5000000000 0.0000000000 0.8359800000\n As 0.5000000000 0.0000000000 0.2237540000\n Cu 0.0000000000 0.0000000000 0.5000000000\n Cu 0.5000000000 0.5000000000 0.5000000000\n As 0.0000000000 0.5000000000 0.7762460000\nend atoms_frac\n\nmp_grid = 12 12 8\n\nbegin kpoints\n 0.00000000 0.00000000 0.00000000 8.680556e-04\n 0.00000000 0.00000000 0.12500000 8.680556e-04\n 0.00000000 0.00000000 0.25000000 8.680556e-04\n","post_id":"scicomp:45300","sha256":"bfa4804e776be29bca5842210cd8392158440467e25159b03488c12d18709439","source_url":"https://scicomp.stackexchange.com/questions/45300/why-does-wannier90-often-fail-to-produce-good-mlwfs-for-this-metallic-system-an"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"d8049548c72290b578787d0f68178f4ca4c0068fb432cc2297faf64aca671377","id":"SCT-8ad9ef21562a390339f53103","language":null,"library_or_tool":null,"problem_text":"I am working on constructing maximally localized Wannier functions (MLWFs) for a metallic system CuMnAs using Wannier90, but the fitting quality is significantly worse than in insulating cases. The disentanglement step shows unstable convergence, the spreads oscillate, and the interpolated bands deviate from the DFT bands—especially near the Fermi level, where multiple bands cross.\n\n\n\n\nI suspect this may be related to the choice of projection orbitals, inner/outer disentanglement windows, or an insufficient k-point mesh. However, even after adjusting these parameters, the Wannierization still fails to produce a smooth and well-localized subspace.\n\n\n\n\nHere is win input:\n\n\n\n\nnum_wann = 52 \nnum_bands = 92 \n\nwrite_hr = true\nwrite_rmn = true\nwrite_tb = true\n\nfermi_energy = 12.1450\n\ndis_num_iter = 150\n\ndis_win_min = 5.3 \ndis_win_max = 15.3 \ndis_froz_max = 13.3 \ndis_froz_min= 5.3 \n\nspinors = .true. \nwrite_xyz = .true. \n!restart = plot \nbands_plot = true \n\nbegin projections\nMnA: d\nMnB: d \nCu: d\nAs: p\nend projections\n\nbegin kpoint_path\nG 0.0000 0.0000 0.0000 Y 0.5000 0.0000 0.0000\nY 0.5000 0.0000 0.0000 M 0.5000 0.5000 0.0000\nM 0.5000 0.5000 0.0000 G 0.0000 0.0000 0.0000\nG 0.0000 0.0000 0.0000 Z 0.0000 0.0000 0.5000\nZ 0.0000 0.0000 0.5000 R 0.5000 0.0000 0.5000\nR 0.5000 0.0000 0.5000 A 0.5000 0.5000 0.5000\nA 0.5000 0.5000 0.5000 Z 0.0000 0.0000 0.5000\nend kpoint_path\n\nbegin unit_cell_cart\nangstrom\n 3.6994910000 0.0000000000 0.0000000000\n 0.0000000000 3.6994910000 0.0000000000\n 0.0000000000 0.0000000000 6.4084220000\nend unit_cell_cart\n\nbegin atoms_frac\n MnA 0.0000000000 0.5000000000 0.1640200000\n MnB 0.5000000000 0.0000000000 0.8359800000\n As 0.5000000000 0.0000000000 0.2237540000\n Cu 0.0000000000 0.0000000000 0.5000000000\n Cu 0.5000000000 0.5000000000 0.5000000000\n As 0.0000000000 0.5000000000 0.7762460000\nend atoms_frac\n\nmp_grid = 12 12 8\n\nbegin kpoints\n 0.00000000 0.00000000 0.00000000 8.680556e-04\n 0.00000000 0.00000000 0.12500000 8.680556e-04\n 0.00000000 0.00000000 0.25000000 8.680556e-04\n\n\n\n\n\nHere are the fatbands:\n\n\n\n\n\n\n\n\n\nIndex\nOrbital\nWeight\nEnergy_min\nEnergy_max\n\n\n\n\n\n\n\n\n\t1\n\tMnB-s\n\t9.881649e-01\n\t-66.668270\n\t-66.667510\n\n\n\n\n\n\n\t2\n\tMnB-s\n\t9.879660e-01\n\t-66.668270\n\t-66.667510\n\n\n\n\n\n\n\t3\n\tMnA-s\n\t9.868490e-01\n\t-66.666030\n\t-66.665820\n\n\n\n\n\n\n\t4\n\tMnA-s\n\t9.867413e-01\n\t-66.666030\n\t-66.665820\n\n\n\n\n\n\n\t5\n\tMnB-p\n\t8.400973e-01\n\t-36.325620\n\t-36.323540\n\n\n\n\n\n\n\t6\n\tMnB-p\n\t8.317571e-01\n\t-36.325620\n\t-36.323540\n\n\n\n\n\n\n\t7\n\tMnA-p\n\t8.318057e-01\n\t-36.323460\n\t-36.317360\n\n\n\n\n\n\n\t8\n\tMnA-p\n\t8.401787e-01\n\t-36.323460\n\t-36.317360\n\n\n\n\n\n\n\t9\n\tMnB-p\n\t8.161489e-01\n\t-35.099230\n\t-35.097040\n\n\n\n\n\n\n\t10\n\tMnB-p\n\t8.040838e-01\n\t-35.099220\n\t-35.097020\n\n\n\n\n\n\n\t11\n\tMnA-p\n\t8.036925e-01\n\t-35.098130\n\t-35.089650\n\n\n\n\n\n\n\t12\n\tMnA-p\n\t8.164002e-01\n\t-35.098110\n\t-35.089650\n\n\n\n\n\n\n\t13\n\tMnB-p\n\t8.358367e-01\n\t-35.036260\n\t-35.031930\n\n\n\n\n\n\n\t14\n\tMnB-p\n\t8.179446e-01\n\t-35.036260\n\t-35.031850\n\n\n\n\n\n\n\t15\n\tMnA-p\n\t8.182119e-01\n\t-35.030990\n\t-35.025720\n\n\n\n\n\n\n\t16\n\tMnA-p\n\t8.356700e-01\n\t-35.030900\n\t-35.025720\n\n\n\n\n\n\n\t17\n\tAs-s\n\t8.392833e-01\n\t-0.831000\n\t1.316030\n\n\n\n\n\n\n\t18\n\tAs-s\n\t8.338588e-01\n\t-0.831000\n\t1.316030\n\n\n\n\n\n\n\t19\n\tAs-s\n\t9.058134e-01\n\t-0.209240\n\t1.324800\n\n\n\n\n\n\n\t20\n\tAs-s\n\t9.062729e-01\n\t-0.209240\n\t1.324800\n\n\n\n\n\n\n\t21\n\tAs-p\n\t6.143355e-01\n\t5.342380\n\t6.637930\n\n\n\n\n\n\n\t22\n\tAs-p\n\t6.134158e-01\n\t5.342380\n\t6.638240\n\n\n\n\n\n\n\t23\n\tAs-p\n\t5.129997e-01\n\t5.401290\n\t7.767510\n\n\n\n\n\n\n\t24\n\tAs-p\n\t5.125643e-01\n\t5.401290\n\t7.768130\n\n\n\n\n\n\n\t25\n\tAs-p\n\t4.726773e-01\n\t6.626010\n\t8.053720\n\n\n\n\n\n\n\t26\n\tAs-p\n\t4.721743e-01\n\t6.626520\n\t8.053720\n\n\n\n\n\n\n\t27\n\tCu-d\n\t4.986890e-01\n\t7.390900\n\t8.116920\n\n\n\n\n\n\n\t28\n\tCu-d\n\t4.998003e-01\n\t7.390900\n\t8.116970\n\n\n\n\n\n\n\t29\n\tCu-d\n\t6.113203e-01\n\t7.854560\n\t8.416970\n\n\n\n\n\n\n\t30\n\tCu-d\n\t6.121870e-01\n\t7.854630\n\t8.417060\n\n\n\n\n\n\n\t31\n\tCu-d\n\t6.305895e-01\n\t8.095260\n\t9.091470\n\n\n\n\n\n\n\t32\n\tCu-d\n\t6.304399e-01\n\t8.096400\n\t9.091470\n\n\n\n\n\n\n\t33\n\tCu-d\n\t9.469474e-01\n\t8.514170\n\t9.141630\n\n\n\n\n\n\n\t34\n\tCu-d\n\t9.472102e-01\n\t8.514250\n\t9.141630\n\n\n\n\n\n\n\t35\n\tCu-d\n\t8.649751e-01\n\t8.578920\n\t9.369690\n\n\n\n\n\n\n\t36\n\tCu-d\n\t8.651089e-01\n\t8.578920\n\t9.369690\n\n\n\n\n\n\n\t37\n\tCu-d\n\t8.952000e-01\n\t8.690770\n\t9.548950\n\n\n\n\n\n\n\t38\n\tCu-d\n\t8.955303e-01\n\t8.690900\n\t9.549270\n\n\n\n\n\n\n\t39\n\tCu-d\n\t8.297525e-01\n\t8.696380\n\t9.812650\n\n\n\n\n\n\n\t40\n\tCu-d\n\t8.296666e-01\n\t8.696380\n\t9.812870\n\n\n\n\n\n\n\t41\n\tCu-d\n\t9.651834e-01\n\t9.459160\n\t10.066180\n\n\n\n\n\n\n\t42\n\tCu-d\n\t9.651335e-01\n\t9.459450\n\t10.066180\n\n\n\n\n\n\n\t43\n\tCu-d\n\t7.823033e-01\n\t9.462930\n\t10.346490\n\n\n\n\n\n\n\t44\n\tCu-d\n\t7.823292e-01\n\t9.462930\n\t10.346490\n\n\n\n\n\n\n\t45\n\tCu-d\n\t6.928074e-01\n\t9.652790\n\t10.470370\n\n\n\n\n\n\n\t46\n\tCu-d\n\t6.929086e-01\n\t9.653110\n\t10.470370\n\n\n\n\n\n\n\t47\n\tCu-d\n\t7.334994e-01\n\t9.653590\n\t10.643890\n\n\n\n\n\n\n\t48\n\tCu-d\n\t7.336775e-01\n\t9.653590\n\t10.644060\n\n\n\n\n\n\n\t49\n\tCu-d\n\t4.933639e-01\n\t9.910510\n\t10.936240\n\n\n\n\n\n\n\t50\n\tCu-d\n\t4.946027e-01\n\t9.910660\n\t10.936620\n\n\n\n\n\n\n\t51\n\tCu-d\n\t3.412474e-01\n\t9.921660\n\t11.233320\n\n\n\n\n\n\n\t52\n\tMnB-d\n\t3.405554e-01\n\t9.921660\n\t11.233320\n\n\n\n\n\n\n\t53\n\tMnB-d\n\t4.567662e-01\n\t10.756070\n\t11.584470\n\n\n\n\n\n\n\t54\n\tMnA-d\n\t4.462384e-01\n\t10.756210\n\t11.584470\n\n\n\n\n\n\n\t55\n\tMnB-d\n\t4.871784e-01\n\t10.775950\n\t11.728830\n\n\n\n\n\n\n\t56\n\tMnA-d\n\t4.970518e-01\n\t10.775950\n\t11.728860\n\n\n\n\n\n\n\t57\n\tMnB-d\n\t5.524834e-01\n\t11.372610\n\t12.116350\n\n\n\n\n\n\n\t58\n\tMnA-d\n\t5.359463e-01\n\t11.372900\n\t12.116520\n\n\n\n\n\n\n\t59\n\tMnB-d\n\t5.310759e-01\n\t11.460860\n\t12.139320\n\n\n\n\n\n\n\t60\n\tMnA-d\n\t5.498770e-01\n\t11.460860\n\t12.139440\n\n\n\n\n\n\n\t61\n\tMnA-d\n\t6.319939e-01\n\t11.760980\n\t12.225210\n\n\n\n\n\n\n\t62\n\tMnB-d\n\t5.944707e-01\n\t11.760980\n\t12.225220\n\n\n\n\n\n\n\t63\n\tMnA-d\n\t5.561498e-01\n\t11.859100\n\t12.476320\n\n\n\n\n\n\n\t64\n\tMnB-d\n\t5.952141e-01\n\t11.859100\n\t12.476390\n\n\n\n\n\n\n\t65\n\tMnA-d\n\t4.443856e-01\n\t11.906640\n\t13.647540\n\n\n\n\n\n\n\t66\n\tMnB-d\n\t4.382827e-01\n\t11.906640\n\t13.647540\n\n\n\n\n\n\n\t67\n\tMnA-d\n\t4.037192e-01\n\t12.546070\n\t14.155400\n\n\n\n\n\n\n\t68\n\tMnB-d\n\t4.076979e-01\n\t12.546260\n\t14.155410\n\n\n\n\n\n\n\t69\n\tMnA-d\n\t3.818132e-01\n\t12.935250\n\t15.122080\n\n\n\n\n\n\n\t70\n\tMnB-d\n\t3.625459e-01\n\t12.935250\n\t15.122080\n\n\n\n\n\n\n\t71\n\tMnA-d\n\t3.490791e-01\n\t12.935300\n\t15.298100\n\n\n\n\n\n\n\t72\n\tMnB-d\n\t3.679672e-01\n\t12.935300\n\t15.298100\n\n\n\n\n\n\n\t73\n\tAs-p\n\t2.463906e-01\n\t13.337000\n\t17.231180\n\n\n\n\n\n\n\t74\n\tAs-p\n\t2.471224e-01\n\t13.337000\n\t17.231940\n\n\n\n\n\n\n\t75\n\tAs-p\n\t2.612448e-01\n\t13.338310\n\t17.238990\n\n\n\n\n\n\n\t76\n\tAs-p\n\t2.613523e-01\n\t13.338310\n\t17.239860\n\n\n\n\n\n\n\t77\n\tCu-s\n\t5.382811e-01\n\t15.735610\n\t18.080020\n\n\n\n\n\n\n\t78\n\tCu-s\n\t5.381753e-01\n\t15.735610\n\t18.080100\n\n\n\n\n\n\n\t79\n\tCu-s\n\t4.345647e-01\n\t15.735650\n\t19.014880\n\n\n\n\n\n\n\t80\n\tCu-s\n\t4.345746e-01\n\t15.735650\n\t19.015010\n\n\n\n\n\n\n\t81\n\tCu-p\n\t6.307476e-01\n\t17.150360\n\t21.672600\n\n\n\n\n\n\n\t82\n\tCu-p\n\t6.301829e-01\n\t17.150360\n\t21.672600\n\n\n\n\n\n\n\t83\n\tCu-p\n\t6.360863e-01\n\t17.151180\n\t21.688920\n\n\n\n\n\n\n\t84\n\tCu-p\n\t6.360073e-01\n\t17.151180\n\t21.689040\n\n\n\n\n\n\n\t85\n\tCu-p\n\t5.066000e-01\n\t18.637610\n\t21.999160\n\n\n\n\n\n\n\t86\n\tCu-p\n\t5.068897e-01\n\t18.637610\n\t22.000310\n\n\n\n\n\n\n\t87\n\tCu-p\n\t3.637123e-01\n\t18.842430\n\t22.443620\n\n\n\n\n\n\n\t88\n\tCu-p\n\t3.633814e-01\n\t18.842430\n\t22.443800\n\n\n\n\n\n\n\t89\n\tCu-p\n\t6.450014e-01\n\t20.094510\n\t25.706380\n\n\n\n\n\n\n\t90\n\tCu-p\n\t6.453492e-01\n\t20.094580\n\t25.706380\n\n\n\n\n\n\n\t91\n\tCu-p\n\t4.970763e-01\n\t20.505080\n\t25.707220\n\n\n\n\n\n\n\t92\n\tCu-p\n\t4.970011e-01\n\t20.505140\n\t25.707220","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":"user","profile_url":"https://scicomp.stackexchange.com/users/56092/user","user_type":"registered"},"created_at":"2025-12-01T05:02:52+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A25C27D9-F00D-43FF-BBCD-A56B29E36C66","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A25C27D9-F00D-43FF-BBCD-A56B29E36C66/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Anton Menshov","profile_url":"https://scicomp.stackexchange.com/users/20688/anton-menshov","user_type":"moderator"},"created_at":"2025-12-05T23:04:02+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"D64A8503-8E84-4833-83F0-F085B193FA6D","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D64A8503-8E84-4833-83F0-F085B193FA6D/view-source"},{"content_license":null,"contributor":{"display_name":"Community","profile_url":"https://scicomp.stackexchange.com/users/-1/community","user_type":"moderator"},"created_at":"2026-02-26T17:03:40+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"4FDC78FA-271C-4288-B604-DBCEB3ED119B","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/4FDC78FA-271C-4288-B604-DBCEB3ED119B/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":"45300","source_record_sha256":"c7c4b5f8b542ed51a248f6eb26d6bf77b934971f18b5fc740a71e63429626f76","source_url":"https://scicomp.stackexchange.com/questions/45300/why-does-wannier90-often-fail-to-produce-good-mlwfs-for-this-metallic-system-an","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am working on constructing maximally localized Wannier functions (MLWFs) for a metallic system CuMnAs using Wannier90, but the fitting quality is significantly worse than in insulating cases. The disentanglement step shows unstable convergence, the spreads oscillate, and the interpolated bands deviate from the DFT bands—especially near the Fermi level, where multiple bands cross.

\n

I suspect this may be related to the choice of projection orbitals, inner/outer disentanglement windows, or an insufficient k-point mesh. However, even after adjusting these parameters, the Wannierization still fails to produce a smooth and well-localized subspace.

\n

Here is win input:

\n
num_wann = 52        \nnum_bands = 92       \n\nwrite_hr           = true\nwrite_rmn          = true\nwrite_tb           = true\n\nfermi_energy = 12.1450\n\ndis_num_iter = 150\n\ndis_win_min = 5.3    \ndis_win_max =  15.3  \ndis_froz_max = 13.3 \ndis_froz_min= 5.3  \n\nspinors = .true. \nwrite_xyz = .true. \n!restart = plot       \nbands_plot = true    \n\nbegin projections\nMnA: d\nMnB: d  \nCu: d\nAs: p\nend projections\n\nbegin kpoint_path\nG  0.0000  0.0000  0.0000   Y  0.5000  0.0000  0.0000\nY  0.5000  0.0000  0.0000   M  0.5000  0.5000  0.0000\nM  0.5000  0.5000  0.0000   G  0.0000  0.0000  0.0000\nG  0.0000  0.0000  0.0000   Z  0.0000  0.0000  0.5000\nZ  0.0000  0.0000  0.5000   R  0.5000  0.0000  0.5000\nR  0.5000  0.0000  0.5000   A  0.5000  0.5000  0.5000\nA  0.5000  0.5000  0.5000   Z  0.0000  0.0000  0.5000\nend kpoint_path\n\nbegin unit_cell_cart\nangstrom\n   3.6994910000  0.0000000000  0.0000000000\n   0.0000000000  3.6994910000  0.0000000000\n   0.0000000000  0.0000000000  6.4084220000\nend unit_cell_cart\n\nbegin atoms_frac\n MnA  0.0000000000  0.5000000000  0.1640200000\n MnB  0.5000000000  0.0000000000  0.8359800000\n As  0.5000000000  0.0000000000  0.2237540000\n Cu  0.0000000000  0.0000000000  0.5000000000\n Cu  0.5000000000  0.5000000000  0.5000000000\n As  0.0000000000  0.5000000000  0.7762460000\nend atoms_frac\n\nmp_grid           = 12 12 8\n\nbegin kpoints\n  0.00000000  0.00000000  0.00000000  8.680556e-04\n  0.00000000  0.00000000  0.12500000  8.680556e-04\n  0.00000000  0.00000000  0.25000000  8.680556e-04\n
\n

Here are the fatbands:

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
IndexOrbitalWeightEnergy_minEnergy_max
1MnB-s9.881649e-01-66.668270-66.667510
2MnB-s9.879660e-01-66.668270-66.667510
3MnA-s9.868490e-01-66.666030-66.665820
4MnA-s9.867413e-01-66.666030-66.665820
5MnB-p8.400973e-01-36.325620-36.323540
6MnB-p8.317571e-01-36.325620-36.323540
7MnA-p8.318057e-01-36.323460-36.317360
8MnA-p8.401787e-01-36.323460-36.317360
9MnB-p8.161489e-01-35.099230-35.097040
10MnB-p8.040838e-01-35.099220-35.097020
11MnA-p8.036925e-01-35.098130-35.089650
12MnA-p8.164002e-01-35.098110-35.089650
13MnB-p8.358367e-01-35.036260-35.031930
14MnB-p8.179446e-01-35.036260-35.031850
15MnA-p8.182119e-01-35.030990-35.025720
16MnA-p8.356700e-01-35.030900-35.025720
17As-s8.392833e-01-0.8310001.316030
18As-s8.338588e-01-0.8310001.316030
19As-s9.058134e-01-0.2092401.324800
20As-s9.062729e-01-0.2092401.324800
21As-p6.143355e-015.3423806.637930
22As-p6.134158e-015.3423806.638240
23As-p5.129997e-015.4012907.767510
24As-p5.125643e-015.4012907.768130
25As-p4.726773e-016.6260108.053720
26As-p4.721743e-016.6265208.053720
27Cu-d4.986890e-017.3909008.116920
28Cu-d4.998003e-017.3909008.116970
29Cu-d6.113203e-017.8545608.416970
30Cu-d6.121870e-017.8546308.417060
31Cu-d6.305895e-018.0952609.091470
32Cu-d6.304399e-018.0964009.091470
33Cu-d9.469474e-018.5141709.141630
34Cu-d9.472102e-018.5142509.141630
35Cu-d8.649751e-018.5789209.369690
36Cu-d8.651089e-018.5789209.369690
37Cu-d8.952000e-018.6907709.548950
38Cu-d8.955303e-018.6909009.549270
39Cu-d8.297525e-018.6963809.812650
40Cu-d8.296666e-018.6963809.812870
41Cu-d9.651834e-019.45916010.066180
42Cu-d9.651335e-019.45945010.066180
43Cu-d7.823033e-019.46293010.346490
44Cu-d7.823292e-019.46293010.346490
45Cu-d6.928074e-019.65279010.470370
46Cu-d6.929086e-019.65311010.470370
47Cu-d7.334994e-019.65359010.643890
48Cu-d7.336775e-019.65359010.644060
49Cu-d4.933639e-019.91051010.936240
50Cu-d4.946027e-019.91066010.936620
51Cu-d3.412474e-019.92166011.233320
52MnB-d3.405554e-019.92166011.233320
53MnB-d4.567662e-0110.75607011.584470
54MnA-d4.462384e-0110.75621011.584470
55MnB-d4.871784e-0110.77595011.728830
56MnA-d4.970518e-0110.77595011.728860
57MnB-d5.524834e-0111.37261012.116350
58MnA-d5.359463e-0111.37290012.116520
59MnB-d5.310759e-0111.46086012.139320
60MnA-d5.498770e-0111.46086012.139440
61MnA-d6.319939e-0111.76098012.225210
62MnB-d5.944707e-0111.76098012.225220
63MnA-d5.561498e-0111.85910012.476320
64MnB-d5.952141e-0111.85910012.476390
65MnA-d4.443856e-0111.90664013.647540
66MnB-d4.382827e-0111.90664013.647540
67MnA-d4.037192e-0112.54607014.155400
68MnB-d4.076979e-0112.54626014.155410
69MnA-d3.818132e-0112.93525015.122080
70MnB-d3.625459e-0112.93525015.122080
71MnA-d3.490791e-0112.93530015.298100
72MnB-d3.679672e-0112.93530015.298100
73As-p2.463906e-0113.33700017.231180
74As-p2.471224e-0113.33700017.231940
75As-p2.612448e-0113.33831017.238990
76As-p2.613523e-0113.33831017.239860
77Cu-s5.382811e-0115.73561018.080020
78Cu-s5.381753e-0115.73561018.080100
79Cu-s4.345647e-0115.73565019.014880
80Cu-s4.345746e-0115.73565019.015010
81Cu-p6.307476e-0117.15036021.672600
82Cu-p6.301829e-0117.15036021.672600
83Cu-p6.360863e-0117.15118021.688920
84Cu-p6.360073e-0117.15118021.689040
85Cu-p5.066000e-0118.63761021.999160
86Cu-p5.068897e-0118.63761022.000310
87Cu-p3.637123e-0118.84243022.443620
88Cu-p3.633814e-0118.84243022.443800
89Cu-p6.450014e-0120.09451025.706380
90Cu-p6.453492e-0120.09458025.706380
91Cu-p4.970763e-0120.50508025.707220
92Cu-p4.970011e-0120.50514025.707220
\n","question_title":"Why does Wannier90 often fail to produce good MLWFs for this metallic system, and what parameters should be adjusted?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45300/why-does-wannier90-often-fail-to-produce-good-mlwfs-for-this-metallic-system-an","split":"train"} {"accepted_answer":{"answer_html":"

Eigenvector matrices are not unique.

\n

The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.

\n

At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.

\n","answer_id":45312,"answer_text":"Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.","answer_url":"https://scicomp.stackexchange.com/a/45312","author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-12-13T10:03:37+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45311,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-13T10:03:37+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"BFC0D245-EF3B-4C7B-9150-73518AFD2D2A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-18T09:34:32+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"74B8DDDA-9B0B-40CA-BE67-18501D69153F","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}],"score":6,"updated_at":"2025-12-18T09:34:32+00:00"},"answer_scores":[{"answer_id":45312,"score":6}],"answers":[{"answer_html":"

Eigenvector matrices are not unique.

\n

The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.

\n

At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.

\n","answer_id":45312,"answer_text":"Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.","answer_url":"https://scicomp.stackexchange.com/a/45312","author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-12-13T10:03:37+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45311,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-13T10:03:37+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"BFC0D245-EF3B-4C7B-9150-73518AFD2D2A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-18T09:34:32+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"74B8DDDA-9B0B-40CA-BE67-18501D69153F","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}],"score":6,"updated_at":"2025-12-18T09:34:32+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-13T10:03:37+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"BFC0D245-EF3B-4C7B-9150-73518AFD2D2A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-18T09:34:32+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"74B8DDDA-9B0B-40CA-BE67-18501D69153F","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45312"}],"question_author":"Argha Nilanjon Nondi","question_author_url":"https://scicomp.stackexchange.com/users/56165/argha-nilanjon-nondi"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n","post_id":"scicomp:45311","sha256":"ad56fe2c0260b1f75acb06603952a687d5a2487cdcb7f14fa35ca2ddbe95dbe9","source_url":"https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"},{"block_index":1,"code_text":"U_, s_, Vt_ = np.linalg.svd(A)\n","post_id":"scicomp:45311","sha256":"c8237ba622cf113feb706a6dd46de44c41ac2edd5ac548cd0e9562bf82e74fa5","source_url":"https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"},{"block_index":2,"code_text":"array([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n","post_id":"scicomp:45311","sha256":"4cda5ade3a144a469abb88bffdd5350eee2a9e4c4c6ffc3fcf0da96e78a532ad","source_url":"https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"},{"block_index":3,"code_text":"array([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n","post_id":"scicomp:45311","sha256":"4d244a0f26aff76a011a4776fb52a39ba22c87240b2d6b50a22f0ad5f693e3d7","source_url":"https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"d690d909f50d3399ad7aee57d32df30be470ce0bbb86280a02f772641c385cba","id":"SCT-70c16e60a8cc7c1c73251ced","language":["python"],"library_or_tool":["numpy"],"problem_text":"Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code\n\n\n\n\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\n\n\n\n\nI am validating my code with the svd method that comes with numpy\n\n\n\n\nU_, s_, Vt_ = np.linalg.svd(A)\n\n\n\n\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:\n\n\n\n\narray([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\n\n\n\n\nbut for U_ (numpy code) it gives\n\n\n\n\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\n\n\n\n\nthe second column of the U and U_ are not same. What did I wrong in my code?","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":"Argha Nilanjon Nondi","profile_url":"https://scicomp.stackexchange.com/users/56165/argha-nilanjon-nondi","user_type":"registered"},"created_at":"2025-12-12T11:42:59+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"55A03C96-FFA6-4091-B82C-8C1BFFCC135C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/55A03C96-FFA6-4091-B82C-8C1BFFCC135C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Rodrigo de Azevedo","profile_url":"https://scicomp.stackexchange.com/users/20417/rodrigo-de-azevedo","user_type":"registered"},"created_at":"2025-12-14T01:42:00+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"66A5A413-7880-49BB-BFD9-3C22E51146C1","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/66A5A413-7880-49BB-BFD9-3C22E51146C1/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Rodrigo de Azevedo","profile_url":"https://scicomp.stackexchange.com/users/20417/rodrigo-de-azevedo","user_type":"registered"},"created_at":"2025-12-17T04:25:41+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"D5AB7600-388F-43AF-86AC-50AA22DFF81D","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D5AB7600-388F-43AF-86AC-50AA22DFF81D/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":"45311","source_record_sha256":"a056be207e03910977984352300db92ae77f896eec52d9f9bf3f4d3d5f3e8953","source_url":"https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code

\n
import numpy as np\n\nA=np.array([\n    [1,2],\n    [4,5],\n    [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n
\n

I am validating my code with the svd method that comes with numpy

\n
U_, s_, Vt_ = np.linalg.svd(A)\n
\n

when I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:

\n
array([[-0.17259857, -0.89640564,  0.40824829],\n       [-0.50818671, -0.27400657, -0.81649658],\n       [-0.84377485,  0.3483925 ,  0.40824829]])\n
\n

but for U_ (numpy code) it gives

\n
array([[-0.17259857,  0.89640564,  0.40824829],\n       [-0.50818671,  0.27400657, -0.81649658],\n       [-0.84377485, -0.3483925 ,  0.40824829]])\n
\n

the second column of the U and U_ are not same. What did I wrong in my code?

\n","question_title":"Computing the SVD manually and using Python — why are the signs different?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different","split":"train"} {"accepted_answer":{"answer_html":"

This implementation of the trust region method is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp which fits your situation closely.

\n

It accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.

\n
from functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n    rand: np.random.Generator,\n    m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n    sp.sparray,  # Q\n    sp.sparray,  # A\n    np.ndarray,  # b\n]:\n    # x is an unknown n-vector\n    x_hidden = rand.random(size=n)\n\n    # Q is a known (n,n) sparse positive semi-definite matrix\n    data = rand.random(size=n*nnz)\n    indices = np.array([\n        rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n        for _ in range(n)\n    ], dtype=np.int32)\n    indices.sort(axis=1)\n    indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n    Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n    data = rand.random(size=m_independent*nnz)\n    indices = np.array([\n        rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n        for _ in range(m_independent)\n    ])\n    indices.sort(axis=1)\n    indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n    A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n    coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n    A_blocks = [\n        row @ A_independent[\n            rand.integers(low=0, high=m_independent, size=2), :,\n        ]\n        for row in coefs\n    ]\n    A_blocks.append(A_independent)\n    A = sp.vstack(A_blocks)\n    b = A @ x_hidden\n\n    return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n    return x @ Q @ x    # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n    return x@QQT    # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n    return QQT      # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n    QQT = Q + Q.T\n    fun = partial(cost, Q=Q)\n    jac = partial(jacobian, QQT=QQT)\n    hess = partial(hessian, QQT=QQT)\n\n    m, n = A.shape\n    err = check_grad(fun, jac, np.ones(n))\n    assert err < 1e-3\n    err = check_grad(jac, hess, np.ones(n))\n    assert err < 1e-5\n\n    result = minimize(\n        method='trust-constr', x0=np.zeros(n),\n        fun=fun, jac=jac, hess=hess,\n        constraints=LinearConstraint(A=A, lb=b, ub=b),\n        options={'factorization_method': 'AugmentedSystem'},\n    )\n    if not result.success:\n        raise ValueError(result.message)\n    print(result)\n    return result.x\n\n\ndef demo() -> None:\n    rand = np.random.default_rng(seed=0)\n    Q, A, b = sample_data(rand=rand)\n    solve(Q, A, b)\n\n\nif __name__ == '__main__':\n    demo()\n
\n
          message: `xtol` termination condition is satisfied.\n          success: True\n           status: 2\n              fun: 420.8655622183405\n                x: [ 5.530e-01  3.104e-01 ...  6.516e-01  6.497e-01]\n              nit: 15\n             nfev: 6\n             njev: 5\n             nhev: 5\n         cg_niter: 0\n     cg_stop_cond: 1\n             grad: [ 7.940e+00  4.136e+00 ...  7.226e+00  7.271e+00]\n  lagrangian_grad: [ 2.711e-01  2.216e-01 ... -1.650e-01  6.675e-01]\n           constr: [array([ 2.573e+00,  3.197e+00, ...,  2.866e+00,\n                           3.016e+00], shape=(350,))]\n              jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n                    with 4167 stored elements and shape (350, 300)>]\n      constr_nfev: [0]\n      constr_njev: [0]\n      constr_nhev: [0]\n                v: [array([-3.314e+02,  4.310e+02, ..., -9.438e-01,\n                           8.593e+00], shape=(350,))]\n           method: equality_constrained_sqp\n       optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n   execution_time: 0.10921216011047363\n        tr_radius: 4.682990630409006e-09\n   constr_penalty: 19.590428780507548\n            niter: 15\n
\n

You may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:

\n
    (\n        x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n    ) = sp.linalg.lsqr(A, b)\n\n    result = minimize(\n        method='trust-constr', x0=x,\n        fun=fun, jac=jac, hess=hess,\n        constraints=LinearConstraint(A=A, lb=b, ub=b),\n        options={'factorization_method': 'AugmentedSystem'},\n    )\n
\n
          message: `xtol` termination condition is satisfied.\n          success: True\n           status: 2\n              fun: 420.86556221833825\n                x: [ 5.530e-01  3.104e-01 ...  6.516e-01  6.497e-01]\n              nit: 11\n             nfev: 3\n             njev: 2\n             nhev: 2\n         cg_niter: 0\n     cg_stop_cond: 1\n             grad: [ 7.940e+00  4.136e+00 ...  7.226e+00  7.271e+00]\n  lagrangian_grad: [ 2.711e-01  2.216e-01 ... -1.650e-01  6.675e-01]\n           constr: [array([ 2.573e+00,  3.197e+00, ...,  2.866e+00,\n                           3.016e+00], shape=(350,))]\n              jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n                    with 4167 stored elements and shape (350, 300)>]\n      constr_nfev: [0]\n      constr_njev: [0]\n      constr_nhev: [0]\n                v: [array([-1.682e+03,  4.026e+02, ..., -9.438e-01,\n                           8.593e+00], shape=(350,))]\n           method: equality_constrained_sqp\n       optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n   execution_time: 0.047506093978881836\n        tr_radius: 1.0000000000000005e-09\n   constr_penalty: 29.017471116474994\n            niter: 11\n
\n","answer_id":45314,"answer_text":"This implementation of the trust region method (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html) is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp (https://github.com/scipy/scipy/blob/8b0782d06d69b568b9a6db1a488dc52f93c0a066/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py#L17) which fits your situation closely.\n\n\n\n\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.\n\n\n\n\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: []\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-3.314e+02, 4.310e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n execution_time: 0.10921216011047363\n tr_radius: 4.682990630409006e-09\n constr_penalty: 19.590428780507548\n niter: 15\n\n\n\n\n\nYou may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:\n\n\n\n\n (\n x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n ) = sp.linalg.lsqr(A, b)\n\n result = minimize(\n method='trust-constr', x0=x,\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.86556221833825\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 11\n nfev: 3\n njev: 2\n nhev: 2\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: []\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-1.682e+03, 4.026e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n execution_time: 0.047506093978881836\n tr_radius: 1.0000000000000005e-09\n constr_penalty: 29.017471116474994\n niter: 11","answer_url":"https://scicomp.stackexchange.com/a/45314","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-12-18T02:10:48+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45313,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:10:48+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"112882E6-D22D-4B0F-B63C-E98B24E090FD","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/112882E6-D22D-4B0F-B63C-E98B24E090FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:27:59+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"4A035A0E-ACFE-4DA8-A9D9-64D3EC0349AA","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4A035A0E-ACFE-4DA8-A9D9-64D3EC0349AA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:45:54+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A3C07864-B437-4296-899A-3CA397B53268","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A3C07864-B437-4296-899A-3CA397B53268/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-19T23:14:22+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"AD48D688-F551-4BC7-A9BB-6CA53CC8E35A","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AD48D688-F551-4BC7-A9BB-6CA53CC8E35A/view-source"}],"score":3,"updated_at":"2025-12-19T23:14:22+00:00"},"answer_scores":[{"answer_id":45314,"score":3}],"answers":[{"answer_html":"

This implementation of the trust region method is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp which fits your situation closely.

\n

It accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.

\n
from functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n    rand: np.random.Generator,\n    m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n    sp.sparray,  # Q\n    sp.sparray,  # A\n    np.ndarray,  # b\n]:\n    # x is an unknown n-vector\n    x_hidden = rand.random(size=n)\n\n    # Q is a known (n,n) sparse positive semi-definite matrix\n    data = rand.random(size=n*nnz)\n    indices = np.array([\n        rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n        for _ in range(n)\n    ], dtype=np.int32)\n    indices.sort(axis=1)\n    indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n    Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n    data = rand.random(size=m_independent*nnz)\n    indices = np.array([\n        rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n        for _ in range(m_independent)\n    ])\n    indices.sort(axis=1)\n    indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n    A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n    coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n    A_blocks = [\n        row @ A_independent[\n            rand.integers(low=0, high=m_independent, size=2), :,\n        ]\n        for row in coefs\n    ]\n    A_blocks.append(A_independent)\n    A = sp.vstack(A_blocks)\n    b = A @ x_hidden\n\n    return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n    return x @ Q @ x    # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n    return x@QQT    # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n    return QQT      # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n    QQT = Q + Q.T\n    fun = partial(cost, Q=Q)\n    jac = partial(jacobian, QQT=QQT)\n    hess = partial(hessian, QQT=QQT)\n\n    m, n = A.shape\n    err = check_grad(fun, jac, np.ones(n))\n    assert err < 1e-3\n    err = check_grad(jac, hess, np.ones(n))\n    assert err < 1e-5\n\n    result = minimize(\n        method='trust-constr', x0=np.zeros(n),\n        fun=fun, jac=jac, hess=hess,\n        constraints=LinearConstraint(A=A, lb=b, ub=b),\n        options={'factorization_method': 'AugmentedSystem'},\n    )\n    if not result.success:\n        raise ValueError(result.message)\n    print(result)\n    return result.x\n\n\ndef demo() -> None:\n    rand = np.random.default_rng(seed=0)\n    Q, A, b = sample_data(rand=rand)\n    solve(Q, A, b)\n\n\nif __name__ == '__main__':\n    demo()\n
\n
          message: `xtol` termination condition is satisfied.\n          success: True\n           status: 2\n              fun: 420.8655622183405\n                x: [ 5.530e-01  3.104e-01 ...  6.516e-01  6.497e-01]\n              nit: 15\n             nfev: 6\n             njev: 5\n             nhev: 5\n         cg_niter: 0\n     cg_stop_cond: 1\n             grad: [ 7.940e+00  4.136e+00 ...  7.226e+00  7.271e+00]\n  lagrangian_grad: [ 2.711e-01  2.216e-01 ... -1.650e-01  6.675e-01]\n           constr: [array([ 2.573e+00,  3.197e+00, ...,  2.866e+00,\n                           3.016e+00], shape=(350,))]\n              jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n                    with 4167 stored elements and shape (350, 300)>]\n      constr_nfev: [0]\n      constr_njev: [0]\n      constr_nhev: [0]\n                v: [array([-3.314e+02,  4.310e+02, ..., -9.438e-01,\n                           8.593e+00], shape=(350,))]\n           method: equality_constrained_sqp\n       optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n   execution_time: 0.10921216011047363\n        tr_radius: 4.682990630409006e-09\n   constr_penalty: 19.590428780507548\n            niter: 15\n
\n

You may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:

\n
    (\n        x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n    ) = sp.linalg.lsqr(A, b)\n\n    result = minimize(\n        method='trust-constr', x0=x,\n        fun=fun, jac=jac, hess=hess,\n        constraints=LinearConstraint(A=A, lb=b, ub=b),\n        options={'factorization_method': 'AugmentedSystem'},\n    )\n
\n
          message: `xtol` termination condition is satisfied.\n          success: True\n           status: 2\n              fun: 420.86556221833825\n                x: [ 5.530e-01  3.104e-01 ...  6.516e-01  6.497e-01]\n              nit: 11\n             nfev: 3\n             njev: 2\n             nhev: 2\n         cg_niter: 0\n     cg_stop_cond: 1\n             grad: [ 7.940e+00  4.136e+00 ...  7.226e+00  7.271e+00]\n  lagrangian_grad: [ 2.711e-01  2.216e-01 ... -1.650e-01  6.675e-01]\n           constr: [array([ 2.573e+00,  3.197e+00, ...,  2.866e+00,\n                           3.016e+00], shape=(350,))]\n              jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n                    with 4167 stored elements and shape (350, 300)>]\n      constr_nfev: [0]\n      constr_njev: [0]\n      constr_nhev: [0]\n                v: [array([-1.682e+03,  4.026e+02, ..., -9.438e-01,\n                           8.593e+00], shape=(350,))]\n           method: equality_constrained_sqp\n       optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n   execution_time: 0.047506093978881836\n        tr_radius: 1.0000000000000005e-09\n   constr_penalty: 29.017471116474994\n            niter: 11\n
\n","answer_id":45314,"answer_text":"This implementation of the trust region method (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html) is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp (https://github.com/scipy/scipy/blob/8b0782d06d69b568b9a6db1a488dc52f93c0a066/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py#L17) which fits your situation closely.\n\n\n\n\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.\n\n\n\n\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: []\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-3.314e+02, 4.310e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n execution_time: 0.10921216011047363\n tr_radius: 4.682990630409006e-09\n constr_penalty: 19.590428780507548\n niter: 15\n\n\n\n\n\nYou may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:\n\n\n\n\n (\n x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n ) = sp.linalg.lsqr(A, b)\n\n result = minimize(\n method='trust-constr', x0=x,\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.86556221833825\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 11\n nfev: 3\n njev: 2\n nhev: 2\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: []\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-1.682e+03, 4.026e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n execution_time: 0.047506093978881836\n tr_radius: 1.0000000000000005e-09\n constr_penalty: 29.017471116474994\n niter: 11","answer_url":"https://scicomp.stackexchange.com/a/45314","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-12-18T02:10:48+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45313,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:10:48+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"112882E6-D22D-4B0F-B63C-E98B24E090FD","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/112882E6-D22D-4B0F-B63C-E98B24E090FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:27:59+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"4A035A0E-ACFE-4DA8-A9D9-64D3EC0349AA","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4A035A0E-ACFE-4DA8-A9D9-64D3EC0349AA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:45:54+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A3C07864-B437-4296-899A-3CA397B53268","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A3C07864-B437-4296-899A-3CA397B53268/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-19T23:14:22+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"AD48D688-F551-4BC7-A9BB-6CA53CC8E35A","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AD48D688-F551-4BC7-A9BB-6CA53CC8E35A/view-source"}],"score":3,"updated_at":"2025-12-19T23:14:22+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:10:48+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"112882E6-D22D-4B0F-B63C-E98B24E090FD","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/112882E6-D22D-4B0F-B63C-E98B24E090FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:27:59+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"4A035A0E-ACFE-4DA8-A9D9-64D3EC0349AA","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4A035A0E-ACFE-4DA8-A9D9-64D3EC0349AA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-18T02:45:54+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A3C07864-B437-4296-899A-3CA397B53268","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A3C07864-B437-4296-899A-3CA397B53268/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-19T23:14:22+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"AD48D688-F551-4BC7-A9BB-6CA53CC8E35A","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AD48D688-F551-4BC7-A9BB-6CA53CC8E35A/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45314"}],"question_author":"BenPol","question_author_url":"https://scicomp.stackexchange.com/users/56185/benpol"},"code_blocks":[{"block_index":0,"code_text":"from functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n","post_id":45314,"sha256":"da81cb2d755a0263cd70a8aae9d8279e3d37a534eae425b0134065686b4623f3","source_url":"https://scicomp.stackexchange.com/a/45314"},{"block_index":1,"code_text":" message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: []\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-3.314e+02, 4.310e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n execution_time: 0.10921216011047363\n tr_radius: 4.682990630409006e-09\n constr_penalty: 19.590428780507548\n niter: 15\n","post_id":45314,"sha256":"df449feda6d2dc5eee9cf83ead27036f7b6db2c16f5c746a5192d773eb590e53","source_url":"https://scicomp.stackexchange.com/a/45314"},{"block_index":2,"code_text":" (\n x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n ) = sp.linalg.lsqr(A, b)\n\n result = minimize(\n method='trust-constr', x0=x,\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n","post_id":45314,"sha256":"19ab7798103d8bac482a3169236cd73ef72f5cd1bddc761175271c25a845c01f","source_url":"https://scicomp.stackexchange.com/a/45314"},{"block_index":3,"code_text":" message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.86556221833825\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 11\n nfev: 3\n njev: 2\n nhev: 2\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: []\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-1.682e+03, 4.026e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n execution_time: 0.047506093978881836\n tr_radius: 1.0000000000000005e-09\n constr_penalty: 29.017471116474994\n niter: 11\n","post_id":45314,"sha256":"14014a4858b522078f46dd7fe14e70d524d076dfdff93cdcbc8d32a97b96bfaf","source_url":"https://scicomp.stackexchange.com/a/45314"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"a9b1da8a04773ed9acc1320920960d53100792fb676ef8216f819b9dc636e4fa","id":"SCT-bb4c14956d4c872569a1f1d7","language":null,"library_or_tool":null,"problem_text":"I have a quadratic programming problem\n$$\n\\begin{matrix}\n\\textrm{minimise} & x^TQx \\\\\n\\textrm{subject to} & Ax = b\n\\end{matrix}\n$$\nwhere $x$ is a vector of unknowns, $Q$ is a positive semi-definite matrix, $A$ is a matrix of constraint coefficients, and $b$ is a vector of constraint rhs values. The constraints represented by $Ax=b$ are linearly dependent. To give an idea of the extent of linear dependency, $A$ could be something $350 \\times 300$, so 350 constraints with 300 unknowns, but this reduces to 280 linearly independent constraints. It can be safely assumed that the constraints are consistent and $\\textrm{null}(Q)\\cap\\textrm{null}(A)=\\{0\\}$ such that the problem has a unique solution. I would like to find a way to solve this problem for large and sparse $Q$ and $A$. I have attempted the following.\n\n\n\n\nFirst, I tried reducing $A$ to only have linearly independent rows, denoted $A_R$, and solving the KKT system\n$$\n\\begin{bmatrix}\nQ & A_R^T \\\\\nA_R & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nI reduced $A$ to linearly independent rows by performing a sparse rank-revealing QR decomposition on $A^T$ to get the linearly independent columns of $A^T$. If this succeeded, I solved the KKT system using a sparse LU decomposition. Solving the KKT system didn't have any issues, however the sparse rank-revealing QR decomposition on $A^T$ was quite fragile and failed on larger systems. I used the C++ library Eigen with Eigen::SparseQR to perform the decomposition. In the Eigen documentation it says \"The numerical pivoting strategy and default threshold are the same as in SuiteSparse QR ... even though it is qualified as \"rank-revealing\", this strategy might fail for some rank deficient problems.\".\n\n\n\n\nSecond, I tried solving the KKT system directly without reducing $A$\n$$\n\\begin{bmatrix}\nQ & A^T \\\\\nA & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nThis is a singular system, so I tried solving it with MINRES. Again I used the Eigen library (Eigen::MINRES). The convergence was extremely poor and solutions usually had a large error. I didn't use a preconditioner as I wasn't sure how to form one for this scenario.\n\n\n\n\nThird, I tried using nonlinear optimiser Ipopt. This did not work at all since Ipopt immediately exits with error Not_Enough_Degrees_Of_Freedom. There is an option in Ipopt to detect and remove linearly dependent constraints but in the docs it says \"This is experimental and does not work well.\", so I'm assuming this will have the same issues as the first approach.\n\n\n\n\nSo, what approaches could I use to solve this problem for large and sparse $Q$ and $A$?. Simply converting everything to dense matrices is not feasible as I need to solve this sort of system for millions of unknowns and constraints.","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":"BenPol","profile_url":"https://scicomp.stackexchange.com/users/56185/benpol","user_type":"registered"},"created_at":"2025-12-16T01:29:04+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"52AB4280-FF49-4A54-8177-8AFB5BBE2030","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/52AB4280-FF49-4A54-8177-8AFB5BBE2030/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":"45313","source_record_sha256":"78b5c29e86ba08913877049c318659ead5da873471baa0fe923b9c82e499b3de","source_url":"https://scicomp.stackexchange.com/questions/45313/quadratic-programming-with-linearly-dependent-equality-constraints","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have a quadratic programming problem\n$$\n\\begin{matrix}\n\\textrm{minimise} & x^TQx \\\\\n\\textrm{subject to} & Ax = b\n\\end{matrix}\n$$\nwhere $x$ is a vector of unknowns, $Q$ is a positive semi-definite matrix, $A$ is a matrix of constraint coefficients, and $b$ is a vector of constraint rhs values. The constraints represented by $Ax=b$ are linearly dependent. To give an idea of the extent of linear dependency, $A$ could be something $350 \\times 300$, so 350 constraints with 300 unknowns, but this reduces to 280 linearly independent constraints. It can be safely assumed that the constraints are consistent and $\\textrm{null}(Q)\\cap\\textrm{null}(A)=\\{0\\}$ such that the problem has a unique solution. I would like to find a way to solve this problem for large and sparse $Q$ and $A$. I have attempted the following.

\n

First, I tried reducing $A$ to only have linearly independent rows, denoted $A_R$, and solving the KKT system\n$$\n\\begin{bmatrix}\nQ & A_R^T \\\\\nA_R & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nI reduced $A$ to linearly independent rows by performing a sparse rank-revealing QR decomposition on $A^T$ to get the linearly independent columns of $A^T$. If this succeeded, I solved the KKT system using a sparse LU decomposition. Solving the KKT system didn't have any issues, however the sparse rank-revealing QR decomposition on $A^T$ was quite fragile and failed on larger systems. I used the C++ library Eigen with Eigen::SparseQR to perform the decomposition. In the Eigen documentation it says "The numerical pivoting strategy and default threshold are the same as in SuiteSparse QR ... even though it is qualified as "rank-revealing", this strategy might fail for some rank deficient problems.".

\n

Second, I tried solving the KKT system directly without reducing $A$\n$$\n\\begin{bmatrix}\nQ & A^T \\\\\nA & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nThis is a singular system, so I tried solving it with MINRES. Again I used the Eigen library (Eigen::MINRES). The convergence was extremely poor and solutions usually had a large error. I didn't use a preconditioner as I wasn't sure how to form one for this scenario.

\n

Third, I tried using nonlinear optimiser Ipopt. This did not work at all since Ipopt immediately exits with error Not_Enough_Degrees_Of_Freedom. There is an option in Ipopt to detect and remove linearly dependent constraints but in the docs it says "This is experimental and does not work well.", so I'm assuming this will have the same issues as the first approach.

\n

So, what approaches could I use to solve this problem for large and sparse $Q$ and $A$?. Simply converting everything to dense matrices is not feasible as I need to solve this sort of system for millions of unknowns and constraints.

\n","question_title":"Quadratic programming with linearly dependent equality constraints","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45313/quadratic-programming-with-linearly-dependent-equality-constraints","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45329,"score":5},{"answer_id":45343,"score":1}],"answers":[{"answer_html":"

this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.

\n

cosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.

\n

in physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.

\n","answer_id":45329,"answer_text":"this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.\n\n\n\n\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.\n\n\n\n\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.","answer_url":"https://scicomp.stackexchange.com/a/45329","author":"Linda Anderson","author_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-05T09:26:54+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":45322,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Linda Anderson","profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","user_type":"registered"},"created_at":"2026-01-05T09:26:54+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"8F296337-1611-4B90-B028-6FDD3F098E8A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/8F296337-1611-4B90-B028-6FDD3F098E8A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Linda Anderson","profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","user_type":"registered"},"created_at":"2026-01-05T09:27:15+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"317C93D3-B055-47E3-8255-35BB56F95C1B","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/317C93D3-B055-47E3-8255-35BB56F95C1B/view-source"}],"score":5,"updated_at":"2026-01-05T09:27:15+00:00"},{"answer_html":"

The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):

\n
void worker_thread(\n    long long unsigned int start_idx,\n    long long unsigned int end_idx,\n    unsigned int thread_seed,\n    const real_type emitter_radius,\n    const real_type receiver_distance,\n    const real_type receiver_distance_plus,\n    const real_type receiver_radius,\n    real_type& result_count,\n    real_type& result_count_plus)\n{\n    // Thread-local random number generator\n    std::mt19937 local_gen(thread_seed);\n    std::uniform_real_distribution<real_type> local_dis(0.0, 1.0);\n\n    real_type local_count = 0;\n    real_type local_count_plus = 0;\n\n    // Update progress every N iterations to reduce atomic overhead\n    const long long unsigned int progress_update_interval = 10000;\n    long long unsigned int local_progress = 0;\n\n    for (long long unsigned int i = start_idx; i < end_idx; i++)\n    {\n        vector_3 location = random_unit_vector(local_gen, local_dis);\n        location.x *= emitter_radius;\n        location.y *= emitter_radius;\n        location.z *= emitter_radius;\n\n        vector_3 surface_normal = location;\n        surface_normal.normalize();\n\n\n        // A) Newtonian gravitation\n        //vector_3 normal =\n        //  surface_normal;\n\n        // B) Schwarzschild gravitation\n        //vector_3 normal = \n        //  random_cosine_weighted_hemisphere(\n        //      surface_normal, local_gen, local_dis);\n\n        // C) Quantum gravitation\n        vector_3 r = random_unit_vector(local_gen, local_dis);\n        r.x *= emitter_radius;\n        r.y *= emitter_radius;\n        r.z *= emitter_radius;\n        vector_3 normal = (location - r).normalize();\n\n\n        local_count += intersect(\n            location, normal,\n            receiver_distance, receiver_radius);\n\n        local_count_plus += intersect(\n            location, normal,\n            receiver_distance_plus, receiver_radius);\n\n        // Update global progress periodically\n        local_progress++;\n        if (local_progress >= progress_update_interval)\n        {\n            global_progress.fetch_add(\n                local_progress, std::memory_order_relaxed);\n    \n            local_progress = 0;\n        }\n    }\n\n    // Add any remaining progress\n    if (local_progress > 0)\n    {\n        global_progress.fetch_add(\n            local_progress, std::memory_order_relaxed);\n    }\n\n    result_count = local_count;\n    result_count_plus = local_count_plus;\n}\n
\n","answer_id":45343,"answer_text":"The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):\n\n\n\n\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distribution local_dis(0.0, 1.0);\n\n real_type local_count = 0;\n real_type local_count_plus = 0;\n\n // Update progress every N iterations to reduce atomic overhead\n const long long unsigned int progress_update_interval = 10000;\n long long unsigned int local_progress = 0;\n\n for (long long unsigned int i = start_idx; i < end_idx; i++)\n {\n vector_3 location = random_unit_vector(local_gen, local_dis);\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n\n // A) Newtonian gravitation\n //vector_3 normal =\n // surface_normal;\n\n // B) Schwarzschild gravitation\n //vector_3 normal = \n // random_cosine_weighted_hemisphere(\n // surface_normal, local_gen, local_dis);\n\n // C) Quantum gravitation\n vector_3 r = random_unit_vector(local_gen, local_dis);\n r.x *= emitter_radius;\n r.y *= emitter_radius;\n r.z *= emitter_radius;\n vector_3 normal = (location - r).normalize();\n\n\n local_count += intersect(\n location, normal,\n receiver_distance, receiver_radius);\n\n local_count_plus += intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n // Update global progress periodically\n local_progress++;\n if (local_progress >= progress_update_interval)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n \n local_progress = 0;\n }\n }\n\n // Add any remaining progress\n if (local_progress > 0)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n }\n\n result_count = local_count;\n result_count_plus = local_count_plus;\n}","answer_url":"https://scicomp.stackexchange.com/a/45343","author":"shawn_halayka","author_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-18T14:29:37+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":45322,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T14:29:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"3B011F27-08FE-4F81-9889-2BB52DA3F041","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3B011F27-08FE-4F81-9889-2BB52DA3F041/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-18T21:51:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"33787801-2B17-4E59-8320-A2FC503E2E22","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/33787801-2B17-4E59-8320-A2FC503E2E22/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T21:51:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"44B530A0-B124-4759-A997-8B27CEECCB3E","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/44B530A0-B124-4759-A997-8B27CEECCB3E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-18T17:04:23+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-19T21:29:13+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"F02DA395-BFED-4987-A4F2-199B2AA19C48","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F02DA395-BFED-4987-A4F2-199B2AA19C48/view-source"}],"score":1,"updated_at":"2026-03-19T21:29:13+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Linda Anderson","author_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Linda Anderson","profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","user_type":"registered"},"created_at":"2026-01-05T09:26:54+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"8F296337-1611-4B90-B028-6FDD3F098E8A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/8F296337-1611-4B90-B028-6FDD3F098E8A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Linda Anderson","profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","user_type":"registered"},"created_at":"2026-01-05T09:27:15+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"317C93D3-B055-47E3-8255-35BB56F95C1B","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/317C93D3-B055-47E3-8255-35BB56F95C1B/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45329"},{"author":"shawn_halayka","author_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T14:29:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"3B011F27-08FE-4F81-9889-2BB52DA3F041","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3B011F27-08FE-4F81-9889-2BB52DA3F041/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-18T21:51:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"33787801-2B17-4E59-8320-A2FC503E2E22","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/33787801-2B17-4E59-8320-A2FC503E2E22/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T21:51:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"44B530A0-B124-4759-A997-8B27CEECCB3E","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/44B530A0-B124-4759-A997-8B27CEECCB3E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-18T17:04:23+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-19T21:29:13+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"F02DA395-BFED-4987-A4F2-199B2AA19C48","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F02DA395-BFED-4987-A4F2-199B2AA19C48/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45343"}],"question_author":"shawn_halayka","question_author_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka"},"code_blocks":[{"block_index":0,"code_text":"double get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_cast(0));\n\n for (long long unsigned int i = 0; i < n; i++)\n {\n vector_3 location = random_unit_vector();\n\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n vector_3 normal = \n random_cosine_weighted_hemisphere(\n surface_normal);\n\n std::optional i_hit = intersect(\n location, normal, \n receiver_distance, receiver_radius);\n\n if (i_hit)\n count += *i_hit / (2.0 * receiver_radius);\n \n i_hit = intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n if (i_hit)\n count_plus += *i_hit / (2.0 * receiver_radius);\n }\n\n return count_plus - count;\n}\n","post_id":"scicomp:45322","sha256":"dd14afb6190985801db0b42e8ce0704e201c4af56175964f7264f111c08c55ef","source_url":"https://scicomp.stackexchange.com/questions/45322/numerical-schwarzschild-gravity"},{"block_index":0,"code_text":"void worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distribution local_dis(0.0, 1.0);\n\n real_type local_count = 0;\n real_type local_count_plus = 0;\n\n // Update progress every N iterations to reduce atomic overhead\n const long long unsigned int progress_update_interval = 10000;\n long long unsigned int local_progress = 0;\n\n for (long long unsigned int i = start_idx; i < end_idx; i++)\n {\n vector_3 location = random_unit_vector(local_gen, local_dis);\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n\n // A) Newtonian gravitation\n //vector_3 normal =\n // surface_normal;\n\n // B) Schwarzschild gravitation\n //vector_3 normal = \n // random_cosine_weighted_hemisphere(\n // surface_normal, local_gen, local_dis);\n\n // C) Quantum gravitation\n vector_3 r = random_unit_vector(local_gen, local_dis);\n r.x *= emitter_radius;\n r.y *= emitter_radius;\n r.z *= emitter_radius;\n vector_3 normal = (location - r).normalize();\n\n\n local_count += intersect(\n location, normal,\n receiver_distance, receiver_radius);\n\n local_count_plus += intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n // Update global progress periodically\n local_progress++;\n if (local_progress >= progress_update_interval)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n \n local_progress = 0;\n }\n }\n\n // Add any remaining progress\n if (local_progress > 0)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n }\n\n result_count = local_count;\n result_count_plus = local_count_plus;\n}\n","post_id":45343,"sha256":"8b4ac807ee7f55790fa205570aa413ed7cef7647bcb76b29af08a9295170026d","source_url":"https://scicomp.stackexchange.com/a/45343"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"493d8f724951311e95828c562fc3793d7d7131e7cc3efc2e287086abc61195fc","id":"SCT-9b0dcf9a1e140879b5148763","language":null,"library_or_tool":null,"problem_text":"Question\n\n\n\n\nWhat is the name of the numerical technique used to generate the appropriate gravitational acceleration by using a set of gravitational field lines that are not necessarily normal to the surface of the emitter?\n\n\n\n\nI have found that using cosine weighted pseudorandom field lines produces the result predicted by Schwarzschild's general relativity. It's a very simple calculation. Please help me identify its owner.\n\n\n\n\nIntroduction\n\n\n\n\nIn the past, I have written a short tutorial for C++ programmers on isotropic Newtonian gravitation.\nIn that old tutorial, I build an isotropic gravitational field through the use of pseudorandomly generated field lines.\nIn that old tutorial I use a sphere as the receiver.\nThe paper for that old tutorial is at Newtonian gravitation from scratch, for C++ programmers (https://www.techrxiv.org/users/685306/articles/1250456-newtonian-gravitation-from-scratch-for-c-programmers).\n\n\n\n\nIn this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book Gravitation, by Misner et al (https://search.worldcat.org/title/585119)).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.\n\n\n\n\nIn this question I use Planck units, where $c = G = \\hbar = k = 1$.\n\n\n\n\nMethod\n\n\n\n\nWhere $r_{e}$ is the emitter's Schwarzschild radius, $r_{r}$ is the receiver AABB radius (e.g. half of the AABB side length), and $1\\mathrm{e}11$ and $0.01$ are arbitrary constants:\n\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}\n\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}\nThe event horizon area is:\n\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}\nWhere $R$ is the distance from the emitter's centre, the derivative is:\n\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}\nHere $\\beta$ is the get intersecting line density function.\nThe gradient strength is:\n\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}\nFrom this I get the Newtonian acceleration $a_N$, where $r_e \\ll R$:\n\\begin{equation}\na_N =\\frac{g R \\log 2}{8 M_{e}} = \\sqrt{\\frac{n_e \\log 2}{4 \\pi R^4}} = \\frac{M_{e}}{R^2}.\n\\end{equation}\nI can also get a general relativistic acceleration $a_S$, where $r_e < R$:\n\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}\nAt close proximity, where $r_e \\approx R$, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}\n\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}\n\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}\nAt far proximity, where $r_e \\ll R$, $t \\approx 1$, and $dt/dR \\approx 0$, the metric produced is Newtonian -- curved space, practically flat time.\n\n\n\n\nUsing numerical relativity, I tried pseudorandom hemisphere and pseudorandom tangent plane field lines, but they did not work.\nThe only technique that works is cosine weighted pseudorandom field lines.\nThat is to say, as per the code for this tutorial (https://github.com/sjhalayka/schwarzschild_falloff_field_lines (https://github.com/sjhalayka/schwarzschild_falloff_field_lines)), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of $2 / \\pi$.\n\n\n\n\nFigure\n\n\n\n\n[image: axis-aligned bounding box; source: https://i.sstatic.net/XWbsh2qc.png] (https://i.sstatic.net/XWbsh2qc.png)\n\n\n\n\nThis figure shows an axis-aligned bounding box and an isotropic emitter, looking from slightly above.\nAn example field line (red) and intersecting line segment (green) are given.\nThe bounding box is filled with these green intersecting line segments.\nIt is the gradient of the density of these line segments that forms the gravitational acceleration.\nNote that the field line is normal to the surface of the emitter (producing Newtonian gravitation).\n\n\n\n\nC++ code\n\n\n\n\ndouble get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_cast(0));\n\n for (long long unsigned int i = 0; i < n; i++)\n {\n vector_3 location = random_unit_vector();\n\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n vector_3 normal = \n random_cosine_weighted_hemisphere(\n surface_normal);\n\n std::optional i_hit = intersect(\n location, normal, \n receiver_distance, receiver_radius);\n\n if (i_hit)\n count += *i_hit / (2.0 * receiver_radius);\n \n i_hit = intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n if (i_hit)\n count_plus += *i_hit / (2.0 * receiver_radius);\n }\n\n return count_plus - count;\n}\n\n\n\n\n\nThank you for your time!","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":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2025-12-27T16:49:47+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B772F06F-B869-413B-B8CD-DA295250BCD1","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B772F06F-B869-413B-B8CD-DA295250BCD1/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-12-27T20:17:48+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"EE985562-6FE8-4FB6-A77E-D42F97D166EC","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EE985562-6FE8-4FB6-A77E-D42F97D166EC/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":"45322","source_record_sha256":"71bb21ea86802a70e8d66ee51503b38cf0c0c7c2827e28417687c0e2d5875a8d","source_url":"https://scicomp.stackexchange.com/questions/45322/numerical-schwarzschild-gravity","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Question

\n

What is the name of the numerical technique used to generate the appropriate gravitational acceleration by using a set of gravitational field lines that are not necessarily normal to the surface of the emitter?

\n

I have found that using cosine weighted pseudorandom field lines produces the result predicted by Schwarzschild's general relativity. It's a very simple calculation. Please help me identify its owner.

\n

Introduction

\n

In the past, I have written a short tutorial for C++ programmers on isotropic Newtonian gravitation.\nIn that old tutorial, I build an isotropic gravitational field through the use of pseudorandomly generated field lines.\nIn that old tutorial I use a sphere as the receiver.\nThe paper for that old tutorial is at Newtonian gravitation from scratch, for C++ programmers.

\n

In this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book Gravitation, by Misner et al).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.

\n

In this question I use Planck units, where $c = G = \\hbar = k = 1$.

\n

Method

\n

Where $r_{e}$ is the emitter's Schwarzschild radius, $r_{r}$ is the receiver AABB radius (e.g. half of the AABB side length), and $1\\mathrm{e}11$ and $0.01$ are arbitrary constants:\n\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}\n\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}\nThe event horizon area is:\n\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}\nWhere $R$ is the distance from the emitter's centre, the derivative is:\n\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}\nHere $\\beta$ is the get intersecting line density function.\nThe gradient strength is:\n\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}\nFrom this I get the Newtonian acceleration $a_N$, where $r_e \\ll R$:\n\\begin{equation}\na_N =\\frac{g R \\log 2}{8 M_{e}} = \\sqrt{\\frac{n_e \\log 2}{4 \\pi R^4}} = \\frac{M_{e}}{R^2}.\n\\end{equation}\nI can also get a general relativistic acceleration $a_S$, where $r_e < R$:\n\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}\nAt close proximity, where $r_e \\approx R$, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}\n\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}\n\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}\nAt far proximity, where $r_e \\ll R$, $t \\approx 1$, and $dt/dR \\approx 0$, the metric produced is Newtonian -- curved space, practically flat time.

\n

Using numerical relativity, I tried pseudorandom hemisphere and pseudorandom tangent plane field lines, but they did not work.\nThe only technique that works is cosine weighted pseudorandom field lines.\nThat is to say, as per the code for this tutorial (https://github.com/sjhalayka/schwarzschild_falloff_field_lines), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of $2 / \\pi$.

\n

Figure

\n

\"axis-aligned

\n

This figure shows an axis-aligned bounding box and an isotropic emitter, looking from slightly above.\nAn example field line (red) and intersecting line segment (green) are given.\nThe bounding box is filled with these green intersecting line segments.\nIt is the gradient of the density of these line segments that forms the gravitational acceleration.\nNote that the field line is normal to the surface of the emitter (producing Newtonian gravitation).

\n

C++ code

\n
double get_intersecting_line_density(\n    const long long unsigned int n,\n    const double emitter_radius,\n    const double receiver_distance,\n    const double receiver_distance_plus,\n    const double receiver_radius)\n{\n    double count = 0;\n    double count_plus = 0;\n\n    generator.seed(static_cast<unsigned>(0));\n\n    for (long long unsigned int i = 0; i < n; i++)\n    {\n        vector_3 location = random_unit_vector();\n\n        location.x *= emitter_radius;\n        location.y *= emitter_radius;\n        location.z *= emitter_radius;\n\n        vector_3 surface_normal = location;\n        surface_normal.normalize();\n\n        vector_3 normal = \n                random_cosine_weighted_hemisphere(\n                surface_normal);\n\n        std::optional<double> i_hit = intersect(\n            location, normal, \n            receiver_distance, receiver_radius);\n\n        if (i_hit)\n            count += *i_hit / (2.0 * receiver_radius);\n    \n        i_hit = intersect(\n            location, normal,\n            receiver_distance_plus, receiver_radius);\n\n        if (i_hit)\n            count_plus += *i_hit / (2.0 * receiver_radius);\n    }\n\n    return count_plus - count;\n}\n
\n

Thank you for your time!

\n","question_title":"Numerical Schwarzschild gravity?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45322/numerical-schwarzschild-gravity","split":"test"} {"accepted_answer":{"answer_html":"

The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.

\n

This is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.

\n","answer_id":45327,"answer_text":"The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).","answer_url":"https://scicomp.stackexchange.com/a/45327","author":"Wolfgang Bangerth","author_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-03T02:46:44+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Wolfgang Bangerth","profile_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","user_type":"registered"},"created_at":"2026-01-03T02:46:44+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-23T14:37:58+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B49E063C-3F0D-471B-956C-B179F2F73567","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}],"score":10,"updated_at":"2026-01-23T14:37:58+00:00"},"answer_scores":[{"answer_id":45327,"score":10},{"answer_id":45328,"score":3},{"answer_id":45348,"score":2}],"answers":[{"answer_html":"

The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.

\n

This is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.

\n","answer_id":45327,"answer_text":"The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).","answer_url":"https://scicomp.stackexchange.com/a/45327","author":"Wolfgang Bangerth","author_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-03T02:46:44+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Wolfgang Bangerth","profile_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","user_type":"registered"},"created_at":"2026-01-03T02:46:44+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-23T14:37:58+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B49E063C-3F0D-471B-956C-B179F2F73567","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}],"score":10,"updated_at":"2026-01-23T14:37:58+00:00"},{"answer_html":"

I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.

\n

In classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).

\n

This gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.

\n

I don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.

\n","answer_id":45328,"answer_text":"I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.\n\n\n\n\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).\n\n\n\n\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.\n\n\n\n\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.","answer_url":"https://scicomp.stackexchange.com/a/45328","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-05T07:08:57+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2026-01-05T07:08:57+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"E5705B06-7DAC-4324-A752-C8064C49BB6C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}],"score":3,"updated_at":"2026-01-05T07:08:57+00:00"},{"answer_html":"

Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.

\n","answer_id":45348,"answer_text":"Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.","answer_url":"https://scicomp.stackexchange.com/a/45348","author":"Donte Lightfoot","author_url":"https://scicomp.stackexchange.com/users/56387/donte-lightfoot","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-22T23:46:46+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Donte Lightfoot","profile_url":"https://scicomp.stackexchange.com/users/56387/donte-lightfoot","user_type":"registered"},"created_at":"2026-01-22T23:46:46+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"790DF00C-3B67-42CD-A314-653CD46193C9","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}],"score":2,"updated_at":"2026-01-22T23:46:46+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Wolfgang Bangerth","author_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Wolfgang Bangerth","profile_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","user_type":"registered"},"created_at":"2026-01-03T02:46:44+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-23T14:37:58+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B49E063C-3F0D-471B-956C-B179F2F73567","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45327"},{"author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2026-01-05T07:08:57+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"E5705B06-7DAC-4324-A752-C8064C49BB6C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45328"},{"author":"Donte Lightfoot","author_url":"https://scicomp.stackexchange.com/users/56387/donte-lightfoot","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Donte Lightfoot","profile_url":"https://scicomp.stackexchange.com/users/56387/donte-lightfoot","user_type":"registered"},"created_at":"2026-01-22T23:46:46+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"790DF00C-3B67-42CD-A314-653CD46193C9","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45348"}],"question_author":"Anwesh Saha","question_author_url":"https://scicomp.stackexchange.com/users/56260/anwesh-saha"},"code_blocks":[{"block_index":0,"code_text":"class PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n","post_id":"scicomp:45326","sha256":"72f89f4e70a0d9ea27afa54ad378f9c4e2b0812f96becf4acbd8f7ebf0cc9b85","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"},{"block_index":1,"code_text":"def df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n","post_id":"scicomp:45326","sha256":"b2d3d4f6e01670c9cb767d689a925772aaee0c1b9223facf411446def617adca","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"},{"block_index":2,"code_text":"class Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n","post_id":"scicomp:45326","sha256":"1a915d175651e4b9f9655e9ec1c9264bc3f1f929f0579d7c759eeba08ce30194","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"},{"block_index":3,"code_text":"def train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n","post_id":"scicomp:45326","sha256":"c7d15b6e7e7d62ba263632f66347f76b266d871b1ee7544ec9e25530d170018b","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"},{"block_index":4,"code_text":"def create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n","post_id":"scicomp:45326","sha256":"9ad8906458885f3d360ec2d77e3f1ad1f6ff1f533262564103a2e6f6d9b8174e","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"072d14733ba8045905359381e1cf881bffaf739b2320cd68f04dd7711f01c725","id":"SCT-779166321a9751e13d72e0ca","language":null,"library_or_tool":["pytorch"],"problem_text":"I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.\n\n\n\n\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.\n\n\n\n\n[image: output GIF; source: https://i.sstatic.net/9QczcfVK.gif] (https://i.sstatic.net/9QczcfVK.gif)\n\n\n\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/IMsKTvWk.png] (https://i.sstatic.net/IMsKTvWk.png)\n\n\n\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$\n\n\n\n\nwhere:\n\n\n\n\n\n(c = 1)\n\n\n\n\n(f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence\n\n\n\n\n\nInitial conditions:\n\n\n\n\n\n(u(x,y,0) = 0)\n\n\n\n\n$\\partial_t u(x,y,0) = 0$\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nFirst-order absorbing (Sommerfeld):\n\n\n\n\n\n$\\partial_t u + c\\,\\partial_n u = 0$\n\n\n\n\n\nThe wavefronts don't make much sense\n\n\n\n\n\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\n\n\n\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\n\n\n\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\n\n\n\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\n\n\n\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\n\n\n\n\n\n\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer\n\n\n\n\n\n\n\n\n\nActivation: sin\n\n\n\n\n\n\n\n\n\nTraining:\n\n\n\n\n\nAdam optimizer (20k epochs)\n\n\n\n\nLBFGS refinement\n\n\n\n\n\n\n\n\n\n\nCollocation points:\n\n\n\n\n\nUniform tensor-product grid in (x, y, t)\n\n\n\n\n\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nImplemented via additional loss terms using autograd\n\n\n\n\n\n\n\n\n\n\nVisualization:\n\n\n\n\n\nPINN evaluated on a dense grid and animated with Matplotlib\n\n\n\n\n\n\n\n\n\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.\n\n\n\n\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.","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":"Anwesh Saha","profile_url":"https://scicomp.stackexchange.com/users/56260/anwesh-saha","user_type":"registered"},"created_at":"2026-01-01T19:29:53+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"48F1548B-237A-4E64-9D2B-23708297897F","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/48F1548B-237A-4E64-9D2B-23708297897F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-02T05:44:50+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"F9E6ED4E-E272-4959-AB38-6016CEED48E6","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F9E6ED4E-E272-4959-AB38-6016CEED48E6/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Anwesh Saha","profile_url":"https://scicomp.stackexchange.com/users/56260/anwesh-saha","user_type":"registered"},"created_at":"2026-01-02T05:49:23+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"D31A0254-33EE-4DC9-BC16-D05905CA3663","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D31A0254-33EE-4DC9-BC16-D05905CA3663/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Anwesh Saha","profile_url":"https://scicomp.stackexchange.com/users/56260/anwesh-saha","user_type":"registered"},"created_at":"2026-01-02T06:00:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"C90C675C-FD01-4F7F-8343-47D3A101E2AF","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C90C675C-FD01-4F7F-8343-47D3A101E2AF/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-01-03T11:41:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"C6534CC8-3DAF-4FF7-918C-DDE4C08B9232","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/C6534CC8-3DAF-4FF7-918C-DDE4C08B9232/view-source"}],"source_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":"45326","source_record_sha256":"42c2cd2a0c6a386d1fb9f33ff03ed096caddd11083e16568f30bcb110cbb524d","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.

\n

I would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.

\n

\"output

\n

Training details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):

\n

\"enter

\n

$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$

\n

where:

\n
    \n
  • (c = 1)
  • \n
  • (f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence
  • \n
\n

Initial conditions:

\n
    \n
  • (u(x,y,0) = 0)
  • \n
  • $\\partial_t u(x,y,0) = 0$
  • \n
\n

Boundary conditions:

\n
    \n
  • First-order absorbing (Sommerfeld):
  • \n
\n

$\\partial_t u + c\\,\\partial_n u = 0$

\n
    \n
  • The wavefronts don't make much sense
  • \n
\n
class PINN(nn.Module):\n    def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n        super().__init__()\n        self.layer_in = nn.Linear(3, dim_hidden)\n        self.layer_out = nn.Linear(dim_hidden, 1)\n        self.middle_layers = nn.ModuleList([\n            nn.Linear(dim_hidden, dim_hidden)\n            for _ in range(num_hidden - 1)\n        ])\n        self.act = act\n\n    def forward(self, x, y, t):\n        z = torch.cat([x, y, t], dim=1)\n        z = self.act(self.layer_in(z))\n        for layer in self.middle_layers:\n            z = self.act(layer(z))\n        return self.layer_out(z)\n
\n
def df(output, input, order=1):\n    v = output\n    for _ in range(order):\n        v = torch.autograd.grad(\n            v, input,\n            grad_outputs=torch.ones_like(input),\n            create_graph=True,\n            retain_graph=True\n        )[0]\n    return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n    return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n    return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n    return df(pinn(x, y, t), y, order)\n
\n
class Loss:\n    def residual_loss(self, pinn):\n        # Wave equation residual\n        return ...\n\n    def initial_loss(self, pinn):\n        # u(x,y,0)=0 and du/dt(x,y,0)=0\n        return ...\n\n    def boundary_loss(self, pinn):\n        # Absorbing (Sommerfeld) BC\n        # dudt + c * du/dn = 0\n        return ...\n
\n
def train_model(pinn, loss_fn):\n    # Adam phase\n    # LBFGS phase\n    return pinn\n
\n
def create_wave_animation(pinn):\n    # Evaluate PINN on grid and animate\n    pass\n
\n
    \n
  • Network: fully-connected MLP, 4 hidden layers, 80 neurons per layer

    \n
  • \n
  • Activation: sin

    \n
  • \n
  • Training:

    \n
      \n
    • Adam optimizer (20k epochs)
    • \n
    • LBFGS refinement
    • \n
    \n
  • \n
  • Collocation points:

    \n
      \n
    • Uniform tensor-product grid in (x, y, t)
    • \n
    \n
  • \n
  • Boundary conditions:

    \n
      \n
    • Implemented via additional loss terms using autograd
    • \n
    \n
  • \n
  • Visualization:

    \n
      \n
    • PINN evaluated on a dense grid and animated with Matplotlib
    • \n
    \n
  • \n
\n

I expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.

\n

Any insight into numerical, architectural, or formulation issues would be greatly appreciated.

\n","question_title":"Physics-Informed Neural Network for 2D Wave Equation Produces Non-Circular / Distorted Wavefronts","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45335,"score":3},{"answer_id":45337,"score":0},{"answer_id":45341,"score":2},{"answer_id":45342,"score":1}],"answers":[{"answer_html":"
\n

monothonic

\n
\n

I'm sure you meant monotonic.

\n
\n

I am looking for a fast way to solve the problem

\n
\n

Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:

\n
    \n
  • Linear, not quadratic
  • \n
  • No manual iteration per se
  • \n
  • Enforce inter-reference monotonicity through simple linear constraints
  • \n
  • Model cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight
  • \n
\n

A traditional LP would express the problem thus. Define the following decision vectors:

\n
    \n
  • $z \\in \\mathbb R^n$, the fit points
  • \n
  • $z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error
  • \n
  • $z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error
  • \n
  • $d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials
  • \n
  • $d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials
  • \n
\n

Find

\n

$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$

\n

given the following constraints:

\n

$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$

\n

$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$

\n

The problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.

\n
import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n    np.ndarray, np.ndarray, np.ndarray,\n]:\n    x = np.linspace(start=0, stop=10, num=n)\n    y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n    iref = np.array((2, 6, 9))*(n//10)\n    return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n    return np.concatenate((\n        np.zeros(n),   # z does not incur a cost directly\n        np.ones(2*n),  # zerr cost\n        np.full(2*nd, fill_value=smoothing),\n    ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n    lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n    lbound[:n] = -np.inf\n    ubound[:] = np.inf\n\n    iprev = iref[:-1]\n    inext = iref[1:]\n    pprev = y[iprev]\n    pnext = y[inext]\n    pfloor = np.minimum(pprev, pnext)\n    pceil = np.maximum(pprev, pnext)\n\n    for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n        lbound[i0] = y[i0]\n        ubound[i0] = y[i0]\n        inner = slice(i0 + 1, i1)\n        lbound[inner] = plo\n        ubound[inner] = phi\n    lbound[iref[-1]] = y[iref[-1]]\n    ubound[iref[-1]] = y[iref[-1]]\n\n    return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n    # zep >= z - y:  z - zep <= y\n    # zen >= y - z:  z + zen >= y\n    eye = sp.eye_array(n)\n    zero = sp.csc_array((n, n))\n    zerond = sp.csc_array((n, 2*nd))\n    pos = LinearConstraint(\n        A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n    neg = LinearConstraint(\n        A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n    return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n    # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n    # d2p >=  d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n    # d2n >= -d2z/dt2:  z[i] - 2z[i+1] + z[i+2] +0 +0 +   0 + d2n >= 0\n    data = np.broadcast_to(\n        np.array(([1], [-2], [1]), dtype=np.float32),  # don't bother with /dt**2\n        shape=(3, n))\n    offsets = np.array((0, 1, 2), dtype=np.int32)\n    kernel = sp.dia_array((data, offsets), shape=(nd, n))\n    err_zero = sp.csc_array((nd, 2*n))\n    eye = sp.eye_array(nd)\n    zero = sp.csc_array((nd, nd))\n    pos = LinearConstraint(\n        A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n    neg = LinearConstraint(\n        A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n    return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n    iprev = iref[:-1]\n    inext = iref[1:]\n    yprev = y[iprev]\n    ynext = y[inext]\n    blocks = []\n\n    for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n        sign = np.sign(y1 - y0)\n        if sign == 0:\n            continue  # the entire segment will already have lower and upper bounds equal to each other\n        block = sp.eye_array(\n            m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n        ) - sp.eye_array(\n            m=i1 - i0, n=3*n + 2*nd, k=i0)\n        blocks.append(sign*block)\n    constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n    return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n    np.ndarray, tuple[LinearConstraint, ...],\n]:\n    '''\n    Variables:\n        z, continuous unbounded (outside of ref points)\n        zep, continuous, >= 0, >= z-y\n        zen, continuous, >= 0, >= y-z\n        d2p, n-2, continuous, >= 0, >= d2z/dt2\n        d2n, n-2, continuous, >= 0, >= -d2z/dt2\n    '''\n    n = y.size\n    nd = n - 2\n    constraints = (\n        zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n    )\n\n    result = milp(\n        c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n        constraints=constraints,\n    )\n    if not result.success:\n        raise result.message\n    z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n    return z, constraints\n\n\ndef demo() -> None:\n    rand = np.random.default_rng(seed=0)\n    x, y, iref = sample_data(rand, n=801)\n\n    fig, ax = plt.subplots()\n    ax.plot(x, y, label='orig')\n    ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n    for smoothing in (0.5, 3):\n        z, constraints = solve(y, iref, smoothing)\n        ax.plot(x, z, label=f'smooth={smoothing}')\n    ax.legend()\n\n    sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n    fig, ax = plt.subplots()\n    ax.set_title(f'Constraint sparsity, n={y.size}')\n    ax.imshow(sparsity)\n\n    plt.show()\n\n\nif __name__ == '__main__':\n    demo()\n
\n

Here we see that the solution does exactly what we tell it to:

\n

\"example

\n

Outside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:

\n

\"smoothing\"

\n

The sparsity pattern for the problem looks like this (size reduced for visibility):

\n

\"sparsity\"

\n

Though the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.

\n","answer_id":45335,"answer_text":"monothonic\n\n\n\n\n\n\n\nI'm sure you meant monotonic.\n\n\n\n\n\n\n\nI am looking for a fast way to solve the problem\n\n\n\n\n\n\n\nAre you actually? I think if you were, you would use something off-the-shelf. \"Simple iterative\" and \"fast\" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:\n\n\n\n\n\nLinear, not quadratic\n\n\n\n\nNo manual iteration per se\n\n\n\n\nEnforce inter-reference monotonicity through simple linear constraints\n\n\n\n\nModel cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight\n\n\n\n\n\nA traditional LP would express the problem thus. Define the following decision vectors:\n\n\n\n\n\n$z \\in \\mathbb R^n$, the fit points\n\n\n\n\n$z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error\n\n\n\n\n$z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error\n\n\n\n\n$d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials\n\n\n\n\n$d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials\n\n\n\n\n\nFind\n\n\n\n\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$\n\n\n\n\ngiven the following constraints:\n\n\n\n\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$\n\n\n\n\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$\n\n\n\n\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\nHere we see that the solution does exactly what we tell it to:\n\n\n\n\n[image: example solution; source: https://i.sstatic.net/oTyX0oWA.png] (https://i.sstatic.net/oTyX0oWA.png)\n\n\n\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:\n\n\n\n\n[image: smoothing; source: https://i.sstatic.net/cW1t1avg.png] (https://i.sstatic.net/cW1t1avg.png)\n\n\n\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):\n\n\n\n\n[image: sparsity; source: https://i.sstatic.net/UmVF5qyE.png] (https://i.sstatic.net/UmVF5qyE.png)\n\n\n\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.","answer_url":"https://scicomp.stackexchange.com/a/45335","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-10T07:56:42+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45334,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T07:56:42+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"49224026-A98C-4DFC-B187-28324764F758","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T15:16:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"0462867C-327F-469E-957B-1FE451F4CE5C","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T20:00:35+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"302EF20B-4729-4185-A059-5377ED4B7555","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}],"score":3,"updated_at":"2026-01-10T20:00:35+00:00"},{"answer_html":"

I managed to create a prototype solver based on ADMM in MATLAB:

\n
function [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n    vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n    mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n    paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n    vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n    mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n    sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n    sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n    sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n    sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n    sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n    sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n    vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n    isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq      = length(vI);\nnumInEq    = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho     = sParams.paramRho;\nparamRhoInv  = inv(paramRho);\nnumIter      = sParams.numIter;\nepsAbs       = sParams.epsAbs;\nepsRel       = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau     = sParams.paramTau;\n\n% ADMM Variables\nvX  = vY;                %<! Optimization variable\nvS  = zeros(numInEq, 1); %<! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %<! Preious iteration buffer\nvMu = zeros(numInEq, 1); %<! Dual variable for inequality\nvNu = zeros(numEq, 1);   %<! Dual variabe for equality\n\n% Factorize the KKT System\n% (Q + rho * A' * A + rho * E' * E) * z = r\nmK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\nsK = decomposition(mK, 'chol', 'CheckCondition', false);\n\nisConv     = false;\nupdatedRho = false;\n\nfor ii = 1:numIter\n    vS1(:) = vS; %<! Previous iteration\n\n    % Solve the Linear System\n    vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %<! Right hand vector\n    vX = sK \\ vR;\n\n    % Proximal / Projection Step\n    % s = -A * z with s >= 0\n    vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n    % Update Dual Variables\n    vMu = vMu + paramRho * (mA * vX + vS);\n    vNu = vNu + paramRho * (mE * vX - vD);\n\n    % Check Convergence\n    if mod(ii, convInterval) == 0\n        primRes = norm(mA * vX + vS, 'inf');\n        dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n        if ((primRes < epsAbs) && (dualRes < epsAbs))\n            isConv = true;\n            break;\n        end\n\n        % Adpat `paramRho`\n        resRatio = primRes / dualRes;\n        % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n        % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n        if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n            updatedRho = true;\n        else\n            updatedRho = false;\n        end\n        if updatedRho\n            paramRho = paramRho * sqrt(resRatio);\n            paramRho = clip(paramRho, 1e-5, 1e5);\n            paramRhoInv  = inv(paramRho);\n            mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n            sK = decomposition(mK, 'chol', 'CheckCondition', false);\n        end\n    end\n\nend\n\nend\n
\n

I has convergence check and adaptation of the ADMM's step size parameter $\\rho$.
\nI will add mathematical formulation and a memory optimized version using Julia.

\n

On MATLAB with this naive code I could beat quadprog() by 30% with the same output:

\n

\"enter

\n\n","answer_id":45337,"answer_text":"I managed to create a prototype solver based on ADMM in MATLAB:\n\n\n\n\nfunction [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n\n\n\n\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.\n\nI will add mathematical formulation and a memory optimized version using Julia.\n\n\n\n\nOn MATLAB with this naive code I could beat quadprog() by 30% with the same output:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/VC8uzUSt.png] (https://i.sstatic.net/VC8uzUSt.png)","answer_url":"https://scicomp.stackexchange.com/a/45337","author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-10T16:53:59+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45334,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-10T16:53:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"62C943AA-9B1D-4A55-BEE1-9F975532FF13","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/62C943AA-9B1D-4A55-BEE1-9F975532FF13/view-source"}],"score":0,"updated_at":"2026-01-10T16:53:59+00:00"},{"answer_html":"

I produced an ADMM based solver which I found very efficient.

\n

The problem is given by:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$

\n

I will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.
\nThe equality constraints can be turned into matrix form and the problem becomes:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$

\n

The trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$

\n

The equality constraints are introduced by the Augmented Lagrangian:

\n

$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$

\n

The steps to solve:

\n
    \n
  • Primal Update (Solve Linear System): $\\boldsymbol{x}^{ \\left( k + 1 \\right)} = {\\left( \\boldsymbol{I} + \\lambda \\boldsymbol{D}^{\\top} \\boldsymbol{D} + \\rho \\boldsymbol{A}^{\\top} \\boldsymbol{A} + \\rho\\boldsymbol{E}^{\\top} \\boldsymbol{E} \\right)}^{-1} \\left( \\boldsymbol{y} - \\boldsymbol{A}^{\\top} \\left( \\rho \\boldsymbol{s}^{\\left( k \\right)} + \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) + \\boldsymbol{E}^{\\top} \\left( \\rho \\boldsymbol{d} - \\boldsymbol{\\nu}^{\\left( k \\right)} \\right) \\right)$.
  • \n
  • Slack Update (Non Negative LS): $\\boldsymbol{s}^{ \\left( k + 1 \\right)} = \\max \\left( \\boldsymbol{0}, - \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} - {\\rho}^{-1} \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.
  • \n
  • Dual Update (Gradient Ascent) for $\\boldsymbol{\\mu}$: $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} \\right)$.
  • \n
  • Dual Update (Gradient Ascent) for $\\boldsymbol{\\nu}$: $\\boldsymbol{\\nu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\nu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{E} \\boldsymbol{x}^{\\left( k + 1 \\right)} - \\boldsymbol{d} \\right)$.
  • \n
\n

The stopping condition is when both residuals are below a threshold:

\n
    \n
  • Primal Residual: ${r}^{\\left( k \\right)} = {\\left\\| \\boldsymbol{A} \\boldsymbol{x}^{\\left( k \\right)} + \\boldsymbol{s}^{\\left( k \\right)} \\right\\|}_{\\infty}$.
  • \n
  • Dual Residual (OSQP Style): ${s}^{\\left( k \\right)} = {\\left\\| \\rho \\boldsymbol{A} \\left( \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{s}^{\\left( k - 1 \\right)} \\right) \\right\\|}_{\\infty}$.
  • \n
\n

The use of the infinity norm decouples the dimension of the problem from the thresholds.

\n

I also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.

\n

I implemented all in Julia and compared to the ECOS / SCS solvers wrapped by Convex.jl.

\n

\"enter

\n

Run Times:

\n
    \n
  • ECOS
  • \n
\n
BenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max):  3.412 ms …  18.615 ms  ┊ GC (min … max): 0.00% … 60.46%\n Time  (median):     3.807 ms               ┊ GC (median):    0.00%\n Time  (mean ± σ):   4.061 ms ± 859.845 μs  ┊ GC (mean ± σ):  1.67% ±  5.36%\n\n   ▅█▇▄▃ ▁\n  ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n  3.41 ms         Histogram: frequency by time        6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n
\n
    \n
  • SCS
  • \n
\n
BenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max):  49.280 ms …  53.704 ms  ┊ GC (min … max): 0.00% … 0.00%\n Time  (median):     50.892 ms               ┊ GC (median):    0.00%\n Time  (mean ± σ):   51.055 ms ± 918.217 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%\n\n       ▁        ▃ ▁▁▁█ █▃ ▁ ▃ ▁   ▆   ▁           ▁\n  ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n  49.3 ms         Histogram: frequency by time         53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n
\n
    \n
  • ADMM (My code):
  • \n
\n
BenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max):  447.700 μs …  23.329 ms  ┊ GC (min … max): 0.00% … 70.82%\n Time  (median):     651.300 μs               ┊ GC (median):    0.00%\n Time  (mean ± σ):   656.690 μs ± 412.333 μs  ┊ GC (mean ± σ):  1.30% ±  2.26%\n\n   ▁▄▄▁            ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n  ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n  448 μs           Histogram: frequency by time          970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n
\n

The ADMM method is an order of magnitude faster than the generic solvers.
\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.

\n
\n

The code is available on my StackExchange Code GitHub Repository (Look at the ComputationalScience\\Q45334 folder).

\n","answer_id":45341,"answer_text":"I produced an ADMM based solver which I found very efficient.\n\n\n\n\nThe problem is given by:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.\n\nThe equality constraints can be turned into matrix form and the problem becomes:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nThe equality constraints are introduced by the Augmented Lagrangian:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}^{ \\left( k + 1 \\right)} = {\\left( \\boldsymbol{I} + \\lambda \\boldsymbol{D}^{\\top} \\boldsymbol{D} + \\rho \\boldsymbol{A}^{\\top} \\boldsymbol{A} + \\rho\\boldsymbol{E}^{\\top} \\boldsymbol{E} \\right)}^{-1} \\left( \\boldsymbol{y} - \\boldsymbol{A}^{\\top} \\left( \\rho \\boldsymbol{s}^{\\left( k \\right)} + \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) + \\boldsymbol{E}^{\\top} \\left( \\rho \\boldsymbol{d} - \\boldsymbol{\\nu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS): $\\boldsymbol{s}^{ \\left( k + 1 \\right)} = \\max \\left( \\boldsymbol{0}, - \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} - {\\rho}^{-1} \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent) for $\\boldsymbol{\\mu}$: $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent) for $\\boldsymbol{\\nu}$: $\\boldsymbol{\\nu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\nu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{E} \\boldsymbol{x}^{\\left( k + 1 \\right)} - \\boldsymbol{d} \\right)$.\n\n\n\n\n\nThe stopping condition is when both residuals are below a threshold:\n\n\n\n\n\nPrimal Residual: ${r}^{\\left( k \\right)} = {\\left\\| \\boldsymbol{A} \\boldsymbol{x}^{\\left( k \\right)} + \\boldsymbol{s}^{\\left( k \\right)} \\right\\|}_{\\infty}$.\n\n\n\n\nDual Residual (OSQP Style): ${s}^{\\left( k \\right)} = {\\left\\| \\rho \\boldsymbol{A} \\left( \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{s}^{\\left( k - 1 \\right)} \\right) \\right\\|}_{\\infty}$.\n\n\n\n\n\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.\n\n\n\n\nI also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.\n\n\n\n\nI implemented all in Julia and compared to the ECOS (https://github.com/embotech/ecos) / SCS (https://github.com/cvxgrp/scs) solvers wrapped by Convex.jl (https://github.com/jump-dev/Convex.jl).\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/f5YcjFm6.png] (https://i.sstatic.net/f5YcjFm6.png)\n\n\n\n\nRun Times:\n\n\n\n\n\nECOS\n\n\n\n\n\nBenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n\n\n\n\n\n\nSCS\n\n\n\n\n\nBenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n\n\n\n\n\n\nADMM (My code):\n\n\n\n\n\nBenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n\n\n\n\n\nThe ADMM method is an order of magnitude faster than the generic solvers.\n\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.\n\n\n\n\n\n\n\nThe code is available on my StackExchange Code GitHub Repository (https://github.com/RoyiAvital/StackExchangeCodes) (Look at the ComputationalScience\\Q45334 folder).","answer_url":"https://scicomp.stackexchange.com/a/45341","author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-17T09:49:49+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45334,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-17T09:49:49+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"00755B30-2CCE-4266-8BA0-1A21879D0A39","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/00755B30-2CCE-4266-8BA0-1A21879D0A39/view-source"}],"score":2,"updated_at":"2026-01-17T09:49:49+00:00"},{"answer_html":"

Another formulation take advantage of the equality constraint to make the problem formulation smaller.

\n

The problem is given by:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$

\n

Let $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:

\n

$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$

\n

Then the above can be formulated as:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$

\n

Where $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.

\n

This formulation reduces the number of constraints to handle.
\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.

\n

The Augmented Lagrangian (Scaled form) is given by:

\n

$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$

\n

The steps to solve:

\n
    \n
  • Primal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.
  • \n
  • Slack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.
  • \n
  • Dual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.
  • \n
\n

The rest is similar to above with the needed adjustments for the residuals calculations.

\n

This implementation reduced another 40 [Micro Sec] of the run time.

\n","answer_id":45342,"answer_text":"Another formulation take advantage of the equality constraint to make the problem formulation smaller.\n\n\n\n\nThe problem is given by:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:\n\n\n\n\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$\n\n\n\n\nThen the above can be formulated as:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.\n\n\n\n\nThis formulation reduces the number of constraints to handle.\n\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.\n\n\n\n\nThe Augmented Lagrangian (Scaled form) is given by:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.\n\n\n\n\n\nThe rest is similar to above with the needed adjustments for the residuals calculations.\n\n\n\n\nThis implementation reduced another 40 [Micro Sec] of the run time.","answer_url":"https://scicomp.stackexchange.com/a/45342","author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-17T12:18:23+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45334,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-17T12:18:23+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}],"score":1,"updated_at":"2026-01-17T12:18:23+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T07:56:42+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"49224026-A98C-4DFC-B187-28324764F758","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T15:16:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"0462867C-327F-469E-957B-1FE451F4CE5C","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T20:00:35+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"302EF20B-4729-4185-A059-5377ED4B7555","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45335"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-10T16:53:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"62C943AA-9B1D-4A55-BEE1-9F975532FF13","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/62C943AA-9B1D-4A55-BEE1-9F975532FF13/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45337"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-17T09:49:49+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"00755B30-2CCE-4266-8BA0-1A21879D0A39","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/00755B30-2CCE-4266-8BA0-1A21879D0A39/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45341"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-17T12:18:23+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45342"}],"question_author":"Royi","question_author_url":"https://scicomp.stackexchange.com/users/7951/royi"},"code_blocks":[{"block_index":0,"code_text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n","post_id":45335,"sha256":"57aac7578bb6f741268023073e8caf04782e2d1a8ebdc92d20507478f02d64b4","source_url":"https://scicomp.stackexchange.com/a/45335"},{"block_index":0,"code_text":"function [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n","post_id":45337,"sha256":"535fd63b99697fb569289a64746583e07c5d7d903898e20406ca04bde8aa5841","source_url":"https://scicomp.stackexchange.com/a/45337"},{"block_index":0,"code_text":"BenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n","post_id":45341,"sha256":"0b2e3243787f36b7a4743ea4db41186e03b8103ddb44694d08359b124a402f78","source_url":"https://scicomp.stackexchange.com/a/45341"},{"block_index":1,"code_text":"BenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n","post_id":45341,"sha256":"71a1c78a3d594c714e47b549671ad205a39c588397342cd1222d7f0374ee212d","source_url":"https://scicomp.stackexchange.com/a/45341"},{"block_index":2,"code_text":"BenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n","post_id":45341,"sha256":"cc617c32c3d824167c364bca08e08e70d29fa3d5e2cbafd454d004adf007d6dd","source_url":"https://scicomp.stackexchange.com/a/45341"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"15b9f73a0305336f8096de53cbd97ad5337151fb87b189a74bb035a849536f87","id":"SCT-446896929ffe977e1e13a64c","language":null,"library_or_tool":null,"problem_text":"Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.\n\n\n\n\nI want to smooth the curve with the following properties:\n\n\n\n\n\nThe result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.\n\n\n\n\nFor a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.\n\n\n\n\nThe smoothed values between 2 reference points must be monotonic.\n\n\n\n\n\nI came up with the following model:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.\n\n\n\n\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.\n\n\n\n\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.","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":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-09T11:12:06+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"47824E2B-27A9-4037-A643-E3F6522A8C95","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/47824E2B-27A9-4037-A643-E3F6522A8C95/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-09T11:26:36+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-10T07:58:10+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"2599F6AB-3F4E-455C-9665-0A36994C9F01","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2599F6AB-3F4E-455C-9665-0A36994C9F01/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-01-10T17:02:45+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"DE676BCF-D21E-4A19-B947-DB9D0FD71DA6","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/DE676BCF-D21E-4A19-B947-DB9D0FD71DA6/view-source"}],"source_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":"45334","source_record_sha256":"359b817cdb7eb4f25a65d862cad899ed03718f46a543f10119a7061fcbb05a16","source_url":"https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.

\n

I want to smooth the curve with the following properties:

\n
    \n
  1. The result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.
  2. \n
  3. For a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.
  4. \n
  5. The smoothed values between 2 reference points must be monotonic.
  6. \n
\n

I came up with the following model:

\n

$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$

\n

Where $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.

\n

I am looking for a fast way to solve the problem for the case of 50-1500 samples.

\n

I rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.

\n","question_title":"Solving Regularized Least Squares with Linear Equality and Linear Inequality Constraints for Curve Smoothing","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con","split":"test"} {"accepted_answer":{"answer_html":"

Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n\"Expected

\n","answer_id":45345,"answer_text":"Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n[image: Expected phase diagram for magnetization; source: https://i.sstatic.net/BHts2usz.png] (https://i.sstatic.net/BHts2usz.png)","answer_url":"https://scicomp.stackexchange.com/a/45345","author":"Andreas Christophilopoulos","author_url":"https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-20T08:42:22+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45344,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Andreas Christophilopoulos","profile_url":"https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos","user_type":"registered"},"created_at":"2026-01-20T08:42:22+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"48A405D5-BF35-4435-851C-8D73362C5805","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/48A405D5-BF35-4435-851C-8D73362C5805/view-source"}],"score":3,"updated_at":"2026-01-20T08:42:22+00:00"},"answer_scores":[{"answer_id":45345,"score":3}],"answers":[{"answer_html":"

Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n\"Expected

\n","answer_id":45345,"answer_text":"Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n[image: Expected phase diagram for magnetization; source: https://i.sstatic.net/BHts2usz.png] (https://i.sstatic.net/BHts2usz.png)","answer_url":"https://scicomp.stackexchange.com/a/45345","author":"Andreas Christophilopoulos","author_url":"https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-20T08:42:22+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45344,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Andreas Christophilopoulos","profile_url":"https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos","user_type":"registered"},"created_at":"2026-01-20T08:42:22+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"48A405D5-BF35-4435-851C-8D73362C5805","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/48A405D5-BF35-4435-851C-8D73362C5805/view-source"}],"score":3,"updated_at":"2026-01-20T08:42:22+00:00"}],"attempted_method_if_explicit":"I tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5 σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel=\"J\", ylabel=\"g\", title=\"Magnetization M(g, J)\")\n","post_id":"scicomp:45344","sha256":"6d0c731a6161c6549a7907a370d22e309f0185f732b83d7612acffee8fc728e4","source_url":"https://scicomp.stackexchange.com/questions/45344/dmrg-returns-weird-results-for-the-tfim-ground-state-magnetization"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"5592f4add4e98a2feec581886f97c580c1df7f2c2c354b4b2e5c355bf7b6cb40","id":"SCT-d8f43872b8259c5bc610e13d","language":null,"library_or_tool":null,"problem_text":"If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.\n\n\n\n\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5 σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel=\"J\", ylabel=\"g\", title=\"Magnetization M(g, J)\")\n\n\n\n\n\nAnd here is the resulting heatmap:\n\n\n\n\n[image: heatmap; source: https://i.sstatic.net/82wynbiT.png] (https://i.sstatic.net/82wynbiT.png)\n\n\n\n\nI tried increasing the bond dimension $D$, but it did nothing. Now, this is VUMPS, but I got the same result more or less with finite $L$ DMRG. I'm at my wit's end! Any help would be appreciated.","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":"Andreas Christophilopoulos","profile_url":"https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos","user_type":"registered"},"created_at":"2026-01-19T13:26:44+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9A79D116-A5E8-4995-9CDC-86061D8C4F49","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9A79D116-A5E8-4995-9CDC-86061D8C4F49/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Andreas Christophilopoulos","profile_url":"https://scicomp.stackexchange.com/users/56337/andreas-christophilopoulos","user_type":"registered"},"created_at":"2026-01-19T14:39:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"17008AF4-25DE-4356-9CA5-A73B1EB6B8C6","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/17008AF4-25DE-4356-9CA5-A73B1EB6B8C6/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-21T20:16:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"D0303D22-34B4-4CE9-B587-04FCADC6EBF4","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D0303D22-34B4-4CE9-B587-04FCADC6EBF4/view-source"}],"source_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":"45344","source_record_sha256":"0cdb23502e19bb17f6453ca16197b1acd5ef11fb6f84264a2d5a5ebbd88c19df","source_url":"https://scicomp.stackexchange.com/questions/45344/dmrg-returns-weird-results-for-the-tfim-ground-state-magnetization","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.

\n

I tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5<g<0.5$. In other words, it doesn't matter how strong or weak $J$ is (as long as it is positive), there is always ferromagnetic order as long as $|g|$ is smaller than $0.5$, and $M=0$ everywhere else.

\n

This is a very odd result that doesn't make sense to me, so I am inclined to believe there is something wrong with my computational methods. I attach the code I used and the diagram that it produced. My code closely mirrors the example from MPSKit.jl's github:

\n
using MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n    H = transverse_field_ising(; J=J, g=g)\n    groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n    return abs(expectation_value(groundstate, 1 => σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n        xlabel="J", ylabel="g", title="Magnetization M(g, J)")\n
\n

And here is the resulting heatmap:

\n

\"heatmap\"

\n

I tried increasing the bond dimension $D$, but it did nothing. Now, this is VUMPS, but I got the same result more or less with finite $L$ DMRG. I'm at my wit's end! Any help would be appreciated.

\n","question_title":"DMRG returns weird results for the TFIM ground state magnetization","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45344/dmrg-returns-weird-results-for-the-tfim-ground-state-magnetization","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45394,"score":2}],"answers":[{"answer_html":"

The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)

\n

I'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}

\n

I'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.

\n

By using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}

\n

Then by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.

\n

Code example

\n

By applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:

\n
import numpy as np\n\ndef integrate_tabulated(f, a, b):\n    xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n    wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n    # Map points from [-1, 1] to [a, b]\n    x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n    w_mapped = wi * 0.5 * (b - a)\n    return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f"Numerical Result: {result:.10f}")\n# Result from WolframAlpha = 0.0187983\n
\n","answer_id":45394,"answer_text":"The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983","answer_url":"https://scicomp.stackexchange.com/a/45394","author":"mle","author_url":"https://scicomp.stackexchange.com/users/46538/mle","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-03-04T18:29:45+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45362,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"mle","profile_url":"https://scicomp.stackexchange.com/users/46538/mle","user_type":"registered"},"created_at":"2026-03-04T18:29:45+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"D8A9E199-F055-462B-8A0D-91FD9CE698F5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}],"score":2,"updated_at":"2026-03-04T18:29:45+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"mle","author_url":"https://scicomp.stackexchange.com/users/46538/mle","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"mle","profile_url":"https://scicomp.stackexchange.com/users/46538/mle","user_type":"registered"},"created_at":"2026-03-04T18:29:45+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"D8A9E199-F055-462B-8A0D-91FD9CE698F5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45394"}],"question_author":"vibe","question_author_url":"https://scicomp.stackexchange.com/users/28440/vibe"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983\n","post_id":45394,"sha256":"3ba14f7d8ca6fcf552a8429426a59372f6c08c1fad801078f723f57a680abda3","source_url":"https://scicomp.stackexchange.com/a/45394"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"f7408494e81e9eb9051ae7559ef4833e86037e463c68458ddae229e377925ec5","id":"SCT-a721c27a72159075f6c8a0c0","language":null,"library_or_tool":null,"problem_text":"I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.\n\n\n\n\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.\n\n\n\n\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.","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":"vibe","profile_url":"https://scicomp.stackexchange.com/users/28440/vibe","user_type":"registered"},"created_at":"2026-02-04T15:10:39+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9B775FCA-6689-4886-BE87-22C985705EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9B775FCA-6689-4886-BE87-22C985705EFF/view-source"}],"source_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":"45362","source_record_sha256":"3cd7fe0248eb0b06ff6dfe38c01b5844f594b098884eed53f61e7f1d6b236d48","source_url":"https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.

\n

My question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.

\n

The problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.

\n","question_title":"Quadrature rule for ratio of polynomials","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials","split":"holdout"} {"accepted_answer":null,"answer_scores":[{"answer_id":45441,"score":1}],"answers":[{"answer_html":"

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\"enter

\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 \n#include \n#include \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 \n#include \n#include \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":"

Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:

\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

The temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.

\n

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

\n

May 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

I tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n\"for

\n

This image is for Ra = 1e7\n\"for

\n

Here is the piece of code for calculating the temperatures

\n
    // TEMPERATURE\nvoid solveTemperature(\n    double theta[Nx + 1][Ny + 1],\n    double u[Nx + 1][Ny + 1],\n    double v[Nx + 1][Ny + 1],\n    double alpha[], double beta[],\n    double hx, double hy, double dt, double Pr, double Ra)\n{\n    double A, B, C, F;\n\n    // in x direction\n    for (int j = 1; j < Ny; j++)\n    {\n        alpha[0] = 1.0;\n        beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n        for (int i = 1; i < Nx; i++)\n        {\n            double k = 1.0 /\n                (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n            A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n            C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n            B = A + C + 1.0 / dt;\n\n            F = -theta[i][j] / dt;\n\n            alpha[i] = A / (B - C * alpha[i - 1]);\n            beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n        }\n\n        // Right wall (i = Nx) - insulated\n        // For Neumann condition on the right wall, we need a special formula\n        // Using first order: Theta[Nx] = Theta[Nx-1]\n        theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]);        // back substitution\n        for (int i = Nx - 1; i >= 0; i--)\n        {\n            theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n        }\n    }\n\n    // sweep in y direction (vertical)\n    for (int i = 1; i < Nx; i++)\n    {\n        // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n        // Using implicit scheme for Neumann condition with flux\n        double flux_bottom = -1.0;  // heat enters\n\n        alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n        beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n            (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n        // Forward sweep for interior nodes\n        for (int j = 1; j < Ny; j++)\n        {\n            double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n            double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n            double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n            double B = A + C + 1.0 / dt;\n\n            double F = -theta[i][j] / dt;\n\n            alpha[j] = A / (B - C * alpha[j - 1]);\n            beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n        }\n\n        // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n        double flux_top = 0.5;  // heat exits\n\n        // For top wall with flux, we use the relationship from the forward sweep\n        // combined with the flux condition\n        theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n        // Back substitution\n        for (int j = Ny - 1; j >= 0; j--)\n        {\n            theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n        }\n    }\n}\n
\n

Vortex solver

\n
// Omega in x direction\nvoid solveOmegaX(\n    double psi[Nx + 1][Ny + 1],\n    double theta[Nx + 1][Ny + 1],\n    double u[Nx + 1][Ny + 1],\n    double omega[Nx + 1][Ny + 1],\n    double alpha[], double beta[],\n    double hx, double dt, double Pr, double Ra)\n{\n    double A, B, C, F;\n\n    for (int j = 1; j < Ny; j++)\n    {\n        alpha[0] = 0.0; // from boundary conditions\n        beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n        for (int i = 1; i < Nx; i++)\n        {\n            double k = sqrt(Pr / Ra) /\n                (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n            A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n            C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n            B = A + C + 1.0 / dt;\n\n            F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n            alpha[i] = A / (B - C * alpha[i - 1]);\n            beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n        }\n\n        omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n        // back substitution\n        for (int i = Nx - 1; i >= 0; i--)\n            omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n    }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n    double psi[Nx + 1][Ny + 1],\n    double v[Nx + 1][Ny + 1],\n    double omega[Nx + 1][Ny + 1],\n    double alpha[], double beta[],\n    double hy, double dt, double Pr, double Ra)\n{\n    double A, B, C, F;\n\n    for (int i = 1; i < Nx; i++)\n    {\n        alpha[0] = 0.0; // bottom wall\n        beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n        for (int j = 1; j < Ny; j++)\n        {\n            double k = 1.0 /\n                (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n            A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n            C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n            B = A + C + 1.0 / dt;\n\n            F = -omega[i][j] / dt;\n\n            alpha[j] = A / (B - C * alpha[j - 1]);\n            beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n        }\n\n        omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n        // back substitution\n        for (int j = Ny - 1; j >= 0; j--)\n            omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n    }\n}\n
\n

Stream function solver

\n
// PSI equation\nvoid solvePsi(\n    double psi[Nx + 1][Ny + 1],\n    double psik[Nx + 1][Ny + 1],\n    double omega[Nx + 1][Ny + 1],\n    double hx, double hy,\n    double relax, double eps)\n{\n    double max_diff = 1.0, psi_new;\n    // This cycle from the lecture line ***\n    while (max_diff > eps)\n    {\n        max_diff = 0.0;\n\n        for (int i = 1; i < Nx; i++)\n            for (int j = 1; j < Ny; j++)\n            {\n                psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n                psi_new =\n                    (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n                        hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n                        hx * hx * hy * hy * omega[i][j]) /\n                    (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n                psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n                double diff = fabs(psi[i][j] - psik[i][j]);\n                if (diff > max_diff)\n                    max_diff = diff;\n            }\n    }\n}\n
\n

Velocity calculator

\n
// Velocities\n//  using formula \nvoid computeVelocity(\n    double psi[Nx + 1][Ny + 1],\n    double u[Nx + 1][Ny + 1],\n    double v[Nx + 1][Ny + 1],\n    double hx, double hy)\n{\n    for (int i = 1; i < Nx; i++)\n        for (int j = 1; j < Ny; j++)\n        {\n            u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n            v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n        }\n}\n
\n

Setting boundary conditions

\n
    // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n    // Boundary conditions for psi (psi=0 on all walls)\n    for (int i = 0; i <= Nx; i++)\n    {\n        psi[i][0] = 0.0;  // bottom wall\n        psi[i][Ny] = 0.0; // top wall\n    }\n    for (int j = 0; j <= Ny; j++)\n    {\n        psi[0][j] = 0.0;  // left wall\n        psi[Nx][j] = 0.0; // right wall\n    }\n}\n
\n

This is the main code

\n
#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\nconstexpr int Nx = 180;\nconstexpr int Ny = 60;\n\n        int main()\n    {\n        const double Lx = 1.5, Ly = 1.0;\n        const double hx = Lx / Nx, hy = Ly / Ny;\n        const double Pr = 0.7, Ra = 1e8, dt = 0.001;\n        const double eps = 1e-6, relax = 1.0;\n    \n        double t = 0.0, t_k = 10.0;\n    \n        static double psi[Nx + 1][Ny + 1]{}, psik[Nx + 1][Ny + 1]{}, omega[Nx + 1][Ny + 1]{};\n        static double theta[Nx + 1][Ny + 1]{}, u[Nx + 1][Ny + 1]{}, v[Nx + 1][Ny + 1]{};\n        static double alpha[(Nx > Ny ? Nx : Ny) + 1]{}, beta[(Nx > Ny ? Nx : Ny) + 1]{}; // if Nx > Ny then take Nx\n        // otherwise take Ny\n    \n        while (t < t_k)\n        {\n            applyPsiBC(psi);\n            solvePsi(psi, psik, omega, hx, hy, relax, eps);\n            computeVelocity(psi, u, v, hx, hy);\n            solveOmegaX(psi, theta, u, omega, alpha, beta, hx, dt, Pr, Ra);\n            solveOmegaY(psi, v, omega, alpha, beta, hy, dt, Pr, Ra);\n            solveTemperature(theta, u, v, alpha, beta, hx, hy, dt, Pr, Ra);\n    \n            t += dt;\n            cout << t << endl;\n        }\n    \n        // OUTPUT to files\n        ofstream fpsi("psitest.txt"), fomega("omegatest.txt"), ftheta("thetatest.txt");\n    \n        for (int i = 0; i <= Nx; i++)\n        {\n            for (int j = 0; j <= Ny; j++)\n            {\n                double x = i * hx;\n                double y = j * hy;\n                fomega << x << " " << y << " " << omega[i][j] << "\\n";\n                ftheta << x << " " << y << " " << theta[i][j] << "\\n";\n                fpsi << x << " " << y << " " << psi[i][j] << "\\n";\n            }\n        }\n    \n        cout << "Calculation completed. Files: psitest.txt, omegatest.txt, thetatest.txt\\n";\n        return 0;\n    }\n
\n","question_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":{"answer_html":"

Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.

\n

In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).

\n

Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:

\n
[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n
\n

Now $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.

\n

Once you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).

\n

Alternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:

\n

With

\n
[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n
\n

the sum becomes a standard dot product:

\n

$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$

\n

See paragraph 5 of Ogita et al. for the accurate computation of dot products.

\n
\n

References

\n

Boldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.

\n","answer_id":45388,"answer_text":"Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.","answer_url":"https://scicomp.stackexchange.com/a/45388","author":"wim","author_url":"https://scicomp.stackexchange.com/users/5286/wim","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-02-27T09:44:31+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45387,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-27T09:44:31+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"42AA8384-A67D-4B93-8A67-6F2708905EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-28T23:54:12+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"3E89E9AE-7857-41C4-8456-59AB2D1A01FD","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-02T09:09:00+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"98F99AB1-1D15-4C9A-942A-7E8E8455BA0F","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}],"score":7,"updated_at":"2026-03-02T09:09:00+00:00"},"answer_scores":[{"answer_id":45388,"score":7}],"answers":[{"answer_html":"

Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.

\n

In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).

\n

Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:

\n
[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n
\n

Now $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.

\n

Once you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).

\n

Alternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:

\n

With

\n
[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n
\n

the sum becomes a standard dot product:

\n

$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$

\n

See paragraph 5 of Ogita et al. for the accurate computation of dot products.

\n
\n

References

\n

Boldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.

\n","answer_id":45388,"answer_text":"Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.","answer_url":"https://scicomp.stackexchange.com/a/45388","author":"wim","author_url":"https://scicomp.stackexchange.com/users/5286/wim","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-02-27T09:44:31+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45387,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-27T09:44:31+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"42AA8384-A67D-4B93-8A67-6F2708905EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-28T23:54:12+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"3E89E9AE-7857-41C4-8456-59AB2D1A01FD","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-02T09:09:00+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"98F99AB1-1D15-4C9A-942A-7E8E8455BA0F","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}],"score":7,"updated_at":"2026-03-02T09:09:00+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"wim","author_url":"https://scicomp.stackexchange.com/users/5286/wim","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-27T09:44:31+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"42AA8384-A67D-4B93-8A67-6F2708905EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-28T23:54:12+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"3E89E9AE-7857-41C4-8456-59AB2D1A01FD","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-02T09:09:00+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"98F99AB1-1D15-4C9A-942A-7E8E8455BA0F","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45388"}],"question_author":"Damien","question_author_url":"https://scicomp.stackexchange.com/users/761/damien"},"code_blocks":[{"block_index":0,"code_text":"function [x, y] = ThreeProduct(a, b, c)\n","post_id":"scicomp:45387","sha256":"bd4356e06b4e83b3708b56f9d06ac35cfeedc70c4f5106650611050aae8f90f8","source_url":"https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers"},{"block_index":1,"code_text":"function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n","post_id":"scicomp:45387","sha256":"80ed3e97e5f90454b0f805d53e1135475404e4eec18ee94dae66478e44276393","source_url":"https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers"},{"block_index":0,"code_text":"[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n","post_id":45388,"sha256":"a393484e7177b2f1315a02128120a3fadec7155cf000a7d533422f66cc059f6a","source_url":"https://scicomp.stackexchange.com/a/45388"},{"block_index":1,"code_text":"[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n","post_id":45388,"sha256":"252c1cfe585024b53f664f442b4d88e29de7c5ecf18cc38270c62b8c1e562a4f","source_url":"https://scicomp.stackexchange.com/a/45388"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"776a27d62b9a31088c690973a48e3c8b12be8bcb0f699de5779c0e4fa359f7f7","id":"SCT-3d431c4e404b018d2fa696fa","language":null,"library_or_tool":null,"problem_text":"TL;DR: I am looking for a function that computes the product of three floating point numbers:\n\n\n\n\nfunction [x, y] = ThreeProduct(a, b, c)\n\n\n\n\n\nSuch that:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\n\n\n\nBackground\n\n\n\n\nOgita et al. (2005) introduced a method of computing a dot product based on \"Error Free Transformation\" primitives, such as TwoSum() (due to Knuth) and TwoProduct():\n\n\n\n\nfunction [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\n\n\n\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name \"Error Free Transformation\". That is, for TwoSum():\n\n\n\n\n$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$\n\n\n\n\nAnd for TwoProduct():\n\n\n\n\n$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$\n\n\n\n\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.\n\n\n\n\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.\n\n\n\n\nMy question is whether there is a known algorithm for the product of three floating point numbers (\"ThreeProduct()\"). That is, something where the following holds:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.\n\n\n\n\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.\n\n\n\n\n\n\n\nReferences:\n\n\n\n\nOgita, T. et al., \"Accurate Sum and Dot Product\", SIAM Journal of Scientific Computing, 2005.\n\n\n\n\nGraillat, S. \"Accurate Floating Point Product and Exponentiation (https://hal.science/hal-00164607v1)\". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.","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":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-02-27T05:27:22+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"652E8057-1F40-4128-9B15-6014E7677D14","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/652E8057-1F40-4128-9B15-6014E7677D14/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-02-27T06:42:56+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"59EECD04-2DAA-4DFE-BCE0-7030495A97DF","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/59EECD04-2DAA-4DFE-BCE0-7030495A97DF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-01T22:07:55+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"E19820FB-0C5D-448A-8B7D-D7FDF8F66E81","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E19820FB-0C5D-448A-8B7D-D7FDF8F66E81/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-01T22:16:04+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"D963AE6C-EC36-4A5E-8DC4-93C74CE72E7B","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D963AE6C-EC36-4A5E-8DC4-93C74CE72E7B/view-source"}],"source_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":"45387","source_record_sha256":"6659015f82b991d28991ce88ec3dc28890279a03077b033bd7866c8f68765698","source_url":"https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

TL;DR: I am looking for a function that computes the product of three floating point numbers:

\n
function [x, y] = ThreeProduct(a, b, c)\n
\n

Such that:

\n

$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$

\n
\n

Background

\n

Ogita et al. (2005) introduced a method of computing a dot product based on "Error Free Transformation" primitives, such as TwoSum() (due to Knuth) and TwoProduct():

\n
function [x, y] = TwoSum(a, b)\n  x = fl(a + b)\n  z = fl(x − a)\n  y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n  x = fl(a · b)\n  y = FMA(a, b, −x)\n
\n

The beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name "Error Free Transformation". That is, for TwoSum():

\n

$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$

\n

And for TwoProduct():

\n

$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$

\n

Where $\\operatorname{fl}()$ is the result of a floating point computation.

\n

Since the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.

\n

My question is whether there is a known algorithm for the product of three floating point numbers ("ThreeProduct()"). That is, something where the following holds:

\n

$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$

\n

I have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.

\n

My motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.

\n
\n

References:

\n

Ogita, T. et al., "Accurate Sum and Dot Product", SIAM Journal of Scientific Computing, 2005.

\n

Graillat, S. "Accurate Floating Point Product and Exponentiation". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.

\n","question_title":"\"Error Free Transformation\" for the product of three floating point numbers","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers","split":"train"} {"accepted_answer":{"answer_html":"

Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.

\n","answer_id":45440,"answer_text":"Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.","answer_url":"https://scicomp.stackexchange.com/a/45440","author":"FilmCoder","author_url":"https://scicomp.stackexchange.com/users/56811/filmcoder","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-05-05T05:53:32+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45396,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"FilmCoder","profile_url":"https://scicomp.stackexchange.com/users/56811/filmcoder","user_type":"registered"},"created_at":"2026-05-05T05:53:32+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"C39D8103-AD54-44E2-90A3-4461BB25C47E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}],"score":3,"updated_at":"2026-05-05T05:53:32+00:00"},"answer_scores":[{"answer_id":45440,"score":3}],"answers":[{"answer_html":"

Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.

\n","answer_id":45440,"answer_text":"Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.","answer_url":"https://scicomp.stackexchange.com/a/45440","author":"FilmCoder","author_url":"https://scicomp.stackexchange.com/users/56811/filmcoder","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-05-05T05:53:32+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45396,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"FilmCoder","profile_url":"https://scicomp.stackexchange.com/users/56811/filmcoder","user_type":"registered"},"created_at":"2026-05-05T05:53:32+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"C39D8103-AD54-44E2-90A3-4461BB25C47E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}],"score":3,"updated_at":"2026-05-05T05:53:32+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"FilmCoder","author_url":"https://scicomp.stackexchange.com/users/56811/filmcoder","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"FilmCoder","profile_url":"https://scicomp.stackexchange.com/users/56811/filmcoder","user_type":"registered"},"created_at":"2026-05-05T05:53:32+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"C39D8103-AD54-44E2-90A3-4461BB25C47E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45440"}],"question_author":"Makogan","question_author_url":"https://scicomp.stackexchange.com/users/38908/makogan"},"code_blocks":[{"block_index":0,"code_text":"let quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node>| {\n // Legendre coefficients.\n let cfs = node.data.coeffs(); \n let coeff_count = node.data.coeff_count();\n\n let pos = box_position + box_dims / 2.;\n let p = (cam_pos - pos) / box_dims;\n let v = ray / box_dims;\n\n let mut a = 0.;\n let mut b = 0.;\n let mut c = 0.;\n // Shift and scale the ray and pos to the local node.\n let ray = v;\n let ray_pos = p;\n for i in 0..coeff_count\n {\n // Coefficient + the degree of each legendre polynomial that was\n // tensor producted to make the basis element, i.e. one of\n // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n let (s, powers) = cfs[i as usize];\n // Compute coefficients for each dimension's Legendre polynomial\n // restricted to line.\n let mut poly = [1., 0., 0.];\n // accumulates as [t^0, t^1, t^2] coefficients.\n\n for axis in 0..3\n {\n // Get teh axial coefficients of this ray\n let (v, p) = match axis\n {\n 0 => (ray.x, ray_pos.x),\n 1 => (ray.y, ray_pos.y),\n 2 => (ray.z, ray_pos.z),\n _ => unreachable!(),\n };\n\n let power = powers[axis];\n\n // Legendre polynomial P_n(vt + p) coefficients in t.\n let leg_coeffs = match power\n {\n 0 => [1., 0., 0.],\n 1 => [p, v, 0.],\n // coefficients of the legendre polynomial of degree 2\n 2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n _ => unreachable!(),\n };\n\n // Multiply poly *= leg_coeffs.\n let temp = [\n poly[0] * leg_coeffs[0],\n poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n poly[0] * leg_coeffs[2]\n + poly[1] * leg_coeffs[1]\n + poly[2] * leg_coeffs[0],\n ];\n poly = temp;\n }\n\n a += s * poly[2];\n b += s * poly[1];\n c += s * poly[0];\n }\n\n let disc = b * b - 4. * a * c;\n if disc < 0.\n {\n return f32::INFINITY;\n }\n\n let sqrt_disc = disc.sqrt();\n let inv_2a = 1. / (2. * a);\n\n // Quadratic solutions.\n let x1 = (-b - sqrt_disc) * inv_2a;\n let x2 = (-b + sqrt_disc) * inv_2a;\n\n // Branchless valid selection: if x < 0, replace with infinity.\n let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n // Take minimum of valid solutions.\n let quad_t = valid_x1.min(valid_x2);\n\n // Handle linear case.\n let is_linear = a.abs() < 0.0001;\n let linear_t = -c / b;\n\n let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n if is_linear { linear_t } else { quad_t }\n };\n","post_id":"scicomp:45396","sha256":"4951aa3005323c7afd7fef999567072e8b75144c8287b939f78cfa2f4fbf6c5c","source_url":"https://scicomp.stackexchange.com/questions/45396/erroneous-behaviour-when-trying-to-solve-ray-collisions-against-an-oct-tree-of-q"},{"block_index":1,"code_text":" let cfs = [\n (-0.1 + 1., [0, 0, 0]),\n (2./3., [2, 0, 0]),\n (2./3., [0, 2, 0]),\n (2./3., [0, 0, 2]),\n ];\n let coeff_count = 4;\n","post_id":"scicomp:45396","sha256":"e507ea393e471223462610a8652896044cc58b0db799f9c7367d7bd6cab205c2","source_url":"https://scicomp.stackexchange.com/questions/45396/erroneous-behaviour-when-trying-to-solve-ray-collisions-against-an-oct-tree-of-q"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"01d9e6f4e4d4506833891031b1a30309c3342ce4f6c23b72a347695790bba646","id":"SCT-b85489ebe403c0fd3263fe64","language":null,"library_or_tool":null,"problem_text":"Background\n\n\n\n\nI have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/mLTa1ZsD.png] (https://i.sstatic.net/mLTa1ZsD.png)\n\n\n\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.\n\n\n\n\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.\n\n\n\n\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/K6cTCsGy.png] (https://i.sstatic.net/K6cTCsGy.png)\n\n\n\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.\n\n\n\n\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/4aqhk3tL.png] (https://i.sstatic.net/4aqhk3tL.png)\n\n\n\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.\n\n\n\n\nI am going to describe the logic in a high level:\n\n\n\n\n\nConsider that an $\\mathbb{R^3}$ legendre polynomial becomes a regular polynomial when restricted to the parametric line of a ray.\n\n\n\n\nGrab the coefficients of the quadric on the current node, knowing these are coefficients of a legendre polynomial, not monomials.\n\n\n\n\nFor each coefficient, add it to the corresponding constant, linear or quadric set of coefficents (for monomials).\n\n\n\n\nGrab the final, properly factored, coeffcients and solve a simple quadratic equation to figure out if and where the ray intersects the quadric on the current node.\n\n\n\n\n\nThe actual code is this:\n\n\n\n\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node>| {\n // Legendre coefficients.\n let cfs = node.data.coeffs(); \n let coeff_count = node.data.coeff_count();\n\n let pos = box_position + box_dims / 2.;\n let p = (cam_pos - pos) / box_dims;\n let v = ray / box_dims;\n\n let mut a = 0.;\n let mut b = 0.;\n let mut c = 0.;\n // Shift and scale the ray and pos to the local node.\n let ray = v;\n let ray_pos = p;\n for i in 0..coeff_count\n {\n // Coefficient + the degree of each legendre polynomial that was\n // tensor producted to make the basis element, i.e. one of\n // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n let (s, powers) = cfs[i as usize];\n // Compute coefficients for each dimension's Legendre polynomial\n // restricted to line.\n let mut poly = [1., 0., 0.];\n // accumulates as [t^0, t^1, t^2] coefficients.\n\n for axis in 0..3\n {\n // Get teh axial coefficients of this ray\n let (v, p) = match axis\n {\n 0 => (ray.x, ray_pos.x),\n 1 => (ray.y, ray_pos.y),\n 2 => (ray.z, ray_pos.z),\n _ => unreachable!(),\n };\n\n let power = powers[axis];\n\n // Legendre polynomial P_n(vt + p) coefficients in t.\n let leg_coeffs = match power\n {\n 0 => [1., 0., 0.],\n 1 => [p, v, 0.],\n // coefficients of the legendre polynomial of degree 2\n 2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n _ => unreachable!(),\n };\n\n // Multiply poly *= leg_coeffs.\n let temp = [\n poly[0] * leg_coeffs[0],\n poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n poly[0] * leg_coeffs[2]\n + poly[1] * leg_coeffs[1]\n + poly[2] * leg_coeffs[0],\n ];\n poly = temp;\n }\n\n a += s * poly[2];\n b += s * poly[1];\n c += s * poly[0];\n }\n\n let disc = b * b - 4. * a * c;\n if disc < 0.\n {\n return f32::INFINITY;\n }\n\n let sqrt_disc = disc.sqrt();\n let inv_2a = 1. / (2. * a);\n\n // Quadratic solutions.\n let x1 = (-b - sqrt_disc) * inv_2a;\n let x2 = (-b + sqrt_disc) * inv_2a;\n\n // Branchless valid selection: if x < 0, replace with infinity.\n let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n // Take minimum of valid solutions.\n let quad_t = valid_x1.min(valid_x2);\n\n // Handle linear case.\n let is_linear = a.abs() < 0.0001;\n let linear_t = -c / b;\n\n let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n if is_linear { linear_t } else { quad_t }\n };\n\n\n\n\n\nTo add further context, to generate the image with the additional spheres all you need to do is hard code the coefficients for a sphere:\n\n\n\n\n let cfs = [\n (-0.1 + 1., [0, 0, 0]),\n (2./3., [2, 0, 0]),\n (2./3., [0, 2, 0]),\n (2./3., [0, 0, 2]),\n ];\n let coeff_count = 4;\n\n\n\n\n\nTo override the ones coming in. But the input coefficients cannot eb wrong because then the first image would not work.\n\n\n\n\nQuestion\n\n\n\n\nThere's something wrong with the way I am computing my ray quadric collisions that is specific to the Legendre case. When I modify my logic to work with the sphere quadrics it works, as shown, so I must have messed something up with when computing the coefficients, but when I see the written code I fail to see what.","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":"Makogan","profile_url":"https://scicomp.stackexchange.com/users/38908/makogan","user_type":"registered"},"created_at":"2026-03-05T07:11:11+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"5D085A5B-26B6-422F-9DEC-349300FA1225","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/5D085A5B-26B6-422F-9DEC-349300FA1225/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Makogan","profile_url":"https://scicomp.stackexchange.com/users/38908/makogan","user_type":"registered"},"created_at":"2026-03-06T06:49:04+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"4727E0AD-D33F-4975-98C2-D0DBA29209AF","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4727E0AD-D33F-4975-98C2-D0DBA29209AF/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":"45396","source_record_sha256":"73b6d9dd98e07bd4d718d3cc6ad603730c900937f54eba9bd655612fcb988cf2","source_url":"https://scicomp.stackexchange.com/questions/45396/erroneous-behaviour-when-trying-to-solve-ray-collisions-against-an-oct-tree-of-q","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Background

\n

I have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):

\n

\"enter

\n

There's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.

\n

But of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.

\n

The image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:

\n

\"enter

\n

This is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.

\n

However, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:

\n

\"enter

\n

Not only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.

\n

I am going to describe the logic in a high level:

\n
    \n
  • Consider that an $\\mathbb{R^3}$ legendre polynomial becomes a regular polynomial when restricted to the parametric line of a ray.
  • \n
  • Grab the coefficients of the quadric on the current node, knowing these are coefficients of a legendre polynomial, not monomials.
  • \n
  • For each coefficient, add it to the corresponding constant, linear or quadric set of coefficents (for monomials).
  • \n
  • Grab the final, properly factored, coeffcients and solve a simple quadratic equation to figure out if and where the ray intersects the quadric on the current node.
  • \n
\n

The actual code is this:

\n
let quadratic_node_intersection =\n        move |origin: &Vec3,\n              lray: &Vec3,\n              box_position: &Vec3,\n              box_dims: &Vec3,\n              node: &Node<HpNode<f32, 10>>| {\n            // Legendre coefficients.\n            let cfs = node.data.coeffs(); \n            let coeff_count = node.data.coeff_count();\n\n            let pos = box_position + box_dims / 2.;\n            let p = (cam_pos - pos) / box_dims;\n            let v = ray / box_dims;\n\n            let mut a = 0.;\n            let mut b = 0.;\n            let mut c = 0.;\n            // Shift and scale the ray and pos to the local node.\n            let ray = v;\n            let ray_pos = p;\n            for i in 0..coeff_count\n            {\n                // Coefficient + the degree of each legendre polynomial that was\n                // tensor producted to make the basis element, i.e. one of\n                // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n                // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n                let (s, powers) = cfs[i as usize];\n                // Compute coefficients for each dimension's Legendre polynomial\n                // restricted to line.\n                let mut poly = [1., 0., 0.];\n                // accumulates as [t^0, t^1, t^2] coefficients.\n\n                for axis in 0..3\n                {\n                    // Get teh axial coefficients of this ray\n                    let (v, p) = match axis\n                    {\n                        0 => (ray.x, ray_pos.x),\n                        1 => (ray.y, ray_pos.y),\n                        2 => (ray.z, ray_pos.z),\n                        _ => unreachable!(),\n                    };\n\n                    let power = powers[axis];\n\n                    // Legendre polynomial P_n(vt + p) coefficients in t.\n                    let leg_coeffs = match power\n                    {\n                        0 => [1., 0., 0.],\n                        1 => [p, v, 0.],\n                        // coefficients of the legendre polynomial of degree 2\n                        2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n                        _ => unreachable!(),\n                    };\n\n                    // Multiply poly *= leg_coeffs.\n                    let temp = [\n                        poly[0] * leg_coeffs[0],\n                        poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n                        poly[0] * leg_coeffs[2]\n                            + poly[1] * leg_coeffs[1]\n                            + poly[2] * leg_coeffs[0],\n                    ];\n                    poly = temp;\n                }\n\n                a += s * poly[2];\n                b += s * poly[1];\n                c += s * poly[0];\n            }\n\n            let disc = b * b - 4. * a * c;\n            if disc < 0.\n            {\n                return f32::INFINITY;\n            }\n\n            let sqrt_disc = disc.sqrt();\n            let inv_2a = 1. / (2. * a);\n\n            // Quadratic solutions.\n            let x1 = (-b - sqrt_disc) * inv_2a;\n            let x2 = (-b + sqrt_disc) * inv_2a;\n\n            // Branchless valid selection: if x < 0, replace with infinity.\n            let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n            let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n            // Take minimum of valid solutions.\n            let quad_t = valid_x1.min(valid_x2);\n\n            // Handle linear case.\n            let is_linear = a.abs() < 0.0001;\n            let linear_t = -c / b;\n\n            let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n            if is_linear { linear_t } else { quad_t }\n        };\n
\n

To add further context, to generate the image with the additional spheres all you need to do is hard code the coefficients for a sphere:

\n
            let cfs = [\n                (-0.1 + 1., [0, 0, 0]),\n                (2./3., [2, 0, 0]),\n                (2./3., [0, 2, 0]),\n                (2./3., [0, 0, 2]),\n            ];\n            let coeff_count = 4;\n
\n

To override the ones coming in. But the input coefficients cannot eb wrong because then the first image would not work.

\n

Question

\n

There's something wrong with the way I am computing my ray quadric collisions that is specific to the Legendre case. When I modify my logic to work with the sphere quadrics it works, as shown, so I must have messed something up with when computing the coefficients, but when I see the written code I fail to see what.

\n","question_title":"Erroneous behaviour when trying to solve ray collisions against an oct tree of quadrics","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45396/erroneous-behaviour-when-trying-to-solve-ray-collisions-against-an-oct-tree-of-q","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45429,"score":3}],"answers":[{"answer_html":"

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.

\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":"

We propose a numerical method for stiff ordinary differential equations (ODEs) based on a geometric transformation. The key ideas are:

\n

1-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

2-Calibration – For a given y2,the geodesic provides the midpoint

\n

(tm,ym). We then compute the derivative from the geodesic:

\n
                       ym′ = (ym−y1)/(tm-t1)\n
\n

​

\n

and evaluate the ODE at the midpoint:

\n

fm =f(tm,ym).\nThe residual is\nR(y2 )=∣ ym′−fm ∣.

\n

3-Adjustment – Because the interval is short,

\n

R is nearly linear in y2 . A few secant iterations (or a simple manual search) suffice to make R negligible.

\n

4-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

5-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

6-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

Why this method differs from classical ones:

\n

No implicit solver, no Jacobian.

\n

Stability is controlled by curvature, not by a CFL condition.

\n

Only one scalar parameter is adjusted per segment, regardless of the system size.

\n

Benchmarks (performed in double precision, reference: Radau with tolerance 1e-12):

\n

Prothero–Robinson

\n

y′ =−1000y+1000sint+cost with y(0.1)=sin(0.1)
\nResult: y(0.101)≈0.10083089255
\nError: 1e-6

\n

Van der Pol,

\n

ε=1000, 8 segments from
\nResult: y(0.248583)≈0.2477211
\nError: 0.7% (finner subdivision gives 1e-7)

\n

Lorenz system (single\nshort segment)

\n

Result: error on all variables
\nError≈1e-7

\n

Brusselator (single segment)

\n

Result: residual on second equation
\nerror: <1e-7

\n

Questions to the community:

\n

Are there other stiff or multi‑scale benchmarks that you would recommend to test this approach further?

\n

Has a similar curvature‑based step control been studied elsewhere?

\n

What theoretical tools could help analyse the stability of such a method?

\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"} {"accepted_answer":{"answer_html":"

The standard approach in most ODE solver packages is the following. First compute the error using a norm weighted by tolerances:\n$$\nerr = \\sqrt{\\frac{1}{d} \\sum_{i=1}^{d} \\left( \\frac{y_i^{[p+m]} - y_i^{[p]}}{atol_i + rtol_i |y_i^{[p]}|} \\right)^2}\n$$

\n

Here, $atol$ is an absolute tolerance and $rtol$ is a relative tolerance.\nTo be consistent with your criteria 2, you can take $atol_i = tol, rtol_i = 0$.

\n

If $err \\leq 1$, the step is accepted, and if $err > 1$, the step is rejected. In either case, the time step is updated by

\n

$$\nh_{new} = \\beta \\, h \\, err^{-1/(\\min(p+m, p) + 1)}\n$$

\n

Note the extra +1 in the exponent that the formula in your question was missing. Typically there's some bounds placed on the growth or shrinking of the step too. I recommend reading pages 167-168 of https://doi.org/10.1007/978-3-540-78862-1

\n

So to answer your questions

\n
\n

Are these two acceptance criteria strictly equivalent in practice

\n
\n

Since $\\beta < 1$, they're not quite equivalent. Criteria 1 seems dubious if not outright misguided because you cannot shrink the time step without rejecting the step. With criteria 2 you can. In the test results you report, this likely explains why criteria 1 was significantly worse.

\n
\n

Is one approach considered more robust or standard in modern implementations

\n
\n

Criteria 1 is not robust, 2 is somewhat robust, and what I provided above most robust.

\n
\n

Are there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?

\n
\n

I struggle to see any situation where criteria 1 is preferable.

\n","answer_id":45426,"answer_text":"The standard approach in most ODE solver packages is the following. First compute the error using a norm weighted by tolerances:\n$$\nerr = \\sqrt{\\frac{1}{d} \\sum_{i=1}^{d} \\left( \\frac{y_i^{[p+m]} - y_i^{[p]}}{atol_i + rtol_i |y_i^{[p]}|} \\right)^2}\n$$\n\n\n\n\nHere, $atol$ is an absolute tolerance and $rtol$ is a relative tolerance.\nTo be consistent with your criteria 2, you can take $atol_i = tol, rtol_i = 0$.\n\n\n\n\nIf $err \\leq 1$, the step is accepted, and if $err > 1$, the step is rejected. In either case, the time step is updated by\n\n\n\n\n$$\nh_{new} = \\beta \\, h \\, err^{-1/(\\min(p+m, p) + 1)}\n$$\n\n\n\n\nNote the extra +1 in the exponent that the formula in your question was missing. Typically there's some bounds placed on the growth or shrinking of the step too. I recommend reading pages 167-168 of https://doi.org/10.1007/978-3-540-78862-1 (https://doi.org/10.1007/978-3-540-78862-1)\n\n\n\n\nSo to answer your questions\n\n\n\n\n\n\n\nAre these two acceptance criteria strictly equivalent in practice\n\n\n\n\n\n\n\nSince $\\beta < 1$, they're not quite equivalent. Criteria 1 seems dubious if not outright misguided because you cannot shrink the time step without rejecting the step. With criteria 2 you can. In the test results you report, this likely explains why criteria 1 was significantly worse.\n\n\n\n\n\n\n\nIs one approach considered more robust or standard in modern implementations\n\n\n\n\n\n\n\nCriteria 1 is not robust, 2 is somewhat robust, and what I provided above most robust.\n\n\n\n\n\n\n\nAre there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?\n\n\n\n\n\n\n\nI struggle to see any situation where criteria 1 is preferable.","answer_url":"https://scicomp.stackexchange.com/a/45426","author":"Steven Roberts","author_url":"https://scicomp.stackexchange.com/users/33269/steven-roberts","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-04-04T04:23:30+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45425,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Steven Roberts","profile_url":"https://scicomp.stackexchange.com/users/33269/steven-roberts","user_type":"registered"},"created_at":"2026-04-04T04:23:30+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"25A90075-8C5D-44B1-A44D-A0B19E6BBEA2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/25A90075-8C5D-44B1-A44D-A0B19E6BBEA2/view-source"}],"score":5,"updated_at":"2026-04-04T04:23:30+00:00"},"answer_scores":[{"answer_id":45426,"score":5}],"answers":[{"answer_html":"

The standard approach in most ODE solver packages is the following. First compute the error using a norm weighted by tolerances:\n$$\nerr = \\sqrt{\\frac{1}{d} \\sum_{i=1}^{d} \\left( \\frac{y_i^{[p+m]} - y_i^{[p]}}{atol_i + rtol_i |y_i^{[p]}|} \\right)^2}\n$$

\n

Here, $atol$ is an absolute tolerance and $rtol$ is a relative tolerance.\nTo be consistent with your criteria 2, you can take $atol_i = tol, rtol_i = 0$.

\n

If $err \\leq 1$, the step is accepted, and if $err > 1$, the step is rejected. In either case, the time step is updated by

\n

$$\nh_{new} = \\beta \\, h \\, err^{-1/(\\min(p+m, p) + 1)}\n$$

\n

Note the extra +1 in the exponent that the formula in your question was missing. Typically there's some bounds placed on the growth or shrinking of the step too. I recommend reading pages 167-168 of https://doi.org/10.1007/978-3-540-78862-1

\n

So to answer your questions

\n
\n

Are these two acceptance criteria strictly equivalent in practice

\n
\n

Since $\\beta < 1$, they're not quite equivalent. Criteria 1 seems dubious if not outright misguided because you cannot shrink the time step without rejecting the step. With criteria 2 you can. In the test results you report, this likely explains why criteria 1 was significantly worse.

\n
\n

Is one approach considered more robust or standard in modern implementations

\n
\n

Criteria 1 is not robust, 2 is somewhat robust, and what I provided above most robust.

\n
\n

Are there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?

\n
\n

I struggle to see any situation where criteria 1 is preferable.

\n","answer_id":45426,"answer_text":"The standard approach in most ODE solver packages is the following. First compute the error using a norm weighted by tolerances:\n$$\nerr = \\sqrt{\\frac{1}{d} \\sum_{i=1}^{d} \\left( \\frac{y_i^{[p+m]} - y_i^{[p]}}{atol_i + rtol_i |y_i^{[p]}|} \\right)^2}\n$$\n\n\n\n\nHere, $atol$ is an absolute tolerance and $rtol$ is a relative tolerance.\nTo be consistent with your criteria 2, you can take $atol_i = tol, rtol_i = 0$.\n\n\n\n\nIf $err \\leq 1$, the step is accepted, and if $err > 1$, the step is rejected. In either case, the time step is updated by\n\n\n\n\n$$\nh_{new} = \\beta \\, h \\, err^{-1/(\\min(p+m, p) + 1)}\n$$\n\n\n\n\nNote the extra +1 in the exponent that the formula in your question was missing. Typically there's some bounds placed on the growth or shrinking of the step too. I recommend reading pages 167-168 of https://doi.org/10.1007/978-3-540-78862-1 (https://doi.org/10.1007/978-3-540-78862-1)\n\n\n\n\nSo to answer your questions\n\n\n\n\n\n\n\nAre these two acceptance criteria strictly equivalent in practice\n\n\n\n\n\n\n\nSince $\\beta < 1$, they're not quite equivalent. Criteria 1 seems dubious if not outright misguided because you cannot shrink the time step without rejecting the step. With criteria 2 you can. In the test results you report, this likely explains why criteria 1 was significantly worse.\n\n\n\n\n\n\n\nIs one approach considered more robust or standard in modern implementations\n\n\n\n\n\n\n\nCriteria 1 is not robust, 2 is somewhat robust, and what I provided above most robust.\n\n\n\n\n\n\n\nAre there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?\n\n\n\n\n\n\n\nI struggle to see any situation where criteria 1 is preferable.","answer_url":"https://scicomp.stackexchange.com/a/45426","author":"Steven Roberts","author_url":"https://scicomp.stackexchange.com/users/33269/steven-roberts","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-04-04T04:23:30+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45425,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Steven Roberts","profile_url":"https://scicomp.stackexchange.com/users/33269/steven-roberts","user_type":"registered"},"created_at":"2026-04-04T04:23:30+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"25A90075-8C5D-44B1-A44D-A0B19E6BBEA2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/25A90075-8C5D-44B1-A44D-A0B19E6BBEA2/view-source"}],"score":5,"updated_at":"2026-04-04T04:23:30+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Steven Roberts","author_url":"https://scicomp.stackexchange.com/users/33269/steven-roberts","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Steven Roberts","profile_url":"https://scicomp.stackexchange.com/users/33269/steven-roberts","user_type":"registered"},"created_at":"2026-04-04T04:23:30+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"25A90075-8C5D-44B1-A44D-A0B19E6BBEA2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/25A90075-8C5D-44B1-A44D-A0B19E6BBEA2/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45426"}],"question_author":"Santiago Iñiguez","question_author_url":"https://scicomp.stackexchange.com/users/56699/santiago-i%c3%b1iguez"},"code_blocks":[{"block_index":0,"code_text":"if (s >= 1) accept step\nelse reject\n","post_id":"scicomp:45425","sha256":"44345fd6c1fe938c9fe62d3f6e522c3010a52d59b81ae9de41767b4d8a16d0a6","source_url":"https://scicomp.stackexchange.com/questions/45425/acceptance-criterion-in-adaptive-runge-kutta-methods-compare-error-directly-or"},{"block_index":1,"code_text":"if (err <= tol) accept step\nelse reject\n","post_id":"scicomp:45425","sha256":"1e17c277eba8f8a80c12b3e3689c921bb7692715fafe6df3ce7a4c30c4e3c287","source_url":"https://scicomp.stackexchange.com/questions/45425/acceptance-criterion-in-adaptive-runge-kutta-methods-compare-error-directly-or"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"1d1d9d666515a31bbbea0403c279365fe3ba72061d39dc97ade33ecb452ebfdb","id":"SCT-5af69781e35379549b92b201","language":null,"library_or_tool":null,"problem_text":"I am implementing adaptive step-size Runge–Kutta methods using embedded pairs (orders ( p ) and ( p+m )). The standard structure is:\n\n\n\n\n\n\n\nCompute two solutions: $$ y^{[p]} \\text{ and } y^{[p+m]} $$\n\n\n\n\n\n\n\n\n\nEstimate local error: $$ \\text{err} = \\left| y^{[p+m]} - y^{[p]} \\right|$$\n\n\n\n\n\n\n\n\n\nCompute scaling factor:\n\n$$\n s = \\beta \\left( \\frac{\\text{tol}}{\\text{err}} \\right)^{1/p}\n $$\n\n\n\n\n\n\n\n\n\nUpdate step:\n\n$$\n h_{\\text{new}} = s \\cdot h\n $$\n\n\n\n\n\n\n\n\nMy question is about the accept/reject criterion:\n\n\n\n\nTwo alternatives I found:\n\n\n\n\n\nCompare using ( s ):\n\n\n\n\n\nif (s >= 1) accept step\nelse reject\n\n\n\n\n\n\nCompare using the error directly:\n\n\n\n\n\nif (err <= tol) accept step\nelse reject\n\n\n\n\n\nFrom what I understand, these should be mathematically equivalent if ( s ) is defined as above.\n\n\n\n\nHowever:\n\n\n\n\n\nIn Shampine-style implementations, it seems the comparison is done directly on the error.\n\n\n\n\nIn some lecture notes and sources, the acceptance is expressed using:\n$$\n s \\ge 1\n $$\n\n\n\n\n\nMy concern (practical behavior):\n\n\n\n\nI tested both approaches on the double pendulum problem, counting rejected steps. Using:\n\n\n\n\n\n$$\n \\text{tol} = 10^{-5}\n $$\n\n\n\n\n$$\n h_{\\max} = 5 \\times 10^{-3}\n $$\n\n\n\n\n\nI observed:\n\n\n\n\n\n\n\nUsing ( s $\\ge$ 1 ):\n\n\n\n\n\n~183,000 rejected steps\n\n\n\n\n~6,000 accepted steps\n\n\n\n\n\n\n\n\n\n\nUsing ( $ \\text{err} \\le \\text{tol} $):\n\n\n\n\n\n< 100 rejected steps\n\n\n\n\nSame number of accepted points (~6,000)\n\n\n\n\n\n\n\n\n\nBoth solutions remain within the requested tolerance band.\n\n\n\n\nQuestions:\n\n\n\n\n\nAre these two acceptance criteria strictly equivalent in practice, or can numerical/implementation details make them behave differently?\n\n\n\n\nIs one approach considered more robust or standard in modern implementations?\n\n\n\n\nAre there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?\n\n\n\n\n\nIf anyone can clarify whether there is a theoretical or practical reason to prefer one over the other, I would really appreciate it.\n\n\n\n\nThanks!","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":"Santiago Iñiguez","profile_url":"https://scicomp.stackexchange.com/users/56699/santiago-i%c3%b1iguez","user_type":"registered"},"created_at":"2026-04-03T20:45:39+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"7B51A856-186D-4E25-8879-D5A9AC045FA1","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/7B51A856-186D-4E25-8879-D5A9AC045FA1/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-04-04T04:48:29+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"840A9812-5074-4EA5-960A-41B99C651A33","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/840A9812-5074-4EA5-960A-41B99C651A33/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":"45425","source_record_sha256":"b0bb0d3eead80e9ce5084ecc798ae396bd868a5a47089371a50b9c3d4d312a9b","source_url":"https://scicomp.stackexchange.com/questions/45425/acceptance-criterion-in-adaptive-runge-kutta-methods-compare-error-directly-or","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am implementing adaptive step-size Runge–Kutta methods using embedded pairs (orders ( p ) and ( p+m )). The standard structure is:

\n
    \n
  • Compute two solutions: $$ y^{[p]} \\text{ and } y^{[p+m]} $$

    \n
  • \n
  • Estimate local error: $$ \\text{err} = \\left| y^{[p+m]} - y^{[p]} \\right|$$

    \n
  • \n
  • Compute scaling factor:
    \n$$\n s = \\beta \\left( \\frac{\\text{tol}}{\\text{err}} \\right)^{1/p}\n $$

    \n
  • \n
  • Update step:
    \n$$\n h_{\\text{new}} = s \\cdot h\n $$

    \n
  • \n
\n

My question is about the accept/reject criterion:

\n

Two alternatives I found:

\n
    \n
  1. Compare using ( s ):
  2. \n
\n
if (s >= 1) accept step\nelse reject\n
\n
    \n
  1. Compare using the error directly:
  2. \n
\n
if (err <= tol) accept step\nelse reject\n
\n

From what I understand, these should be mathematically equivalent if ( s ) is defined as above.

\n

However:

\n
    \n
  • In Shampine-style implementations, it seems the comparison is done directly on the error.
  • \n
  • In some lecture notes and sources, the acceptance is expressed using:\n$$\n s \\ge 1\n $$
  • \n
\n

My concern (practical behavior):

\n

I tested both approaches on the double pendulum problem, counting rejected steps. Using:

\n
    \n
  • $$\n \\text{tol} = 10^{-5}\n $$
  • \n
  • $$\n h_{\\max} = 5 \\times 10^{-3}\n $$
  • \n
\n

I observed:

\n
    \n
  • Using ( s $\\ge$ 1 ):

    \n
      \n
    • ~183,000 rejected steps
    • \n
    • ~6,000 accepted steps
    • \n
    \n
  • \n
  • Using ( $ \\text{err} \\le \\text{tol} $):

    \n
      \n
    • < 100 rejected steps
    • \n
    • Same number of accepted points (~6,000)
    • \n
    \n
  • \n
\n

Both solutions remain within the requested tolerance band.

\n

Questions:

\n
    \n
  1. Are these two acceptance criteria strictly equivalent in practice, or can numerical/implementation details make them behave differently?
  2. \n
  3. Is one approach considered more robust or standard in modern implementations?
  4. \n
  5. Are there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?
  6. \n
\n

If anyone can clarify whether there is a theoretical or practical reason to prefer one over the other, I would really appreciate it.

\n

Thanks!

\n","question_title":"Acceptance criterion in adaptive Runge–Kutta methods: compare error directly or via step factor ( s )?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45425/acceptance-criterion-in-adaptive-runge-kutta-methods-compare-error-directly-or","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45473,"score":2},{"answer_id":45482,"score":3}],"answers":[{"answer_html":"

The gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.

\n

The given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).

\n

We assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.

\n

Also the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.

\n

In order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.

\n

Because these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.

\n

Comparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).

\n

When those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
First polynomialSecond polynomial
$1$ or $q^0$$q^{8+2x_{13}}$
$q^2$$q^{10+2x_{13}}$
$q^8$$q^{4+2x_{15}}$
$q^{10}$$q^{6+2x_{15}}$
$q^{12}$$q^{2x_{17}}$
$q^{14}$$q^{2+2x_{17}}$
$q^{16}$$q^{2x_{35}}$
$q^{18}$$q^{2+2x_{35}}$
$q^{20}$$q^{-4+2x_{37}}$
$q^{22}$$q^{-2+2x_{37}}$
$q^{24}$$q^{-8+2x_{57}}$
$q^{26}$$q^{-6+2x_{57}}$
\n

Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.

\n

This resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.

\n

My personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.

\n

I must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.

\n","answer_id":45473,"answer_text":"The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.","answer_url":"https://scicomp.stackexchange.com/a/45473","author":"hardmath","author_url":"https://scicomp.stackexchange.com/users/651/hardmath","author_user_type":"moderator","content_license":"CC BY-SA 4.0","created_at":"2026-06-24T21:53:31+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45472,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"hardmath","profile_url":"https://scicomp.stackexchange.com/users/651/hardmath","user_type":"moderator"},"created_at":"2026-06-24T21:53:31+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"6B10CE88-2D26-43C8-9F27-870834FE5FB3","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}],"score":2,"updated_at":"2026-06-24T21:53:31+00:00"},{"answer_html":"

Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative "pulls down" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:

\n
restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n  eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n
\n

For the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.

\n","answer_id":45482,"answer_text":"Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative \"pulls down\" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:\n\n\n\n\nrestart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\n\n\n\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.","answer_url":"https://scicomp.stackexchange.com/a/45482","author":"dharr","author_url":"https://scicomp.stackexchange.com/users/50934/dharr","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-06-28T17:22:41+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45472,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-28T17:22:41+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"17B5B435-530D-44FB-A531-8C7EBC69DAB0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-28T17:30:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B335F14D-BC1A-4871-8C8E-AA1A1574CE8E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T00:34:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE6B318A-E224-4873-94DF-796E47B0400A","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T01:28:55+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"E46B4CBF-9F68-49D7-885E-BE0F07FBA25B","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T02:02:10+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"BE24CE57-475F-48DB-8B09-676A64E891E3","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-07-06T01:31:28+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"64B9EB1B-7407-427F-BF22-4AF94181F69C","revision_number":6,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}],"score":3,"updated_at":"2026-07-06T01:31:28+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"hardmath","author_url":"https://scicomp.stackexchange.com/users/651/hardmath","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"hardmath","profile_url":"https://scicomp.stackexchange.com/users/651/hardmath","user_type":"moderator"},"created_at":"2026-06-24T21:53:31+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"6B10CE88-2D26-43C8-9F27-870834FE5FB3","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45473"},{"author":"dharr","author_url":"https://scicomp.stackexchange.com/users/50934/dharr","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-28T17:22:41+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"17B5B435-530D-44FB-A531-8C7EBC69DAB0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-28T17:30:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B335F14D-BC1A-4871-8C8E-AA1A1574CE8E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T00:34:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE6B318A-E224-4873-94DF-796E47B0400A","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T01:28:55+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"E46B4CBF-9F68-49D7-885E-BE0F07FBA25B","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T02:02:10+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"BE24CE57-475F-48DB-8B09-676A64E891E3","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-07-06T01:31:28+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"64B9EB1B-7407-427F-BF22-4AF94181F69C","revision_number":6,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45482"}],"question_author":"ateixeira82","question_author_url":"https://scicomp.stackexchange.com/users/56972/ateixeira82"},"code_blocks":[{"block_index":0,"code_text":"restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n","post_id":45482,"sha256":"9e7ab01b813928e1abd2c01b90d8713d1947c604928afebe74732a90aaf36920","source_url":"https://scicomp.stackexchange.com/a/45482"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"ba8c1ea063a38cb557574bceff9bc01e80edefed422c366a755c5950746a3dc7","id":"SCT-a7f1b1f692444856dbf30099","language":["python","mathematica"],"library_or_tool":["mathematica"],"problem_text":"I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.\n\n\n\n\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.\n\n\n\n\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.\n\n\n\n\nDo you guys know of any hint or solution on how to tackle these problems?\n\n\n\n\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$\n\n\n\n\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$\n\n\n\n\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.","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":"ateixeira82","profile_url":"https://scicomp.stackexchange.com/users/56972/ateixeira82","user_type":"registered"},"created_at":"2026-06-21T10:31:05+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"F5FC1979-2C80-415C-8F46-2AF9C62D8214","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F5FC1979-2C80-415C-8F46-2AF9C62D8214/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ateixeira82","profile_url":"https://scicomp.stackexchange.com/users/56972/ateixeira82","user_type":"registered"},"created_at":"2026-06-21T14:46:19+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"53FB132D-482A-4B58-AD12-EF8D7216467C","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/53FB132D-482A-4B58-AD12-EF8D7216467C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"hardmath","profile_url":"https://scicomp.stackexchange.com/users/651/hardmath","user_type":"moderator"},"created_at":"2026-06-24T19:16:29+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"41EC7BF5-D5F7-4405-918D-9C3797D59DDE","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/41EC7BF5-D5F7-4405-918D-9C3797D59DDE/view-source"}],"source_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":"45472","source_record_sha256":"a32b3bf956b22a32e447e1ba11347b8aec1628c76dd3c4ee5932670cc859cf29","source_url":"https://scicomp.stackexchange.com/questions/45472/solving-linear-system-of-equations-with-combinatorics","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am trying to solve a linear system of equations that comes from equating two Laurent polynomials. The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.

\n

They always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.

\n

My idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.

\n

Do you guys know of any hint or solution on how to tackle these problems?

\n

As an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$

\n

and here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$

\n

There are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.

\n","question_title":"Solving linear system of equations with combinatorics","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45472/solving-linear-system-of-equations-with-combinatorics","split":"train"} {"accepted_answer":{"answer_html":"

The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.

\n

In fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.

\n

For anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method

\n

And here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6

\n

The original comment was:

\n
\n

Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).

\n

Your RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.

\n

My advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.

\n
\n","answer_id":45503,"answer_text":"The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.","answer_url":"https://scicomp.stackexchange.com/a/45503","author":"Omar Osman Mahamoud","author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-29T16:42:27+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-29T16:42:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"DD32D002-9E3F-4398-BC22-FB7FBF667951","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}],"score":2,"updated_at":"2026-07-29T16:42:27+00:00"},"answer_scores":[{"answer_id":45490,"score":6},{"answer_id":45491,"score":7},{"answer_id":45503,"score":2}],"answers":[{"answer_html":"

From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:

\n
import matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1     # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n                   vx_earth: float = 0., vy_earth: float = 2*np.pi,\n                   dt: float = 0.1) -> tuple[list, list]:\n    xpos = []\n    ypos = []\n\n    for i in range(n_steps):\n        ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        vx_earth += ax_earth * dt\n        vy_earth += ay_earth * dt\n\n        xpos.append(x_earth)\n        ypos.append(y_earth)\n\n        x_earth += vx_earth * dt\n        y_earth += vy_earth * dt\n\n    return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n                   vx_earth: float = 0., vy_earth: float = 2*np.pi,\n                   dt: float = 0.1) -> tuple[list, list]:\n    xpos = []\n    ypos = []\n\n    for i in range(n_steps):\n        ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        x_earth_mid = x_earth + vx_earth * (dt / 2)\n        y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n        vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n        vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n        ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n        ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n        vx_earth += ax_earth_mid * dt\n        vy_earth += ay_earth_mid * dt\n\n        xpos.append(x_earth)\n        ypos.append(y_earth)\n\n        x_earth += vx_earth_mid * dt\n        y_earth += vy_earth_mid * dt\n\n    return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n                   vx_earth: float = 0., vy_earth: float = 2*np.pi,\n                   dt: float = 0.1) -> tuple[list, list]:\n    xpos = []\n    ypos = []\n\n    for i in range(n_steps):\n        ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        xpos.append(x_earth)\n        ypos.append(y_earth)\n\n        x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n        y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n        ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n        vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n    return xpos, ypos\n\n\ndef main() -> None:\n    fig, ax = plt.subplots()\n    for method, name in (\n        (euler_function, 'Euler'),\n        (runge_kutta_function, 'RK2'),\n        (verlet_function, 'Verlet'),\n    ):\n        x, y = method(dt=0.01)\n        ax.plot(x, y, label=name)\n    ax.legend()\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n
\n

\"comparison\"

\n

For n=5000, dt=0.001, the output is closer yet:

\n

\"dt=0.001\"

\n

Obviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:

\n
import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1     # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n    p, v = np.split(state, 2)\n    a = -G * M_sun / np.linalg.norm(p)**3 * p\n    return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n    p, v = np.split(state, 2)\n\n    # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n    x, y = p\n    fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n    daxdpx = fnorm5*(y**2 - 2*x**2)\n    daydpy = fnorm5*(x**2 - 2*y**2)\n    daxdpy = fnorm5*-3*x*y\n    daydpx = daxdpy\n    jac = np.array((\n        #  /dpx    /dpy /dvx /dvy\n        (     0,      0,   1,   0), # dvx\n        (     0,      0,   0,   1), # dvy\n        (daxdpx, daxdpy,   0,   0), # dax\n        (daydpx, daydpy,   0,   0), # day\n    ))\n\n    return jac\n\n\nout = scipy.integrate.solve_ivp(\n    method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n    # jac=d2dt2,  # not used by Runge-Kutta\n    t_span=(0, 1000),  # Année\n    y0=(\n        1.5, 0,      # UA\n        0, 2*np.pi,  # UA/Année\n    ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n
\n

\"RK32\"

\n","answer_id":45490,"answer_text":"From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n[image: comparison; source: https://i.sstatic.net/ZOXbZlmS.png] (https://i.sstatic.net/ZOXbZlmS.png)\n\n\n\n\nFor n=5000, dt=0.001, the output is closer yet:\n\n\n\n\n[image: dt=0.001; source: https://i.sstatic.net/mLRffKQD.png] (https://i.sstatic.net/mLRffKQD.png)\n\n\n\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine (https://www.sciencedirect.com/science/article/pii/0893965989900797) form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: RK32; source: https://i.sstatic.net/DgMDrx4E.png] (https://i.sstatic.net/DgMDrx4E.png)","answer_url":"https://scicomp.stackexchange.com/a/45490","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-13T01:47:13+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T01:47:13+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"06EC415F-DC78-49A5-97D0-ED020CE6C74F","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T03:28:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"88B016CA-5B2E-46C7-99DA-7F374A3A0853","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T21:27:38+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"51F9060A-E0B8-4FC6-AAA1-D61ED8331962","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}],"score":6,"updated_at":"2026-07-13T21:27:38+00:00"},{"answer_html":"

When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.

\n

Each method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!

\n

What you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)

\n

From the top of my head orbital mechanics are often solved with implicit euler-like methods "symplectic integrators", because they preserve energy and impulse better, but my memory may be leaky.

\n","answer_id":45491,"answer_text":"When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.\n\n\n\n\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!\n\n\n\n\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)\n\n\n\n\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods \"symplectic integrators\", because they preserve energy and impulse better, but my memory may be leaky.","answer_url":"https://scicomp.stackexchange.com/a/45491","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-13T06:50:20+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2026-07-13T06:50:20+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}],"score":7,"updated_at":"2026-07-13T06:50:20+00:00"},{"answer_html":"

The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.

\n

In fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.

\n

For anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method

\n

And here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6

\n

The original comment was:

\n
\n

Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).

\n

Your RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.

\n

My advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.

\n
\n","answer_id":45503,"answer_text":"The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.","answer_url":"https://scicomp.stackexchange.com/a/45503","author":"Omar Osman Mahamoud","author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-29T16:42:27+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-29T16:42:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"DD32D002-9E3F-4398-BC22-FB7FBF667951","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}],"score":2,"updated_at":"2026-07-29T16:42:27+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T01:47:13+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"06EC415F-DC78-49A5-97D0-ED020CE6C74F","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T03:28:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"88B016CA-5B2E-46C7-99DA-7F374A3A0853","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T21:27:38+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"51F9060A-E0B8-4FC6-AAA1-D61ED8331962","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45490"},{"author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2026-07-13T06:50:20+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45491"},{"author":"Omar Osman Mahamoud","author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-29T16:42:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"DD32D002-9E3F-4398-BC22-FB7FBF667951","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45503"}],"question_author":"Omar Osman Mahamoud","question_author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud"},"code_blocks":[{"block_index":0,"code_text":"def euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n","post_id":"scicomp:45487","sha256":"cf0bde6333be3658682c2bbbf3514be3f691d7dfe36bcc4c07befe85d7046069","source_url":"https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"},{"block_index":1,"code_text":"def Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n","post_id":"scicomp:45487","sha256":"16f70485ac76c3d299f343fc55817b8b11ff0d5048050d78df40f99c7a3c34d5","source_url":"https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"},{"block_index":2,"code_text":"def Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n","post_id":"scicomp:45487","sha256":"664f217d728581a98996f2f18b9c12d83f56da4e8f3ec3511a3531d746e98194","source_url":"https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"},{"block_index":0,"code_text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","post_id":45490,"sha256":"0739849795b9b7d88e5352edf2511378cd32dd94d0652612d0afef3309011d46","source_url":"https://scicomp.stackexchange.com/a/45490"},{"block_index":1,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n","post_id":45490,"sha256":"5e92562921cb4c242909f38ee3d1a780addba783f5b7d0dce4ef1fffc163584d","source_url":"https://scicomp.stackexchange.com/a/45490"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"beca8c4610246c91accf92185c3232f2b3353eecd314278877621725d73e8a49","id":"SCT-6c88b8fe984f80f592145a39","language":null,"library_or_tool":null,"problem_text":"I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.\n\n\n\n\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.\n\n\n\n\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?\n\n\n\n\nHere are the three implementations.\n\n\n\n\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\n\n\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?","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":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-12T12:23:53+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"D3AC3DA9-7794-465F-AF03-B877C6C0EF0D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D3AC3DA9-7794-465F-AF03-B877C6C0EF0D/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-07-13T01:54:39+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"8CA42130-747B-47CA-BB4D-D7CD4CD70CC8","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/8CA42130-747B-47CA-BB4D-D7CD4CD70CC8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lutz Lehmann","profile_url":"https://scicomp.stackexchange.com/users/6839/lutz-lehmann","user_type":"registered"},"created_at":"2026-07-13T09:09:11+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"3FEC6861-FADA-4330-8FB0-12A8839B955D","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3FEC6861-FADA-4330-8FB0-12A8839B955D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-15T23:49:16+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"7914AE3D-629C-4FCA-BF96-6D9824005EDC","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/7914AE3D-629C-4FCA-BF96-6D9824005EDC/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-16T00:10:59+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"62C0155C-4F90-4C15-8CFB-EDCF7BC7548E","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/62C0155C-4F90-4C15-8CFB-EDCF7BC7548E/view-source"},{"content_license":null,"contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-16T11:22:30+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"BAF51E0F-7B50-4443-B0DF-BC44A34EF5BE","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BAF51E0F-7B50-4443-B0DF-BC44A34EF5BE/view-source"}],"source_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":"45487","source_record_sha256":"fb2f9716a3a897b863e97190af8c04de26251c428debde3c07b71878bf637e9f","source_url":"https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.

\n

However, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.

\n

I've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?

\n

Here are the three implementations.

\n
def euler_function(\n        x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n    for i in range(n_steps):\n        ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        vx_earth += ax_earth * dt\n        vy_earth += ay_earth * dt\n\n        xpos.append(x_earth)\n        ypos.append(y_earth)\n\n        x_earth += vx_earth * dt\n        y_earth += vy_earth * dt\n\n    return xpos, ypos\n
\n
def Runge_kutta_function(\n        x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n    for i in range(n_steps):\n\n        ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        x_earth_mid = x_earth + vx_earth * (dt / 2)\n        y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n        vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n        vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n        ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n        ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n        vx_earth += ax_earth_mid * dt\n        vy_earth += ay_earth_mid * dt\n\n        xpos.append(x_earth)\n        ypos.append(y_earth)\n\n        x_earth += vx_earth_mid * dt\n        y_earth += vy_earth_mid * dt\n\n    return xpos, ypos\n
\n
def Verlet_function(\n        x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n    for i in range(n_steps):\n\n        ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        xpos.append(x_earth)\n        ypos.append(y_earth)\n\n        x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n        y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n        ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n        ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n        vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n        vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n    return xpos, ypos\n
\n

What am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?

\n","question_title":"Why do my RK2 and Velocity Verlet implementations produce less accurate orbits than Euler?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t","split":"train"} {"accepted_answer":{"answer_html":"
\n

What is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?

\n
\n

In general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs. You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.

\n
\n

Are there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?

\n
\n

Not that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.

\n

References

\n
    \n
  1. O.C. Zienkiewicz and J.Z. Zhu, The Superconvergent patch\nrecovery and a posteriori error estimators. Part 1. The\nrecovery technique, Int. J. Numer. Methods Eng., 33,\n1331-1364 (1992).
  2. \n
\n","answer_id":45494,"answer_text":"What is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?\n\n\n\n\n\n\n\nIn general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs (https://en.wikipedia.org/wiki/Glyph_(data_visualization)). You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.\n\n\n\n\n\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?\n\n\n\n\n\n\n\nNot that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.\n\n\n\n\nReferences\n\n\n\n\n\nO.C. Zienkiewicz and J.Z. Zhu, The Superconvergent patch\nrecovery and a posteriori error estimators. Part 1. The\nrecovery technique, Int. J. Numer. Methods Eng., 33,\n1331-1364 (1992).","answer_url":"https://scicomp.stackexchange.com/a/45494","author":"nicoguaro","author_url":"https://scicomp.stackexchange.com/users/9667/nicoguaro","author_user_type":"moderator","content_license":"CC BY-SA 4.0","created_at":"2026-07-14T14:45:43+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45493,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"nicoguaro","profile_url":"https://scicomp.stackexchange.com/users/9667/nicoguaro","user_type":"moderator"},"created_at":"2026-07-14T14:45:43+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2B037104-8D63-4873-B969-9C5B1E328135","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2B037104-8D63-4873-B969-9C5B1E328135/view-source"}],"score":2,"updated_at":"2026-07-14T14:45:43+00:00"},"answer_scores":[{"answer_id":45494,"score":2}],"answers":[{"answer_html":"
\n

What is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?

\n
\n

In general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs. You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.

\n
\n

Are there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?

\n
\n

Not that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.

\n

References

\n
    \n
  1. O.C. Zienkiewicz and J.Z. Zhu, The Superconvergent patch\nrecovery and a posteriori error estimators. Part 1. The\nrecovery technique, Int. J. Numer. Methods Eng., 33,\n1331-1364 (1992).
  2. \n
\n","answer_id":45494,"answer_text":"What is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?\n\n\n\n\n\n\n\nIn general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs (https://en.wikipedia.org/wiki/Glyph_(data_visualization)). You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.\n\n\n\n\n\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?\n\n\n\n\n\n\n\nNot that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.\n\n\n\n\nReferences\n\n\n\n\n\nO.C. Zienkiewicz and J.Z. Zhu, The Superconvergent patch\nrecovery and a posteriori error estimators. Part 1. The\nrecovery technique, Int. J. Numer. Methods Eng., 33,\n1331-1364 (1992).","answer_url":"https://scicomp.stackexchange.com/a/45494","author":"nicoguaro","author_url":"https://scicomp.stackexchange.com/users/9667/nicoguaro","author_user_type":"moderator","content_license":"CC BY-SA 4.0","created_at":"2026-07-14T14:45:43+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45493,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"nicoguaro","profile_url":"https://scicomp.stackexchange.com/users/9667/nicoguaro","user_type":"moderator"},"created_at":"2026-07-14T14:45:43+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2B037104-8D63-4873-B969-9C5B1E328135","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2B037104-8D63-4873-B969-9C5B1E328135/view-source"}],"score":2,"updated_at":"2026-07-14T14:45:43+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"nicoguaro","author_url":"https://scicomp.stackexchange.com/users/9667/nicoguaro","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"nicoguaro","profile_url":"https://scicomp.stackexchange.com/users/9667/nicoguaro","user_type":"moderator"},"created_at":"2026-07-14T14:45:43+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2B037104-8D63-4873-B969-9C5B1E328135","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2B037104-8D63-4873-B969-9C5B1E328135/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45494"}],"question_author":"Rasa R. Behboud","question_author_url":"https://scicomp.stackexchange.com/users/57047/rasa-r-behboud"},"code_blocks":[{"block_index":0,"code_text":"for i = 1:NoE\n\n nl = EL(i,1:NPE);\n\n for j = 1:NPE\n X(j,i) = ENL(nl(j),1) ...\n + scale*ENL(nl(j),4*PD+1);\n\n Y(j,i) = ENL(nl(j),2) ...\n + scale*ENL(nl(j),4*PD+2);\n end\n\n for j = 1:NPE\n val = stress(i,:,1,1);\n stress_xx(j,i) = val(1,j);\n end\nend\n","post_id":"scicomp:45493","sha256":"87eaa06191380585ef32730ecff3af70a014452f45d3e650fcab2e4335913bb4","source_url":"https://scicomp.stackexchange.com/questions/45493/how-should-gauss-point-stresses-be-plotted-for-q8-serendipity-finite-elements-wi"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"f60dd2981c0e957bd1a3d61c310c9286e29f4e23dccf92093f1917c5f406bea2","id":"SCT-3bd50a9ba375aa9f37de8a7c","language":["matlab"],"library_or_tool":["matlab"],"problem_text":"I am implementing a two-dimensional displacement-based finite element code in MATLAB.\n\n\n\n\nFor a Q4 element, stress and strain are calculated at four (2\\times2) Gauss integration points. In my current post-processing code, I use:\n\n\n\n\nfor i = 1:NoE\n\n nl = EL(i,1:NPE);\n\n for j = 1:NPE\n X(j,i) = ENL(nl(j),1) ...\n + scale*ENL(nl(j),4*PD+1);\n\n Y(j,i) = ENL(nl(j),2) ...\n + scale*ENL(nl(j),4*PD+2);\n end\n\n for j = 1:NPE\n val = stress(i,:,1,1);\n stress_xx(j,i) = val(1,j);\n end\nend\n\n\n\n\n\nI then use the nodal-coordinate arrays X and Y, together with stress_xx, to produce a colored element plot.\n\n\n\n\nI now understand that this does not actually calculate stress at the nodes. It simply associates stress at Gauss point (j) with the coordinates of local node (j). The fact that Q4 has four nodes and four Gauss points made this one-to-one assignment appear reasonable, although the Gauss points and nodes have different coordinates.\n\n\n\n\nMy supervisor also pointed out that treating stress as a unique nodal quantity is generally incorrect in a standard displacement-based FEM. Displacement is continuous across element boundaries, but its gradients, strains, and stresses are element-wise quantities and can jump across adjacent elements.\n\n\n\n\nI am now implementing a Q8 element using (3\\times3) Gaussian integration. Therefore, every element has eight nodes but nine Gauss-point stress values. A direct assignment is no longer even numerically possible because there is no Q8 node corresponding to the center Gauss point.\n\n\n\n\nMy questions are:\n\n\n\n\n\nWhat is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?\n\n\n\n\nShould I map the Gauss-point coordinates from the parent element to the physical element and plot the values directly?\n\n\n\n\nHow can I construct an element-wise contour plot that preserves possible stress jumps across element boundaries?\n\n\n\n\nIs Gauss-point-to-node extrapolation appropriate only for a recovered or smoothed visualization field, rather than for representing the original finite element stress field?\n\n\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?\n\n\n\n\n\nI want to avoid discarding the ninth Gauss-point value, arbitrarily attaching Gauss-point values to nodes, or presenting an averaged nodal stress field as though it were the original FEM stress solution.","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":"Rasa R. Behboud","profile_url":"https://scicomp.stackexchange.com/users/57047/rasa-r-behboud","user_type":"registered"},"created_at":"2026-07-14T08:51:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"0DE2EEFB-055C-46F0-8FDE-C3A7A6127CDE","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0DE2EEFB-055C-46F0-8FDE-C3A7A6127CDE/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":"45493","source_record_sha256":"b4782322b9a3a66fcdfbf3064a9a1c7b2c84dd5894b24360f7ef3f08ef675a51","source_url":"https://scicomp.stackexchange.com/questions/45493/how-should-gauss-point-stresses-be-plotted-for-q8-serendipity-finite-elements-wi","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am implementing a two-dimensional displacement-based finite element code in MATLAB.

\n

For a Q4 element, stress and strain are calculated at four (2\\times2) Gauss integration points. In my current post-processing code, I use:

\n
for i = 1:NoE\n\n nl = EL(i,1:NPE);\n\n for j = 1:NPE\n     X(j,i) = ENL(nl(j),1) ...\n            + scale*ENL(nl(j),4*PD+1);\n\n     Y(j,i) = ENL(nl(j),2) ...\n            + scale*ENL(nl(j),4*PD+2);\n end\n\n for j = 1:NPE\n     val = stress(i,:,1,1);\n     stress_xx(j,i) = val(1,j);\n end\nend\n
\n

I then use the nodal-coordinate arrays X and Y, together with stress_xx, to produce a colored element plot.

\n

I now understand that this does not actually calculate stress at the nodes. It simply associates stress at Gauss point (j) with the coordinates of local node (j). The fact that Q4 has four nodes and four Gauss points made this one-to-one assignment appear reasonable, although the Gauss points and nodes have different coordinates.

\n

My supervisor also pointed out that treating stress as a unique nodal quantity is generally incorrect in a standard displacement-based FEM. Displacement is continuous across element boundaries, but its gradients, strains, and stresses are element-wise quantities and can jump across adjacent elements.

\n

I am now implementing a Q8 element using (3\\times3) Gaussian integration. Therefore, every element has eight nodes but nine Gauss-point stress values. A direct assignment is no longer even numerically possible because there is no Q8 node corresponding to the center Gauss point.

\n

My questions are:

\n
    \n
  1. What is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?
  2. \n
  3. Should I map the Gauss-point coordinates from the parent element to the physical element and plot the values directly?
  4. \n
  5. How can I construct an element-wise contour plot that preserves possible stress jumps across element boundaries?
  6. \n
  7. Is Gauss-point-to-node extrapolation appropriate only for a recovered or smoothed visualization field, rather than for representing the original finite element stress field?
  8. \n
  9. Are there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?
  10. \n
\n

I want to avoid discarding the ninth Gauss-point value, arbitrarily attaching Gauss-point values to nodes, or presenting an averaged nodal stress field as though it were the original FEM stress solution.

\n","question_title":"How should Gauss-point stresses be plotted for Q8 Serendipity finite elements without treating them as nodal values?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45493/how-should-gauss-point-stresses-be-plotted-for-q8-serendipity-finite-elements-wi","split":"train"} {"accepted_answer":{"answer_html":"

Your loop structure to accumulate the acceleration is wrong:

\n
# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n    for j in range(len(x)):\n        for k in range(len(x)):\n            if j != k: # so that a body doesn't interact with its self\n                # Gravitational acceleration exerted by body k on body j\n                ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n                ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n    [...]\n
\n

ax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.

\n","answer_id":45500,"answer_text":"Your loop structure to accumulate the acceleration is wrong:\n\n\n\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n\n\n\n\n\nax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.","answer_url":"https://scicomp.stackexchange.com/a/45500","author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-26T12:40:27+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45499,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2026-07-26T12:40:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B8255433-9052-441D-AE6B-91B2BE5FFF23","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B8255433-9052-441D-AE6B-91B2BE5FFF23/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2026-07-26T14:51:43+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"C3E76714-CDFD-4384-97ED-7A06A938A6D3","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3E76714-CDFD-4384-97ED-7A06A938A6D3/view-source"}],"score":3,"updated_at":"2026-07-26T14:51:43+00:00"},"answer_scores":[{"answer_id":45500,"score":3},{"answer_id":45501,"score":4}],"answers":[{"answer_html":"

Your loop structure to accumulate the acceleration is wrong:

\n
# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n    for j in range(len(x)):\n        for k in range(len(x)):\n            if j != k: # so that a body doesn't interact with its self\n                # Gravitational acceleration exerted by body k on body j\n                ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n                ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n    [...]\n
\n

ax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.

\n","answer_id":45500,"answer_text":"Your loop structure to accumulate the acceleration is wrong:\n\n\n\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n\n\n\n\n\nax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.","answer_url":"https://scicomp.stackexchange.com/a/45500","author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-26T12:40:27+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45499,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2026-07-26T12:40:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B8255433-9052-441D-AE6B-91B2BE5FFF23","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B8255433-9052-441D-AE6B-91B2BE5FFF23/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2026-07-26T14:51:43+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"C3E76714-CDFD-4384-97ED-7A06A938A6D3","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3E76714-CDFD-4384-97ED-7A06A938A6D3/view-source"}],"score":3,"updated_at":"2026-07-26T14:51:43+00:00"},{"answer_html":"

I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).

\n

Also, I feel the need to remind you that

\n
    \n
  1. you need to vectorise - Python is inherently brutally slow, so it doesn't surprise me that you're worrying about printing simulation time;
  2. \n
  3. you should be treating this as an IVP and leveraging a good library, which will (for our purposes) always do better than a naive implementation.
  4. \n
\n

Stopping short of rewriting this as an IVP for you, the vectorised version can look like:

\n
import numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201            # Step count\nyears = 0.95       # Duration (years)\ndt = years/(n-1)   # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array((  # (5,)\n    1.988475e30,  # Sol\n    0.330103e24,  # Mercury\n    4.867310e24,  # Venus\n    5.972170e24,  # Earth\n    0.641691e24,  # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n    (0.,         0.),  # Sol\n    (0.387098,   0.),  # Mercury\n    (0.723332,   0.),  # Venus\n    (1.,         0.),  # Earth\n    (1.52368055, 0.),  # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array((  # (5,2)\n    (0.,  0.    ),  # Sol\n    (0., 47.36  ),  # Mercury\n    (0., 35.02  ),  # Venus\n    (0., 29.7827),  # Earth\n    (0., 24.07  ),  # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n"""\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n  [1, 2, 3, 2, 3, 3]]\n"""\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1))  # (2,10)\nj, k = indices  # each (10,)\n\n"""\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n   jk jk jk jk jk jk\n   01 02 03 12 13 23\nj0  1  1  1 \nj1 -1        1  1\nj2    -1    -1     1\nj3       -1    -1 -1   signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00,  3.9e-04, -0.0e+00,  9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00,  3.9e-04, -0.0e+00,  9.7e-10,  1.2e-09]]\n"""\nA = np.zeros((mass.size, j.size))  # (5,10)\ni = np.arange(j.size)  # (10,)\ndt_G_mass = dt*G*mass  # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] =  (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n    pj, pk = all_p[i, indices]  # Interaction previous positions, each (10,2)\n    r = pj - pk  # (10,2)       # Interaction displacement, effectively xy[j] - xy[k]\n\n    # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n    norms = np.linalg.norm(r, axis=1, keepdims=1)**-3  # (10,1)\n\n    # Gravitational acceleration exerted by body k on body j\n    v += A @ (norms * r)          # Effectively: vxy[l] += axy[l] * dt\n    all_p[i+1] = all_p[i] + v*dt  # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n    ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n    all_p.transpose((1, 2, 0)),\n):\n    ax.plot(*data, label=name)\nax.legend()\nplt.show()\n
\n

\"orbit\"

\n

\"detail\"

\n","answer_id":45501,"answer_text":"I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).\n\n\n\n\nAlso, I feel the need to remind you that\n\n\n\n\n\nyou need to vectorise - Python is inherently brutally slow, so it doesn't surprise me that you're worrying about printing simulation time;\n\n\n\n\nyou should be treating this as an IVP and leveraging a good library, which will (for our purposes) always do better than a naive implementation.\n\n\n\n\n\nStopping short of rewriting this as an IVP for you, the vectorised version can look like:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201 # Step count\nyears = 0.95 # Duration (years)\ndt = years/(n-1) # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array(( # (5,)\n 1.988475e30, # Sol\n 0.330103e24, # Mercury\n 4.867310e24, # Venus\n 5.972170e24, # Earth\n 0.641691e24, # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n (0., 0.), # Sol\n (0.387098, 0.), # Mercury\n (0.723332, 0.), # Venus\n (1., 0.), # Earth\n (1.52368055, 0.), # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array(( # (5,2)\n (0., 0. ), # Sol\n (0., 47.36 ), # Mercury\n (0., 35.02 ), # Venus\n (0., 29.7827), # Earth\n (0., 24.07 ), # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n\"\"\"\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n [1, 2, 3, 2, 3, 3]]\n\"\"\"\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1)) # (2,10)\nj, k = indices # each (10,)\n\n\"\"\"\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n jk jk jk jk jk jk\n 01 02 03 12 13 23\nj0 1 1 1 \nj1 -1 1 1\nj2 -1 -1 1\nj3 -1 -1 -1 signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, 1.2e-09]]\n\"\"\"\nA = np.zeros((mass.size, j.size)) # (5,10)\ni = np.arange(j.size) # (10,)\ndt_G_mass = dt*G*mass # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] = (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n pj, pk = all_p[i, indices] # Interaction previous positions, each (10,2)\n r = pj - pk # (10,2) # Interaction displacement, effectively xy[j] - xy[k]\n\n # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n norms = np.linalg.norm(r, axis=1, keepdims=1)**-3 # (10,1)\n\n # Gravitational acceleration exerted by body k on body j\n v += A @ (norms * r) # Effectively: vxy[l] += axy[l] * dt\n all_p[i+1] = all_p[i] + v*dt # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n all_p.transpose((1, 2, 0)),\n):\n ax.plot(*data, label=name)\nax.legend()\nplt.show()\n\n\n\n\n\n[image: orbit; source: https://i.sstatic.net/LhxHLqTd.png] (https://i.sstatic.net/LhxHLqTd.png)\n\n\n\n\n[image: detail; source: https://i.sstatic.net/4hfjqDYL.png] (https://i.sstatic.net/4hfjqDYL.png)","answer_url":"https://scicomp.stackexchange.com/a/45501","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-26T21:58:33+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":45499,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T21:58:33+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EF321E57-4E53-4FF8-8A71-168FCE2ABCEA","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EF321E57-4E53-4FF8-8A71-168FCE2ABCEA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T22:17:48+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"3395FCAD-0F42-401F-82C1-7A4A3F6DD667","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3395FCAD-0F42-401F-82C1-7A4A3F6DD667/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T23:16:40+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B57EC924-2004-47BD-8F48-18BF4689A68A","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B57EC924-2004-47BD-8F48-18BF4689A68A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T23:59:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"24BECCC5-5481-4A1E-9914-5605FB3E7FBA","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/24BECCC5-5481-4A1E-9914-5605FB3E7FBA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-27T00:13:00+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"100FC7CD-8D17-4210-AF56-663AB1987016","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/100FC7CD-8D17-4210-AF56-663AB1987016/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-27T22:23:55+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"0A4D6874-4E2E-4411-82AD-5833BB738B39","revision_number":6,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0A4D6874-4E2E-4411-82AD-5833BB738B39/view-source"}],"score":4,"updated_at":"2026-07-27T22:23:55+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2026-07-26T12:40:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B8255433-9052-441D-AE6B-91B2BE5FFF23","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B8255433-9052-441D-AE6B-91B2BE5FFF23/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2026-07-26T14:51:43+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"C3E76714-CDFD-4384-97ED-7A06A938A6D3","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3E76714-CDFD-4384-97ED-7A06A938A6D3/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45500"},{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T21:58:33+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EF321E57-4E53-4FF8-8A71-168FCE2ABCEA","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EF321E57-4E53-4FF8-8A71-168FCE2ABCEA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T22:17:48+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"3395FCAD-0F42-401F-82C1-7A4A3F6DD667","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3395FCAD-0F42-401F-82C1-7A4A3F6DD667/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T23:16:40+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B57EC924-2004-47BD-8F48-18BF4689A68A","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B57EC924-2004-47BD-8F48-18BF4689A68A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-26T23:59:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"24BECCC5-5481-4A1E-9914-5605FB3E7FBA","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/24BECCC5-5481-4A1E-9914-5605FB3E7FBA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-27T00:13:00+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"100FC7CD-8D17-4210-AF56-663AB1987016","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/100FC7CD-8D17-4210-AF56-663AB1987016/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-27T22:23:55+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"0A4D6874-4E2E-4411-82AD-5833BB738B39","revision_number":6,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0A4D6874-4E2E-4411-82AD-5833BB738B39/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45501"}],"question_author":"Omar Osman Mahamoud","question_author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport winsound as ws\nfrom matplotlib.animation import FuncAnimation\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * (np.pi)**2\n\n# Distance from the Sun in astronomical units (AU)\n# 1 AU ≈ 149.6 million km\n\n# Initial x coordinates\nx = [\n 1, # Earth\n 1.5237, # Mars\n 0 # Sun\n]\n\n# Initial y coordinates\ny = [\n 0, # Earth\n 0, # Mars\n 0 # Sun\n]\n\n# Lists storing the x coordinates during the simulation\nxpos = [[], [], []]\n\n# Lists storing the y coordinates during the simulation\nypos = [[], [], []]\n\n# Initial velocity components (AU/year)\nvx = [0, 0, 0]\n\n# Initial tangential velocities (AU/year)\nvy = [\n 6.281991687112502, # Earth\n 5.0867271316753815, # Mars \n 0 # Sun\n]\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n# Masses expressed in solar masses\nmass = [\n 3.002513826043238e-06, # Earth\n 3.2267471091000503e-07, # Mars \n 1 # Sun\n]\n\n# Time step (years)\ndt = 0.00001\n\nstart_time = time.time()\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n for l in range(len(x)):\n\n # Velocity update\n vx[l] += ax[l] * dt\n vy[l] += ay[l] * dt\n\n # Store trajectory\n xpos[l].append(x[l])\n ypos[l].append(y[l])\n\n # Position update\n x[l] += vx[l] * dt\n y[l] += vy[l] * dt\n\nend_time = time.time()\n\nprint(f\"Simulation time: {end_time-start_time:.2f} s\")\n\n# Audible notification when the simulation is finished\nws.Beep(400, 1000)\n\nplt.plot(xpos[0], ypos[0], label=\"Earth\", color=\"green\")\nplt.plot(xpos[1], ypos[1], label=\"mars\", color=\"violet\")\nplt.plot(xpos[2], ypos[2], label=\"sun\", color=\"red\")\n\nplt.legend()\nplt.show()\n","post_id":"scicomp:45499","sha256":"1193dd9ea00fe201629657cad0dde25ee0cee1a068ec95b37b0726b48dbb6bae","source_url":"https://scicomp.stackexchange.com/questions/45499/n-body-gravitation"},{"block_index":1,"code_text":"ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])\n","post_id":"scicomp:45499","sha256":"9fb3a484706fe427bc57e8d0c75e35bf63ad7f2bbd04f79d633363f91cefdafa","source_url":"https://scicomp.stackexchange.com/questions/45499/n-body-gravitation"},{"block_index":2,"code_text":"ax[j] += -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] += -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n","post_id":"scicomp:45499","sha256":"8ca362cac5dfcdd1ed56990639a72f8a6d1dc714d67d6a9368853e72e7217ac6","source_url":"https://scicomp.stackexchange.com/questions/45499/n-body-gravitation"},{"block_index":0,"code_text":"# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n","post_id":45500,"sha256":"d8a80be1b3d545d7a5d9a8c80a53a62dfbc51b9d04d89fc45edd4c4bac91c856","source_url":"https://scicomp.stackexchange.com/a/45500"},{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201 # Step count\nyears = 0.95 # Duration (years)\ndt = years/(n-1) # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array(( # (5,)\n 1.988475e30, # Sol\n 0.330103e24, # Mercury\n 4.867310e24, # Venus\n 5.972170e24, # Earth\n 0.641691e24, # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n (0., 0.), # Sol\n (0.387098, 0.), # Mercury\n (0.723332, 0.), # Venus\n (1., 0.), # Earth\n (1.52368055, 0.), # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array(( # (5,2)\n (0., 0. ), # Sol\n (0., 47.36 ), # Mercury\n (0., 35.02 ), # Venus\n (0., 29.7827), # Earth\n (0., 24.07 ), # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n\"\"\"\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n [1, 2, 3, 2, 3, 3]]\n\"\"\"\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1)) # (2,10)\nj, k = indices # each (10,)\n\n\"\"\"\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n jk jk jk jk jk jk\n 01 02 03 12 13 23\nj0 1 1 1 \nj1 -1 1 1\nj2 -1 -1 1\nj3 -1 -1 -1 signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, 1.2e-09]]\n\"\"\"\nA = np.zeros((mass.size, j.size)) # (5,10)\ni = np.arange(j.size) # (10,)\ndt_G_mass = dt*G*mass # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] = (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n pj, pk = all_p[i, indices] # Interaction previous positions, each (10,2)\n r = pj - pk # (10,2) # Interaction displacement, effectively xy[j] - xy[k]\n\n # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n norms = np.linalg.norm(r, axis=1, keepdims=1)**-3 # (10,1)\n\n # Gravitational acceleration exerted by body k on body j\n v += A @ (norms * r) # Effectively: vxy[l] += axy[l] * dt\n all_p[i+1] = all_p[i] + v*dt # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n all_p.transpose((1, 2, 0)),\n):\n ax.plot(*data, label=name)\nax.legend()\nplt.show()\n","post_id":45501,"sha256":"925479250025ff4289341809174e50931ff902fe6be3335d7bb92bad8402a1de","source_url":"https://scicomp.stackexchange.com/a/45501"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"f7231ee05cfd60a5cfe68dc2da9803d92b4afd7f29384eade979c9fb8e8d04bd","id":"SCT-beb8bf5b1adadb339930dac1","language":null,"library_or_tool":["numpy"],"problem_text":"I implemented the following code to simulate an $N$-body gravitational system (here: the Sun, Earth, and Mars).\n\n\n\n\nThe code is:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport winsound as ws\nfrom matplotlib.animation import FuncAnimation\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * (np.pi)**2\n\n# Distance from the Sun in astronomical units (AU)\n# 1 AU ≈ 149.6 million km\n\n# Initial x coordinates\nx = [\n 1, # Earth\n 1.5237, # Mars\n 0 # Sun\n]\n\n# Initial y coordinates\ny = [\n 0, # Earth\n 0, # Mars\n 0 # Sun\n]\n\n# Lists storing the x coordinates during the simulation\nxpos = [[], [], []]\n\n# Lists storing the y coordinates during the simulation\nypos = [[], [], []]\n\n# Initial velocity components (AU/year)\nvx = [0, 0, 0]\n\n# Initial tangential velocities (AU/year)\nvy = [\n 6.281991687112502, # Earth\n 5.0867271316753815, # Mars \n 0 # Sun\n]\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n# Masses expressed in solar masses\nmass = [\n 3.002513826043238e-06, # Earth\n 3.2267471091000503e-07, # Mars \n 1 # Sun\n]\n\n# Time step (years)\ndt = 0.00001\n\nstart_time = time.time()\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n for l in range(len(x)):\n\n # Velocity update\n vx[l] += ax[l] * dt\n vy[l] += ay[l] * dt\n\n # Store trajectory\n xpos[l].append(x[l])\n ypos[l].append(y[l])\n\n # Position update\n x[l] += vx[l] * dt\n y[l] += vy[l] * dt\n\nend_time = time.time()\n\nprint(f\"Simulation time: {end_time-start_time:.2f} s\")\n\n# Audible notification when the simulation is finished\nws.Beep(400, 1000)\n\nplt.plot(xpos[0], ypos[0], label=\"Earth\", color=\"green\")\nplt.plot(xpos[1], ypos[1], label=\"mars\", color=\"violet\")\nplt.plot(xpos[2], ypos[2], label=\"sun\", color=\"red\")\n\nplt.legend()\nplt.show()\n\n\n\n\n\nThis produces the following result:\n\n\n\n\n[image: The resulte of the code above; source: https://i.sstatic.net/f5j0wZO6.png] (https://i.sstatic.net/f5j0wZO6.png)\n\n\n\n\nAt first glance, one might think the problem comes from the fact that I overwrite the acceleration instead of accumulating the contributions from all the other bodies.\n\n\n\n\nSo I changed\n\n\n\n\nax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])\n\n\n\n\n\nto\n\n\n\n\nax[j] += -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] += -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n\n\n\n\nsince the total acceleration acting on body j should be the sum of the accelerations produced by every other body.\n\n\n\n\nHowever, this actually makes the simulation even worse. The result becomes:\n\n\n\n\n[image: the result of the modified code; source: https://i.sstatic.net/cWWHipMg.png] (https://i.sstatic.net/cWWHipMg.png)\n\n\n\n\nSo I feel that I am missing something more fundamental.\n\n\n\n\nAnother thing I do not understand is the behavior of the Sun in the first version. Since the acceleration is overwritten, the Sun ends up accelerating only because of the last body processed in the loop (Mars). However, the Sun is much more massive than either Earth or Mars (1 >> 3.0025e-6 and 1 >> 3.2267e-7), so I would not expect such a large acceleration. Why does this happen?\n\n\n\n\nLikewise, why does the += version diverge so quickly instead of improving the simulation?\n\n\n\n\nMy ultimate goal is to simulate the Solar System (the Sun and the eight planets) using this double loop, but if the simulation is already unstable with only three bodies, I am clearly doing something wrong.\n\n\n\n\nFinally, I intentionally initialized the Sun with zero position, zero velocity, and zero acceleration because I wanted it to remain fixed at the origin, assuming that the Solar System barycenter is approximately at the center of the Sun.","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":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-26T12:32:03+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"61294F33-1CB8-459E-AB4B-4941AD8D2670","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/61294F33-1CB8-459E-AB4B-4941AD8D2670/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-07-27T11:52:44+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"3F7393D0-FAE5-408C-BCD8-32B84FC1BD39","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/3F7393D0-FAE5-408C-BCD8-32B84FC1BD39/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":"45499","source_record_sha256":"a6d3c552254236b4509dcc9f28f7c476a20da72f1cc54f9f1b0cbf538f5a0f12","source_url":"https://scicomp.stackexchange.com/questions/45499/n-body-gravitation","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I implemented the following code to simulate an $N$-body gravitational system (here: the Sun, Earth, and Mars).

\n

The code is:

\n
import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport winsound as ws\nfrom matplotlib.animation import FuncAnimation\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * (np.pi)**2\n\n# Distance from the Sun in astronomical units (AU)\n# 1 AU ≈ 149.6 million km\n\n# Initial x coordinates\nx = [\n    1,       # Earth\n    1.5237,  # Mars\n    0         # Sun\n]\n\n# Initial y coordinates\ny = [\n    0,  # Earth\n    0,  # Mars\n    0   # Sun\n]\n\n# Lists storing the x coordinates during the simulation\nxpos = [[], [], []]\n\n# Lists storing the y coordinates during the simulation\nypos = [[], [], []]\n\n# Initial velocity components (AU/year)\nvx = [0, 0, 0]\n\n# Initial tangential velocities (AU/year)\nvy = [\n    6.281991687112502,  # Earth\n    5.0867271316753815, # Mars             \n    0                   # Sun\n]\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n# Masses expressed in solar masses\nmass = [\n    3.002513826043238e-06,      # Earth\n    3.2267471091000503e-07,     # Mars               \n    1                           # Sun\n]\n\n# Time step (years)\ndt = 0.00001\n\nstart_time = time.time()\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(10**5):\n    for j in range(len(x)):\n        for k in range(len(x)):\n            if j != k: # so that a body doesn't interact with its self\n                # Gravitational acceleration exerted by body k on body j\n                ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n                ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n    for l in range(len(x)):\n\n        # Velocity update\n        vx[l] += ax[l] * dt\n        vy[l] += ay[l] * dt\n\n        # Store trajectory\n        xpos[l].append(x[l])\n        ypos[l].append(y[l])\n\n        # Position update\n        x[l] += vx[l] * dt\n        y[l] += vy[l] * dt\n\nend_time = time.time()\n\nprint(f"Simulation time: {end_time-start_time:.2f} s")\n\n# Audible notification when the simulation is finished\nws.Beep(400, 1000)\n\nplt.plot(xpos[0], ypos[0], label="Earth", color="green")\nplt.plot(xpos[1], ypos[1], label="mars", color="violet")\nplt.plot(xpos[2], ypos[2], label="sun", color="red")\n\nplt.legend()\nplt.show()\n
\n

This produces the following result:

\n

\"The

\n

At first glance, one might think the problem comes from the fact that I overwrite the acceleration instead of accumulating the contributions from all the other bodies.

\n

So I changed

\n
ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])\n
\n

to

\n
ax[j] += -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] += -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n
\n

since the total acceleration acting on body j should be the sum of the accelerations produced by every other body.

\n

However, this actually makes the simulation even worse. The result becomes:

\n

\"the

\n

So I feel that I am missing something more fundamental.

\n

Another thing I do not understand is the behavior of the Sun in the first version. Since the acceleration is overwritten, the Sun ends up accelerating only because of the last body processed in the loop (Mars). However, the Sun is much more massive than either Earth or Mars (1 >> 3.0025e-6 and 1 >> 3.2267e-7), so I would not expect such a large acceleration. Why does this happen?

\n

Likewise, why does the += version diverge so quickly instead of improving the simulation?

\n

My ultimate goal is to simulate the Solar System (the Sun and the eight planets) using this double loop, but if the simulation is already unstable with only three bodies, I am clearly doing something wrong.

\n

Finally, I intentionally initialized the Sun with zero position, zero velocity, and zero acceleration because I wanted it to remain fixed at the origin, assuming that the Solar System barycenter is approximately at the center of the Sun.

\n","question_title":"N-body gravitation","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45499/n-body-gravitation","split":"train"} {"accepted_answer":{"answer_html":"

You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.

\n

Let ufft be your current solution in frequency space, then:

\n
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n
\n

I'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.

\n","answer_id":45511,"answer_text":"You are \"dealiasing\" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.\n\n\n\n\nLet ufft be your current solution in frequency space, then:\n\n\n\n\nureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\n\n\n\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 \"Grain boundary velocity\". Depending on what your goals are you might also want to use pre-made phase-field software.","answer_url":"https://scicomp.stackexchange.com/a/45511","author":"niemc","author_url":"https://scicomp.stackexchange.com/users/50632/niemc","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-06T00:18:52+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45510,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"niemc","profile_url":"https://scicomp.stackexchange.com/users/50632/niemc","user_type":"registered"},"created_at":"2026-08-06T00:18:52+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2/view-source"}],"score":2,"updated_at":"2026-08-06T00:18:52+00:00"},"answer_scores":[{"answer_id":45511,"score":2}],"answers":[{"answer_html":"

You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.

\n

Let ufft be your current solution in frequency space, then:

\n
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n
\n

I'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.

\n","answer_id":45511,"answer_text":"You are \"dealiasing\" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.\n\n\n\n\nLet ufft be your current solution in frequency space, then:\n\n\n\n\nureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\n\n\n\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 \"Grain boundary velocity\". Depending on what your goals are you might also want to use pre-made phase-field software.","answer_url":"https://scicomp.stackexchange.com/a/45511","author":"niemc","author_url":"https://scicomp.stackexchange.com/users/50632/niemc","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-06T00:18:52+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45510,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"niemc","profile_url":"https://scicomp.stackexchange.com/users/50632/niemc","user_type":"registered"},"created_at":"2026-08-06T00:18:52+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2/view-source"}],"score":2,"updated_at":"2026-08-06T00:18:52+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"niemc","author_url":"https://scicomp.stackexchange.com/users/50632/niemc","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"niemc","profile_url":"https://scicomp.stackexchange.com/users/50632/niemc","user_type":"registered"},"created_at":"2026-08-06T00:18:52+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45511"}],"question_author":"Manav Jalan","question_author_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan"},"code_blocks":[{"block_index":0,"code_text":"# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n","post_id":"scicomp:45510","sha256":"4b699a38ac0a60297f7571f8542df84f21ad9915d6304dbef03624cde7723cf0","source_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio"},{"block_index":0,"code_text":"ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n","post_id":45511,"sha256":"bf6e3c4e955925e698cefc2a1209b1e9e5d424546243235be7f9469e57224119","source_url":"https://scicomp.stackexchange.com/a/45511"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"1f34eebb11d832f228fad67a66d7d7358a50b61b08a200479243f33dd3b85141","id":"SCT-55ab89b249a9d7536656f38b","language":null,"library_or_tool":null,"problem_text":"I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods (https://open.umich.edu/sites/default/files/downloads/2012-parallel-spectral-numerical-methods.pdf). Accordingly, I have implemented the scheme as follows::\n\n\n\n\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\n\n\n\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.","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":"Manav Jalan","profile_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan","user_type":"registered"},"created_at":"2026-08-05T11:30:29+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"89E117A0-D17A-486B-9AB6-3BFCFC57C353","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/89E117A0-D17A-486B-9AB6-3BFCFC57C353/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-06T12:01:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"669E53D8-1766-46EB-8CA1-42CE9017157D","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/669E53D8-1766-46EB-8CA1-42CE9017157D/view-source"}],"source_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":"45510","source_record_sha256":"6440d51489c2af8c0b1d243f5d9680747e3091a326007a87f31b5ea3b5179b92","source_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods. Accordingly, I have implemented the scheme as follows::

\n
# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n    fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n    u_t = np.fft.ifft2(fft)\n    cubed = (u_t.real*freq_mask) ** 3\n    cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n
\n

The code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.

\n","question_title":"Allen Cahn Psuedospectral solver blowup even after reaching steady state solution","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio","split":"test"} {"accepted_answer":{"answer_html":"

Your calculation

\n
vecaf[0]=vecf[0]-veca[0];  vecaf[1]=vecf[1]-vecf[0]\n
\n

is wrong. Notice your typo in the last vector term.

\n

But also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -

\n
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n    7 |     double pid;\n      |            ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n   38 |     vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n      |                   ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n   33 |     double vece[2];\n      |            ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n   38 |     vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n      |                           ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n   29 |     double vecd[2];\n      |            ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n
\n

More broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.

\n
import numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n
\n
cbcf = 88.56°\nabaf = 88.56°\n
\n

Finally:

\n
\n

the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$

\n
\n

This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,

\n
for n in range(5, 21, 2):\n    # ...\n
\n
n = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n
\n

You can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.

\n","answer_id":45524,"answer_text":"Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\n: In function 'main':\n:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\n\n\n\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.\n\n\n\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\n\n\n\n\ncbcf = 88.56°\nabaf = 88.56°\n\n\n\n\n\nFinally:\n\n\n\n\n\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$\n\n\n\n\n\n\n\nThis is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,\n\n\n\n\nfor n in range(5, 21, 2):\n # ...\n\n\n\n\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\n\n\n\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.","answer_url":"https://scicomp.stackexchange.com/a/45524","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-19T00:02:29+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45523,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:02:29+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2AA6BC7A-D0B8-417C-8564-356A9E73019D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2AA6BC7A-D0B8-417C-8564-356A9E73019D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:13:57+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"94F28792-4A20-400C-B334-5069EB06CEE2","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/94F28792-4A20-400C-B334-5069EB06CEE2/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:38:14+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"FC356EC3-01AB-4542-B1E1-94E478F8FE71","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FC356EC3-01AB-4542-B1E1-94E478F8FE71/view-source"}],"score":4,"updated_at":"2026-08-19T00:38:14+00:00"},"answer_scores":[{"answer_id":45524,"score":4}],"answers":[{"answer_html":"

Your calculation

\n
vecaf[0]=vecf[0]-veca[0];  vecaf[1]=vecf[1]-vecf[0]\n
\n

is wrong. Notice your typo in the last vector term.

\n

But also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -

\n
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n    7 |     double pid;\n      |            ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n   38 |     vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n      |                   ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n   33 |     double vece[2];\n      |            ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n   38 |     vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n      |                           ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n   29 |     double vecd[2];\n      |            ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n
\n

More broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.

\n
import numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n
\n
cbcf = 88.56°\nabaf = 88.56°\n
\n

Finally:

\n
\n

the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$

\n
\n

This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,

\n
for n in range(5, 21, 2):\n    # ...\n
\n
n = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n
\n

You can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.

\n","answer_id":45524,"answer_text":"Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\n: In function 'main':\n:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\n\n\n\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.\n\n\n\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\n\n\n\n\ncbcf = 88.56°\nabaf = 88.56°\n\n\n\n\n\nFinally:\n\n\n\n\n\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$\n\n\n\n\n\n\n\nThis is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,\n\n\n\n\nfor n in range(5, 21, 2):\n # ...\n\n\n\n\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\n\n\n\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.","answer_url":"https://scicomp.stackexchange.com/a/45524","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-19T00:02:29+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45523,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:02:29+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2AA6BC7A-D0B8-417C-8564-356A9E73019D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2AA6BC7A-D0B8-417C-8564-356A9E73019D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:13:57+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"94F28792-4A20-400C-B334-5069EB06CEE2","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/94F28792-4A20-400C-B334-5069EB06CEE2/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:38:14+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"FC356EC3-01AB-4542-B1E1-94E478F8FE71","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FC356EC3-01AB-4542-B1E1-94E478F8FE71/view-source"}],"score":4,"updated_at":"2026-08-19T00:38:14+00:00"}],"attempted_method_if_explicit":"I tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:","author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:02:29+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2AA6BC7A-D0B8-417C-8564-356A9E73019D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2AA6BC7A-D0B8-417C-8564-356A9E73019D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:13:57+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"94F28792-4A20-400C-B334-5069EB06CEE2","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/94F28792-4A20-400C-B334-5069EB06CEE2/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-08-19T00:38:14+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"FC356EC3-01AB-4542-B1E1-94E478F8FE71","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FC356EC3-01AB-4542-B1E1-94E478F8FE71/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45524"}],"question_author":"Stephen Elliott","question_author_url":"https://scicomp.stackexchange.com/users/57153/stephen-elliott"},"code_blocks":[{"block_index":0,"code_text":"Double: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n","post_id":"scicomp:45523","sha256":"c12d0f40e7972c2d22bba31495d9dcdddcb997bc8775e18b5a8befe6c599656e","source_url":"https://scicomp.stackexchange.com/questions/45523/why-are-the-results-from-my-c-program-to-calculate-critical-angles-for-a-regular"},{"block_index":1,"code_text":"Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n","post_id":"scicomp:45523","sha256":"edd8b8a66a4b178342b62e3a476f6dbdba138bc67a662718dde887221d8601f3","source_url":"https://scicomp.stackexchange.com/questions/45523/why-are-the-results-from-my-c-program-to-calculate-critical-angles-for-a-regular"},{"block_index":2,"code_text":"#include \n#include \n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double pid;\n // pid=acos(-1);\n // double DegreesToRadians = 3.14159265358979323846/180.0;\n // double DegreesToRadians = pid/180.0;\n // const double DegreesToRadians=3.14159265358979323846/180.0;\n double DegreesToRadians=acos(-1.0)/180.0;\n \n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n // 3. Print Results\n // %lf is the format specifier for double, %f is for float\n // printf(\"Double: cos(%.1lf degrees) = %lf\\n\", degrees_d, result_double);\n // printf(\"Float: cos(%.1f degrees) = %f\\n\", degrees_f, result_float);\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n\n printf(\"Double: acos(-1.0) %.15lf \\n\",acos(-1.0));\n printf(\"Double: vec cb dot vec cf %0.15lf\\n\", cbdotcf);\n printf(\"Double: vec ab dot vec af %0.15lf\\n\", abdotaf);\n printf(\"Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n\",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf(\"Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n\",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n\n return 0;\n}\n","post_id":"scicomp:45523","sha256":"d4dd5cef1c41c75eea8ba7438d44ccb705006f8157c9eef89e7eb8f70c25d8ab","source_url":"https://scicomp.stackexchange.com/questions/45523/why-are-the-results-from-my-c-program-to-calculate-critical-angles-for-a-regular"},{"block_index":3,"code_text":"#include \n#include \n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double DegreesToRadians = 3.14159265358979323846/180.0;\n\n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-veca[1];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n //Calculate the necessary dot products\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n // Print Results\n // %lf is the format specifier for double %l.15 is for 15 digits to the right\n // That amount of precision is consistant with the constant PI as a double float\n printf(\"Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \\n\");\n printf(\"Double: acos(-1.0) = %.15lf \\n\",acos(-1.0));\n printf(\"Constant 3.14159265358979323846 = %.15lf \\n\",3.14159265358979323846);\n printf(\"Double: acos(-1.0)/180.0 = %.15lf \\n\",acos(-1.0)/180.0);\n printf(\"Double: 3.14159265358979323846/180.0 = %.15lf \\n\",3.14159265358979323846/180.0);\n printf(\"Double: vec cb dot vec cf %0.15lf\\n\", cbdotcf);\n printf(\"Double: vec ab dot vec af %0.15lf\\n\", abdotaf);\n printf(\"Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n\",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf(\"Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n\",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n return 0;\n}\n","post_id":"scicomp:45523","sha256":"40ab1c239635a73c417b14307c38c127949e5a7cc9a7ecb7a9a13f5963aadce2","source_url":"https://scicomp.stackexchange.com/questions/45523/why-are-the-results-from-my-c-program-to-calculate-critical-angles-for-a-regular"},{"block_index":0,"code_text":"vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n","post_id":45524,"sha256":"3ebec4208ceb57aac08e2dae0fdcaafdecf46fce6a648ca6884a8c81f88470e2","source_url":"https://scicomp.stackexchange.com/a/45524"},{"block_index":1,"code_text":": In function 'main':\n:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n","post_id":45524,"sha256":"1a3c9d39bcefb26c735ab725b94739565017c9710ade1f42a7a5a13c88c281dd","source_url":"https://scicomp.stackexchange.com/a/45524"},{"block_index":2,"code_text":"import numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n","post_id":45524,"sha256":"cc7631c9b086240fdb9bff0d69b65c2653b97db4e6513b413f6962c26d848b43","source_url":"https://scicomp.stackexchange.com/a/45524"},{"block_index":3,"code_text":"cbcf = 88.56°\nabaf = 88.56°\n","post_id":45524,"sha256":"0a67cb37bbdc49ee89efc70256607d96e37e382603b0d274308054092d4d6b0e","source_url":"https://scicomp.stackexchange.com/a/45524"},{"block_index":4,"code_text":"for n in range(5, 21, 2):\n # ...\n","post_id":45524,"sha256":"728b6f315fc0098de355a6fe2c7e0ec231f31d4eea5e3feffa768961565aeb0a","source_url":"https://scicomp.stackexchange.com/a/45524"},{"block_index":5,"code_text":"n = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n","post_id":45524,"sha256":"71eb10d31ef69d7657613038dc5e354f38d2131b46e19c291c52aba62c7b3fa2","source_url":"https://scicomp.stackexchange.com/a/45524"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"5b44d2423c18a425977b844af69d490819ce2afde0840bc7c92dc486a6be522c","id":"SCT-9b42b7d8e0fb2956c399a1fe","language":null,"library_or_tool":null,"problem_text":"I am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:\n\n\n\n\nHow can the Referenced Regular Heptagon inscribed within a Unit Circle, with its center coinciding, be drawn using PostScript Programming Language? (https://scicomp.stackexchange.com/questions/45518/how-can-the-referenced-regular-heptagon-inscribed-within-a-unit-circle-with-its)\n\n\n\n\n[image: Image of the Regular Heptagon; source: https://i.sstatic.net/z1YPOvX5.png] (https://i.sstatic.net/z1YPOvX5.png)\n\n\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:\n\n\n\n\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\n\n\n\n\nThe Question: Where Are my C calculations Going Wrong?\n\n\n\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?\n\n\n\n\nUpdate: Answer Calculated, but Angles $\\angle BCF$ and\n$\\angle BAF$ are equal, but not $90^{\\circ}$\n\n\n\n\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: \"Figure. Regular Heptagon Image taken from a Math Stack Exchange Question\", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.\n\n\n\n\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:\n\n\n\n\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\n\n\n\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.\n\n\n\n\n\n\n\nFrom the question \"What could be this unknown angle in this regular\nheptagon?\" (https://math.stackexchange.com/questions/5146710/what-could-be-this-unknown-angle-in-this-regular-heptagon/5146818#5146818)\n\n\n\n\nThere is the image drawn of a Regular Heptagon:\n\n\n\n\n\n\n\n[image: Regular Heptagon Image taken from a Math Stack Exchange Question; source: https://i.sstatic.net/JpG0VRI2.jpg] (https://i.sstatic.net/JpG0VRI2.jpg) \nFigure. Regular Heptagon Image taken from a\nMath Stack Exchange Question\n\n\n\n\n\n\n\n\n\n\n\nAppendix: C Programming Language Source Code to Calculate Angles for a Regular Heptagon\n\n\n\n\nOn the site: https://www.onlinegdb.com/online_c_compiler (https://www.onlinegdb.com/online_c_compiler)\n\n\n\n\n#include \n#include \n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double pid;\n // pid=acos(-1);\n // double DegreesToRadians = 3.14159265358979323846/180.0;\n // double DegreesToRadians = pid/180.0;\n // const double DegreesToRadians=3.14159265358979323846/180.0;\n double DegreesToRadians=acos(-1.0)/180.0;\n \n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n // 3. Print Results\n // %lf is the format specifier for double, %f is for float\n // printf(\"Double: cos(%.1lf degrees) = %lf\\n\", degrees_d, result_double);\n // printf(\"Float: cos(%.1f degrees) = %f\\n\", degrees_f, result_float);\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n\n printf(\"Double: acos(-1.0) %.15lf \\n\",acos(-1.0));\n printf(\"Double: vec cb dot vec cf %0.15lf\\n\", cbdotcf);\n printf(\"Double: vec ab dot vec af %0.15lf\\n\", abdotaf);\n printf(\"Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n\",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf(\"Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n\",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n\n return 0;\n}\n\n\n\n\n\nAppendix: Updated C Source code to Calculate the Angles for $\\angle BCF$ and $\\angle BAF$\n\n\n\n\nTaking the suggestions from Reinderien's answer, the source code was updated. Using the online c compiler https://www.onlinegdb.com/online_c_compiler (https://www.onlinegdb.com/online_c_compiler), the below source code compiled fine and yielded angles very consistent with Reinderien's answer quoted below, with instead of 2 digits precision, 15 digit precision:\n\n\n\n\n\n\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56° \n\n\n\n\n\n\n\n#include \n#include \n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double DegreesToRadians = 3.14159265358979323846/180.0;\n\n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-veca[1];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n //Calculate the necessary dot products\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n // Print Results\n // %lf is the format specifier for double %l.15 is for 15 digits to the right\n // That amount of precision is consistant with the constant PI as a double float\n printf(\"Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \\n\");\n printf(\"Double: acos(-1.0) = %.15lf \\n\",acos(-1.0));\n printf(\"Constant 3.14159265358979323846 = %.15lf \\n\",3.14159265358979323846);\n printf(\"Double: acos(-1.0)/180.0 = %.15lf \\n\",acos(-1.0)/180.0);\n printf(\"Double: 3.14159265358979323846/180.0 = %.15lf \\n\",3.14159265358979323846/180.0);\n printf(\"Double: vec cb dot vec cf %0.15lf\\n\", cbdotcf);\n printf(\"Double: vec ab dot vec af %0.15lf\\n\", abdotaf);\n printf(\"Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n\",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf(\"Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n\",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n return 0;\n}","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":"Stephen Elliott","profile_url":"https://scicomp.stackexchange.com/users/57153/stephen-elliott","user_type":"registered"},"created_at":"2026-08-18T13:55:17+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B5777BFC-2E82-4C87-A959-0AFA25B2891D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B5777BFC-2E82-4C87-A959-0AFA25B2891D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Stephen Elliott","profile_url":"https://scicomp.stackexchange.com/users/57153/stephen-elliott","user_type":"registered"},"created_at":"2026-08-19T11:17:30+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"C043274E-7072-4F3E-B48B-C4F26D2DF886","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C043274E-7072-4F3E-B48B-C4F26D2DF886/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":"45523","source_record_sha256":"0ac491e5a27a01ce1019df303b993399bb18411fe237c572995ac09395a2603c","source_url":"https://scicomp.stackexchange.com/questions/45523/why-are-the-results-from-my-c-program-to-calculate-critical-angles-for-a-regular","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:

\n

How can the Referenced Regular Heptagon inscribed within a Unit Circle, with its center coinciding, be drawn using PostScript Programming Language?

\n

\"Image

\n

I tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:

\n
Double: acos(-1.0) 3.141592653589793 \nDouble:  vec cb dot vec cf 0.376510198141266\nDouble:  vec ab dot vec af 0.611260466978158\nDouble:  coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble:  cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n
\n

The Question: Where Are my C calculations Going Wrong?

\n

How can I debug the C program to arrive at reasonable values for the calculated angles?

\n

Update: Answer Calculated, but Angles $\\angle BCF$ and\n$\\angle BAF$ are equal, but not $90^{\\circ}$

\n

The source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: "Figure. Regular Heptagon Image taken from a Math Stack Exchange Question", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.

\n

I am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:

\n
Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble:  vec cb dot vec cf 0.037286231168214\nDouble:  vec ab dot vec af 0.037286231168214\nDouble:  coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble:  cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n
\n

I was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.

\n
\n

From the question "What could be this unknown angle in this regular\nheptagon?"

\n

There is the image drawn of a Regular Heptagon:

\n
\n

\"Regular
Figure. Regular Heptagon Image taken from a\nMath Stack Exchange Question

\n
\n
\n

Appendix: C Programming Language Source Code to Calculate Angles for a Regular Heptagon

\n

On the site: https://www.onlinegdb.com/online_c_compiler

\n
#include <stdio.h>\n#include <math.h>\n\nint main() {\n    // Define a constant for PI to convert degrees to radians\n    // const double PI = 3.14159265358979323846;\n    double pid;\n    // pid=acos(-1);\n    // double DegreesToRadians = 3.14159265358979323846/180.0;\n    // double DegreesToRadians = pid/180.0;\n    // const double DegreesToRadians=3.14159265358979323846/180.0;\n    double DegreesToRadians=acos(-1.0)/180.0;\n    \n    //setup vector angles a,b,c,d,e, and f needs to be calculated later\n    //setup veca angle to calculate veca vector later with 1 unit radius\n    const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n    double veca[2];\n\n    //setup vecb angle to calculate vecb vector later with 1 unit radius\n    const double vecb_angle = (90.0)*DegreesToRadians;\n    double vecb[2];\n    \n    //setup vecc angle to calculate vecc vector later with 1 unit radius\n    const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n    double vecc[2];\n\n    //setup vecd angle to calculate vecd vector later with 1 unit radius\n    const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n    double vecd[2];\n\n    //setup vece angle to calculate vecd vector later with 1 unit radius\n    const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n    double vece[2];\n\n    //vector vecf needs to be calculated later as half vece + vecd\n    double vecf[2];\n   //compute cooordinate vector f as 0.5*(e+d)\n    vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n    //compute cooordinate vectors a through e\n    veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n    vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n    vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n    vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n    vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n    //vector veccb needs to be calculated later as vector B - vector C\n    double veccb[2];\n    veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n    //vector vecab needs to be calculated later as vector B - vector A\n    double vecab[2];\n    vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n    //vector vecaf needs to be calculated later as vector F - vector A\n    double vecaf[2];\n    vecaf[0]=vecf[0]-veca[0];  vecaf[1]=vecf[1]-vecf[0];\n\n    //vector veccf needs to be calculated later as vector F - vector C\n    double veccf[2];\n    veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n    // 3. Print Results\n    // %lf is the format specifier for double, %f is for float\n    // printf("Double: cos(%.1lf degrees) = %lf\\n", degrees_d, result_double);\n    // printf("Float:  cos(%.1f degrees) = %f\\n", degrees_f, result_float);\n    double cbdotcf;\n    cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n    double abdotaf;\n    abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n    double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n                     /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n    double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n                     /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n\n    printf("Double: acos(-1.0) %.15lf \\n",acos(-1.0));\n    printf("Double:  vec cb dot vec cf %0.15lf\\n", cbdotcf);\n    printf("Double:  vec ab dot vec af %0.15lf\\n", abdotaf);\n    printf("Double:  coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n        180.0/acos(-1.0)*acos(coscbcf));\n    printf("Double:  cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n        180.0/acos(-1.0)*acos(cosabaf));\n\n    return 0;\n}\n
\n

Appendix: Updated C Source code to Calculate the Angles for $\\angle BCF$ and $\\angle BAF$

\n

Taking the suggestions from Reinderien's answer, the source code was updated. Using the online c compiler https://www.onlinegdb.com/online_c_compiler, the below source code compiled fine and yielded angles very consistent with Reinderien's answer quoted below, with instead of 2 digits precision, 15 digit precision:

\n
\n

n = 7\ncbcf = 88.56°\nabaf = 88.56°

\n
\n
#include <stdio.h>\n#include <math.h>\n\nint main() {\n    // Define a constant for PI to convert degrees to radians\n    // const double PI = 3.14159265358979323846;\n    double DegreesToRadians = 3.14159265358979323846/180.0;\n\n    //setup vector angles a,b,c,d,e, and f needs to be calculated later\n    //setup veca angle to calculate veca vector later with 1 unit radius\n    const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n    double veca[2];\n\n    //setup vecb angle to calculate vecb vector later with 1 unit radius\n    const double vecb_angle = (90.0)*DegreesToRadians;\n    double vecb[2];\n    \n    //setup vecc angle to calculate vecc vector later with 1 unit radius\n    const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n    double vecc[2];\n\n    //setup vecd angle to calculate vecd vector later with 1 unit radius\n    const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n    double vecd[2];\n\n    //setup vece angle to calculate vecd vector later with 1 unit radius\n    const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n    double vece[2];\n\n    //compute cooordinate vectors a through e\n    veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n    vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n    vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n    vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n    vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n\n    //vector vecf needs to be calculated later as half vece + vecd\n    double vecf[2];\n   //compute cooordinate vector f as 0.5*(e+d)\n    vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n    //vector veccb needs to be calculated later as vector B - vector C\n    double veccb[2];\n    veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n    //vector vecab needs to be calculated later as vector B - vector A\n    double vecab[2];\n    vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n    //vector vecaf needs to be calculated later as vector F - vector A\n    double vecaf[2];\n    vecaf[0]=vecf[0]-veca[0];  vecaf[1]=vecf[1]-veca[1];\n\n    //vector veccf needs to be calculated later as vector F - vector C\n    double veccf[2];\n    veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n    //Calculate the necessary dot products\n    double cbdotcf;\n    cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n    double abdotaf;\n    abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n    double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n                     /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n    double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n                     /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n    // Print Results\n    // %lf is the format specifier for double %l.15 is for 15 digits to the right\n    // That amount of precision is consistant with the constant PI as a double float\n    printf("Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \\n");\n    printf("Double: acos(-1.0) = %.15lf \\n",acos(-1.0));\n    printf("Constant 3.14159265358979323846 = %.15lf \\n",3.14159265358979323846);\n    printf("Double: acos(-1.0)/180.0 = %.15lf \\n",acos(-1.0)/180.0);\n    printf("Double: 3.14159265358979323846/180.0 = %.15lf \\n",3.14159265358979323846/180.0);\n    printf("Double:  vec cb dot vec cf %0.15lf\\n", cbdotcf);\n    printf("Double:  vec ab dot vec af %0.15lf\\n", abdotaf);\n    printf("Double:  coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n        180.0/acos(-1.0)*acos(coscbcf));\n    printf("Double:  cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n        180.0/acos(-1.0)*acos(cosabaf));\n    return 0;\n}\n
\n","question_title":"Why are the results from my C program to calculate critical angles for a Regular Heptagon not yielding reasonable results?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45523/why-are-the-results-from-my-c-program-to-calculate-critical-angles-for-a-regular","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45531,"score":3}],"answers":[{"answer_html":"

I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.

\n

Here is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.

\n
import sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n    math.prod(\n    [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n    )\n    for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n    [\n        [\n            sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n            for j in range(len(nodes))\n        ]\n        for i in range(len(nodes))\n    ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n    A[\n        (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n        (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n    ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n    for j in range(len(nodes)):\n\n        b[(len(nodes) - 1) * i + j, 0] += (\n            sympy.integrate(\n                basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n            )\n            * detJ\n        )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n
\n

\"sol\"

\n

Here are a few finite element specific resources:

\n\n

For how to analyze the general stability of numerical discretizations:

\n\n","answer_id":45531,"answer_text":"I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.\n\n\n\n\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.\n\n\n\n\nimport sympy\nimport math\n\nxi = sympy.Symbol(\"xi\")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol(\"x\")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\n\n\n\n[image: sol; source: https://i.sstatic.net/lGjPuZl9.png] (https://i.sstatic.net/lGjPuZl9.png)\n\n\n\n\nHere are a few finite element specific resources:\n\n\n\n\n\nThe Finite Element Method: Its Basis and Fundamentals (https://www.sciencedirect.com/book/monograph/9781856176330/the-finite-element-method-its-basis-and-fundamentals) by Zienkiewics et al.\n\n\n\n\nFinite Elements I (https://doi.org/10.1007/978-3-030-56341-7) by Ern and Guermond (there's also a II and III)\n\n\n\n\nThe Mathematical Theory of Finite Element Methods (https://doi.org/10.1007/978-0-387-75934-0) by Brenner and Scott\n\n\n\n\nNodal Discontinuous Galerkin Methods (https://doi.org/10.1007/978-0-387-72067-8) by Hesthaven and Warburton\n\n\n\n\n\nFor how to analyze the general stability of numerical discretizations:\n\n\n\n\n\nFinite Difference Methods for Ordinary and Partial Differential Equations: Steady-State and Time-Dependent Problems (https://epubs.siam.org/doi/book/10.1137/1.9780898717839) by LeVeque\n\n\n\n\nSolving Ordinary Differential Equations I (https://doi.org/10.1007/978-3-540-78862-1) by Hairer et al. (there's also a II)","answer_url":"https://scicomp.stackexchange.com/a/45531","author":"helloworld922","author_url":"https://scicomp.stackexchange.com/users/1295/helloworld922","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-31T07:00:04+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":45530,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"helloworld922","profile_url":"https://scicomp.stackexchange.com/users/1295/helloworld922","user_type":"registered"},"created_at":"2026-08-31T07:00:04+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"7CCE8B46-6AEC-40C9-A3E6-5955A7DA625E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/7CCE8B46-6AEC-40C9-A3E6-5955A7DA625E/view-source"}],"score":3,"updated_at":"2026-08-31T07:00:04+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"helloworld922","author_url":"https://scicomp.stackexchange.com/users/1295/helloworld922","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"helloworld922","profile_url":"https://scicomp.stackexchange.com/users/1295/helloworld922","user_type":"registered"},"created_at":"2026-08-31T07:00:04+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"7CCE8B46-6AEC-40C9-A3E6-5955A7DA625E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/7CCE8B46-6AEC-40C9-A3E6-5955A7DA625E/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45531"}],"question_author":"Researcher R","question_author_url":"https://scicomp.stackexchange.com/users/53321/researcher-r"},"code_blocks":[{"block_index":0,"code_text":"from dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = \"Lagrange\" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure(\"dx\", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = \"preonly\" # Preconditioning Matrix Option\nsolver_type = \"lu\" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix=\"first_order_ODE\", bcs = [bc], petsc_options={\"ksp_type\": ksp_type, \"pc_type\": solver_type})\nu_sol = problem.solve()\n","post_id":"scicomp:45530","sha256":"58939fbd06efafe4e7b4ac47177bb119412a18b22eb2d7c341154b00f1d7478f","source_url":"https://scicomp.stackexchange.com/questions/45530/are-there-any-resources-which-cover-finding-stable-weak-forms-to-1st-order-diffe"},{"block_index":0,"code_text":"import sympy\nimport math\n\nxi = sympy.Symbol(\"xi\")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol(\"x\")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n","post_id":45531,"sha256":"78948cc3608f1a63a2de2bd121547ac6bed61c12bc60057061d54da136ef25ce","source_url":"https://scicomp.stackexchange.com/a/45531"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"fc6e4aa62c5b39d08b716de998903e11f4c87558e968837f6a17c9e02592c212","id":"SCT-3c789c6f1ddeef49e8562e93","language":null,"library_or_tool":["numpy"],"problem_text":"I need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled \"Finite Element Method\", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.\n\n\n\n\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?\n\n\n\n\n\n\n\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided\n\n\n\n\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = \"Lagrange\" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure(\"dx\", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = \"preonly\" # Preconditioning Matrix Option\nsolver_type = \"lu\" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix=\"first_order_ODE\", bcs = [bc], petsc_options={\"ksp_type\": ksp_type, \"pc_type\": solver_type})\nu_sol = problem.solve()\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/8M1U5hQT.png] (https://i.sstatic.net/8M1U5hQT.png)\n\n\n\n\nwe can see the solution is infinity at all node values of the functionspace.","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":"Researcher R","profile_url":"https://scicomp.stackexchange.com/users/53321/researcher-r","user_type":"registered"},"created_at":"2026-08-30T03:46:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"8A694B8D-C740-489D-AB57-AFCBA245C49D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/8A694B8D-C740-489D-AB57-AFCBA245C49D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Researcher R","profile_url":"https://scicomp.stackexchange.com/users/53321/researcher-r","user_type":"registered"},"created_at":"2026-08-30T23:41:50+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-31T23:54:34+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8/view-source"}],"source_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":"45530","source_record_sha256":"5d025e3a7932de94e0b9cb040abb9d6b2cecb69b971fa2adf75722d8ebf14359","source_url":"https://scicomp.stackexchange.com/questions/45530/are-there-any-resources-which-cover-finding-stable-weak-forms-to-1st-order-diffe","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled "Finite Element Method", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.

\n

Would a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?

\n
\n

Edit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided

\n
from dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = "Lagrange" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure("dx", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = "preonly" # Preconditioning Matrix Option\nsolver_type = "lu" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix="first_order_ODE", bcs = [bc], petsc_options={"ksp_type": ksp_type, "pc_type": solver_type})\nu_sol = problem.solve()\n
\n

\"enter

\n

we can see the solution is infinity at all node values of the functionspace.

\n","question_title":"Are there any resources which cover finding stable weak forms to 1st-order differential equations","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45530/are-there-any-resources-which-cover-finding-stable-weak-forms-to-1st-order-diffe","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45536,"score":5}],"answers":[{"answer_html":"

Even when using an IMEX scheme, you have to consider that the explicit part still imposes a stability restriction on $\\Delta t$. In your implementation, you have to consider something like:

\n

$$\n\\Delta t \\le \\frac{2\\,\\mathrm{CFL}}{3M\\beta k_{\\max}^2}, \\quad \\text{with} \\quad \\text{CFL}=1.\n$$

\n

A larger CFL number permits a larger time step and reduces the computational cost, but choosing it too large (CFL>1) can lead to numerical instability.

\n

Example: left stable, right unstable

\n

\"CFL \"CFL

\n","answer_id":45536,"answer_text":"Even when using an IMEX scheme, you have to consider that the explicit part still imposes a stability restriction on $\\Delta t$. In your implementation, you have to consider something like:\n\n\n\n\n$$\n\\Delta t \\le \\frac{2\\,\\mathrm{CFL}}{3M\\beta k_{\\max}^2}, \\quad \\text{with} \\quad \\text{CFL}=1.\n$$\n\n\n\n\nA larger CFL number permits a larger time step and reduces the computational cost, but choosing it too large (CFL>1) can lead to numerical instability.\n\n\n\n\nExample: left stable, right unstable\n\n\n\n\n[image: CFL < 1; source: https://i.sstatic.net/oJcmKuaA.gif] (https://i.sstatic.net/oJcmKuaA.gif) [image: CFL > 1; source: https://i.sstatic.net/jj2j0EFd.gif] (https://i.sstatic.net/jj2j0EFd.gif)","answer_url":"https://scicomp.stackexchange.com/a/45536","author":"ConvexHull","author_url":"https://scicomp.stackexchange.com/users/36512/convexhull","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-05T20:38:57+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":45532,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ConvexHull","profile_url":"https://scicomp.stackexchange.com/users/36512/convexhull","user_type":"registered"},"created_at":"2026-09-05T20:38:57+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"FAFB8920-4950-4612-A439-2940A54D031D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FAFB8920-4950-4612-A439-2940A54D031D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ConvexHull","profile_url":"https://scicomp.stackexchange.com/users/36512/convexhull","user_type":"registered"},"created_at":"2026-09-05T20:49:24+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"A2D91D1E-0B9E-429A-85F4-6DAD1D377E64","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A2D91D1E-0B9E-429A-85F4-6DAD1D377E64/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ConvexHull","profile_url":"https://scicomp.stackexchange.com/users/36512/convexhull","user_type":"registered"},"created_at":"2026-09-05T21:02:30+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9/view-source"}],"score":5,"updated_at":"2026-09-05T21:02:30+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"ConvexHull","author_url":"https://scicomp.stackexchange.com/users/36512/convexhull","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ConvexHull","profile_url":"https://scicomp.stackexchange.com/users/36512/convexhull","user_type":"registered"},"created_at":"2026-09-05T20:38:57+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"FAFB8920-4950-4612-A439-2940A54D031D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FAFB8920-4950-4612-A439-2940A54D031D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ConvexHull","profile_url":"https://scicomp.stackexchange.com/users/36512/convexhull","user_type":"registered"},"created_at":"2026-09-05T20:49:24+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"A2D91D1E-0B9E-429A-85F4-6DAD1D377E64","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A2D91D1E-0B9E-429A-85F4-6DAD1D377E64/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ConvexHull","profile_url":"https://scicomp.stackexchange.com/users/36512/convexhull","user_type":"registered"},"created_at":"2026-09-05T21:02:30+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45536"}],"question_author":"Manav Jalan","question_author_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan"},"code_blocks":[{"block_index":0,"code_text":"k_max = 250\nphi_0 = +0.0\nstd_dev = 0.05\n\nu_0_rand = np.random.randn(N,N)*std_dev + phi_0\nu_0_filter = u_0_rand # Please ignore the names of the variable\n","post_id":"scicomp:45532","sha256":"f40592e672522d5411963bc86e0bbe1592feb49f5dada74f8814a3c3b9b2c352","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"},{"block_index":1,"code_text":"delta_x = 0.75\nhalf_length = delta_x * N/2\n\n#Grid Construction\ngrid_1d = np.linspace(-half_length,half_length,N, endpoint=False)\nX, Y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\ngrid = np.stack((X, Y))\n\n#Frequency Grid\nfreq_1d = np.fft.fftfreq(N, delta_x) * 2 * np.pi \nfreq_X, freq_Y = np.meshgrid(freq_1d, freq_1d, indexing='ij')\nfreq_grid = np.stack((freq_X, freq_Y))\n\n# Create mask to zero out frequencies\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nif dealiasing_mask:\n k_cutoff = (N / 4) * (2*np.pi / (N*delta_x))\n freq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\nelse:\n freq_mask = np.ones(k_x.shape)\n","post_id":"scicomp:45532","sha256":"ec379444a6721a5231aebe08d7e169930c9add7bfbb99a32c99e4239ddc360ea","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"},{"block_index":2,"code_text":"# d(phi)/ dt = M lap( alpha*phi + beta*phi^3 + gamma*lap(phi))\nalpha = -1\nbeta = 1\ngamma = -1\nM = 1\nk_b = 1\n","post_id":"scicomp:45532","sha256":"231b429a5e2043d3797b87e9158b0c3fead54cb66dacff4f7735ac805d50abce","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"},{"block_index":3,"code_text":"def radial_average(image, center):\n \n assert image.shape[-2] == image.shape[-1], \"The image is not a square matrix\"\n \n y, x = np.indices(image.shape)\n cy, cx = center\n\n r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)\n \n mask = (r < (image.shape[-1]//2 - 1))\n \n radial_sum = np.bincount(\n r[mask].ravel(),\n weights=image[mask].ravel()\n )\n\n radial_count = np.bincount(r[mask].ravel())\n\n radial_average = radial_sum / radial_count\n\n return np.arange(len(radial_average)), radial_average\n","post_id":"scicomp:45532","sha256":"9f3ce8c6b10cd45e7f2b7ca3d87f386103b6b4a5eaa910551cb1fe652de70560","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"},{"block_index":4,"code_text":"# Simulation Controls\ndelta_t = 0.5\ntimesteps = 5000\nk_2 = k_x**2 + k_y**2\nzero_freq_masking = False\nhardening = False\n\n# History\nt_spacing = 20\nu_history = []\nfft_history = []\nrec_time_hist = []\navg_domain_size = []\nradial_S_k_history = []\nradial_corr_history = []\n\n# Initialize\nfft = np.fft.fft2(u_0_filter.real)\nfor t in tqdm(range(timesteps)):\n \n u_t_masked = np.fft.ifft2(fft * freq_mask).real\n cubed = u_t_masked ** 3\n cubed_fft = np.fft.fft2(cubed) * freq_mask\n \n \n # IMEX Update Step\n num = (fft - M*beta*k_2*delta_t*cubed_fft) + noise_increment\n denm = 1 + M*delta_t*k_2*(alpha - gamma*k_2)\n fft = num/denm\n \n #Projection to real space\n u_t = np.fft.ifft2(fft).real\n fft = np.fft.fft2(u_t)\n \n # History update\n if t%t_spacing == 0:\n \n u_t_snap = u_t.copy()\n if hardening:\n u_t_snap[u_t_snap>0] = +1\n u_t_snap[u_t_snap<0] = -1\n fft_snap = np.fft.fft2(u_t_snap)\n else:\n fft_snap = fft.copy()\n \n fft_history.append(fft_snap)\n u_history.append(u_t_snap.real)\n rec_time_hist.append((t+1)*delta_t)\n \n # Domain Size calculation\n S_k = np.abs(fft_snap)**2 / N**2\n shifted_S_k = np.fft.fftshift(S_k)\n \n r_val ,radial_S = radial_average(shifted_S_k, center=(N//2,N//2))\n radial_S_k_history.append(radial_S)\n \n # Converting the bin indices to frequency\n k_val = r_val * 2 * np.pi / (N * delta_x)\n if zero_freq_masking:\n mask = (k_val>0)\n avg_k = np.sum(radial_S[mask] * k_val[mask]) / np.sum(radial_S[mask])\n else:\n avg_k = np.sum(radial_S * k_val) / np.sum(radial_S)\n domain_size = np.pi / avg_k\n avg_domain_size.append(domain_size)\n \n # Azimuthally averaged correlation function\n corr_2d = np.fft.fftshift(np.fft.ifft2(S_k))\n r_val , radial_corr = radial_average(corr_2d.real, center=(N//2,N//2))\n radial_corr_history.append(radial_corr)\n \n# Converting the r_val from indices units to real units\nr_val = delta_x*r_val\n \nu_final_spectral = np.fft.ifft2(fft).real\nu_history = np.array(u_history)\nfft_history = np.array(fft_history)\n\n# Plotting \nfig, ax = plt.subplots(1, 2, figsize=(9, 4), constrained_layout=True)\nlevels = np.linspace(-1.5, 1.5, 100)\nim1 = ax[0].contourf(X, Y, u_0_filter.real , levels=levels, cmap=\"bwr\")\nim2 = ax[1].contourf(X, Y, u_final_spectral, levels=levels, cmap=\"bwr\")\nax[0].set_title(\"Initial State\")\nax[1].set_title(\"IMEX Spectral Result\")\nfig.colorbar(im2, ax=ax, ticks=[-1.5, 0, 1.5])\nplt.show()\n","post_id":"scicomp:45532","sha256":"36883faddc429ff294899e4ad411886dc0693ea138fe351621b56d8d314abd2f","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"e12d2b10ac726fb5b6aa3b1fea53e2a7fced4efd6e4ee7f3bbde464e9786d9c2","id":"SCT-581b2ce3e081b7e49fbc64f4","language":null,"library_or_tool":null,"problem_text":"I am trying to simulate the cahn-hilliard system using a psuedospectral solver. I am using the following scheme:\n$$\\widetilde{\\phi}_{k}^{\\,t+1}=\\frac{\\widetilde{\\phi}_{k}^{\\,t}-M\\beta k^2\\Delta\\widetilde{\\phi_{k}^{\\,3}}^{\\,t}}{1+M\\Delta k^2\\left(\\alpha-\\gamma k^2\\right)}$$ for the equation $$ \\frac{d\\phi}{\\mathrm{d}t}\\;=\\;M\\;\\nabla^2\\left(\\alpha\\cdot\\phi\\;+\\;\\beta\\cdot\\phi^3\\;+\\;\\gamma\\cdot\\nabla^2\\phi\\right)\n$$\nwhere $\\triangle$ is the time spacing.\nThe code is as follows:\n\n\n\n\nk_max = 250\nphi_0 = +0.0\nstd_dev = 0.05\n\nu_0_rand = np.random.randn(N,N)*std_dev + phi_0\nu_0_filter = u_0_rand # Please ignore the names of the variable\n\n\n\n\n\ndelta_x = 0.75\nhalf_length = delta_x * N/2\n\n#Grid Construction\ngrid_1d = np.linspace(-half_length,half_length,N, endpoint=False)\nX, Y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\ngrid = np.stack((X, Y))\n\n#Frequency Grid\nfreq_1d = np.fft.fftfreq(N, delta_x) * 2 * np.pi \nfreq_X, freq_Y = np.meshgrid(freq_1d, freq_1d, indexing='ij')\nfreq_grid = np.stack((freq_X, freq_Y))\n\n# Create mask to zero out frequencies\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nif dealiasing_mask:\n k_cutoff = (N / 4) * (2*np.pi / (N*delta_x))\n freq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\nelse:\n freq_mask = np.ones(k_x.shape)\n\n\n\n\n\n# d(phi)/ dt = M lap( alpha*phi + beta*phi^3 + gamma*lap(phi))\nalpha = -1\nbeta = 1\ngamma = -1\nM = 1\nk_b = 1\n\n\n\n\n\ndef radial_average(image, center):\n \n assert image.shape[-2] == image.shape[-1], \"The image is not a square matrix\"\n \n y, x = np.indices(image.shape)\n cy, cx = center\n\n r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)\n \n mask = (r < (image.shape[-1]//2 - 1))\n \n radial_sum = np.bincount(\n r[mask].ravel(),\n weights=image[mask].ravel()\n )\n\n radial_count = np.bincount(r[mask].ravel())\n\n radial_average = radial_sum / radial_count\n\n return np.arange(len(radial_average)), radial_average\n\n\n\n\n\n# Simulation Controls\ndelta_t = 0.5\ntimesteps = 5000\nk_2 = k_x**2 + k_y**2\nzero_freq_masking = False\nhardening = False\n\n# History\nt_spacing = 20\nu_history = []\nfft_history = []\nrec_time_hist = []\navg_domain_size = []\nradial_S_k_history = []\nradial_corr_history = []\n\n# Initialize\nfft = np.fft.fft2(u_0_filter.real)\nfor t in tqdm(range(timesteps)):\n \n u_t_masked = np.fft.ifft2(fft * freq_mask).real\n cubed = u_t_masked ** 3\n cubed_fft = np.fft.fft2(cubed) * freq_mask\n \n \n # IMEX Update Step\n num = (fft - M*beta*k_2*delta_t*cubed_fft) + noise_increment\n denm = 1 + M*delta_t*k_2*(alpha - gamma*k_2)\n fft = num/denm\n \n #Projection to real space\n u_t = np.fft.ifft2(fft).real\n fft = np.fft.fft2(u_t)\n \n # History update\n if t%t_spacing == 0:\n \n u_t_snap = u_t.copy()\n if hardening:\n u_t_snap[u_t_snap>0] = +1\n u_t_snap[u_t_snap<0] = -1\n fft_snap = np.fft.fft2(u_t_snap)\n else:\n fft_snap = fft.copy()\n \n fft_history.append(fft_snap)\n u_history.append(u_t_snap.real)\n rec_time_hist.append((t+1)*delta_t)\n \n # Domain Size calculation\n S_k = np.abs(fft_snap)**2 / N**2\n shifted_S_k = np.fft.fftshift(S_k)\n \n r_val ,radial_S = radial_average(shifted_S_k, center=(N//2,N//2))\n radial_S_k_history.append(radial_S)\n \n # Converting the bin indices to frequency\n k_val = r_val * 2 * np.pi / (N * delta_x)\n if zero_freq_masking:\n mask = (k_val>0)\n avg_k = np.sum(radial_S[mask] * k_val[mask]) / np.sum(radial_S[mask])\n else:\n avg_k = np.sum(radial_S * k_val) / np.sum(radial_S)\n domain_size = np.pi / avg_k\n avg_domain_size.append(domain_size)\n \n # Azimuthally averaged correlation function\n corr_2d = np.fft.fftshift(np.fft.ifft2(S_k))\n r_val , radial_corr = radial_average(corr_2d.real, center=(N//2,N//2))\n radial_corr_history.append(radial_corr)\n \n# Converting the r_val from indices units to real units\nr_val = delta_x*r_val\n \nu_final_spectral = np.fft.ifft2(fft).real\nu_history = np.array(u_history)\nfft_history = np.array(fft_history)\n\n# Plotting \nfig, ax = plt.subplots(1, 2, figsize=(9, 4), constrained_layout=True)\nlevels = np.linspace(-1.5, 1.5, 100)\nim1 = ax[0].contourf(X, Y, u_0_filter.real , levels=levels, cmap=\"bwr\")\nim2 = ax[1].contourf(X, Y, u_final_spectral, levels=levels, cmap=\"bwr\")\nax[0].set_title(\"Initial State\")\nax[1].set_title(\"IMEX Spectral Result\")\nfig.colorbar(im2, ax=ax, ticks=[-1.5, 0, 1.5])\nplt.show()\n\n\n\n\n\nThe projection part to real space is done to improve stability. I am also introducing hardening to remove finite interfaces so that one can clearly observe the $k^{-3}$ porod's tail decay.\n\n\n\n\nThe following results are obtained without hardening:\nFirst, I have turned on the dealiasing mask. This gives me the following solution:\n[image: Solution with dealiasing mask; source: https://i.sstatic.net/12z0CS3L.png] (https://i.sstatic.net/12z0CS3L.png)\n\n\n\n\nThe domain growth is also well obtained and follows the theoretical 1/3 law.\n[image: domain growth; source: https://i.sstatic.net/655HZFjB.png] (https://i.sstatic.net/655HZFjB.png)\n\n\n\n\nThe problem comes in the structure factor collapse:\n[image: Structure factor collapse; source: https://i.sstatic.net/xVZy72zi.png] (https://i.sstatic.net/xVZy72zi.png)\n\n\n\n\nDue to dealiasing, the high frequency modes are getting supressed completely as the $u^3$ term is not contributing anything. Also, the bigger problem is the oscillations present in the solutions. The faint waves present in the solution. I am suspecting the abrupt cutoff to cause this problem.\n\n\n\n\nNext, I tried with no dealiasing filter. This time the problem of structure factor is removed because contributions of the $u^3$ term is present.\n[image: Structure factor collapse; source: https://i.sstatic.net/TMxN8G8J.png] (https://i.sstatic.net/TMxN8G8J.png)\n\n\n\n\nWith hardening the slope also comes around to -3. But the problem of oscillation still remains.\n[image: Oscillations in the solution; source: https://i.sstatic.net/3KkMyklD.png] (https://i.sstatic.net/3KkMyklD.png)\n\n\n\n\nI have also plotted the regions which are outside the [-1,1] value range.\n[image: Mass pileup; source: https://i.sstatic.net/65RiIZsB.png] (https://i.sstatic.net/65RiIZsB.png)\n\n\n\n\nThere is clear mass pileup which was also present in the case with dealiasing filter. My best guess is the aliasing is causing some of the oscillations but I have no clue why there is mass pileup (However, the relative magnitude is small. The maximum mass is roughly +1.15 and minimum mass is -1.15).\n\n\n\n\nThe main doubts are:\n\n\n\n\n\nWhy is there mass pileup?\n\n\n\n\nWhy is there oscillations in both cases?\n\n\n\n\nHow to prevent this? Is it a common problem in psuedospectral implementations? I have seen few PREs and PRRs where they have used psuedospectral solvers with dealiasing filter but none has reported such problems. Is it only specific to my implementation, has someone ever faced this issue?","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":"Manav Jalan","profile_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan","user_type":"registered"},"created_at":"2026-09-02T16:06:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AC851941-A7C5-45E6-8C52-ADE45AB9931D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AC851941-A7C5-45E6-8C52-ADE45AB9931D/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":"45532","source_record_sha256":"03a6862fb4f5ce081294d52c123c5f2cbaf0854900e348b9209b1161f9f67231","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I am trying to simulate the cahn-hilliard system using a psuedospectral solver. I am using the following scheme:\n$$\\widetilde{\\phi}_{k}^{\\,t+1}=\\frac{\\widetilde{\\phi}_{k}^{\\,t}-M\\beta k^2\\Delta\\widetilde{\\phi_{k}^{\\,3}}^{\\,t}}{1+M\\Delta k^2\\left(\\alpha-\\gamma k^2\\right)}$$ for the equation $$ \\frac{d\\phi}{\\mathrm{d}t}\\;=\\;M\\;\\nabla^2\\left(\\alpha\\cdot\\phi\\;+\\;\\beta\\cdot\\phi^3\\;+\\;\\gamma\\cdot\\nabla^2\\phi\\right)\n$$\nwhere $\\triangle$ is the time spacing.\nThe code is as follows:

\n
k_max = 250\nphi_0 = +0.0\nstd_dev = 0.05\n\nu_0_rand = np.random.randn(N,N)*std_dev + phi_0\nu_0_filter = u_0_rand # Please ignore the names of the variable\n
\n
delta_x = 0.75\nhalf_length = delta_x * N/2\n\n#Grid Construction\ngrid_1d = np.linspace(-half_length,half_length,N, endpoint=False)\nX, Y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\ngrid = np.stack((X, Y))\n\n#Frequency Grid\nfreq_1d = np.fft.fftfreq(N, delta_x) * 2 * np.pi \nfreq_X, freq_Y = np.meshgrid(freq_1d, freq_1d, indexing='ij')\nfreq_grid = np.stack((freq_X, freq_Y))\n\n# Create mask to zero out frequencies\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nif dealiasing_mask:\n    k_cutoff = (N / 4) * (2*np.pi / (N*delta_x))\n    freq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\nelse:\n    freq_mask = np.ones(k_x.shape)\n
\n
# d(phi)/ dt = M lap( alpha*phi + beta*phi^3 + gamma*lap(phi))\nalpha = -1\nbeta = 1\ngamma = -1\nM = 1\nk_b = 1\n
\n
def radial_average(image, center):\n    \n    assert image.shape[-2] == image.shape[-1], "The image is not a square matrix"\n    \n    y, x = np.indices(image.shape)\n    cy, cx = center\n\n    r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)\n    \n    mask = (r < (image.shape[-1]//2 - 1))\n    \n    radial_sum = np.bincount(\n        r[mask].ravel(),\n        weights=image[mask].ravel()\n    )\n\n    radial_count = np.bincount(r[mask].ravel())\n\n    radial_average = radial_sum / radial_count\n\n    return np.arange(len(radial_average)), radial_average\n
\n
# Simulation Controls\ndelta_t = 0.5\ntimesteps = 5000\nk_2 = k_x**2 + k_y**2\nzero_freq_masking = False\nhardening = False\n\n# History\nt_spacing = 20\nu_history = []\nfft_history = []\nrec_time_hist = []\navg_domain_size = []\nradial_S_k_history = []\nradial_corr_history = []\n\n# Initialize\nfft = np.fft.fft2(u_0_filter.real)\nfor t in tqdm(range(timesteps)):\n    \n    u_t_masked = np.fft.ifft2(fft * freq_mask).real\n    cubed = u_t_masked ** 3\n    cubed_fft = np.fft.fft2(cubed) * freq_mask\n    \n    \n    # IMEX Update Step\n    num = (fft - M*beta*k_2*delta_t*cubed_fft) + noise_increment\n    denm = 1 + M*delta_t*k_2*(alpha - gamma*k_2)\n    fft = num/denm\n    \n    #Projection to real space\n    u_t = np.fft.ifft2(fft).real\n    fft = np.fft.fft2(u_t)\n    \n    # History update\n    if t%t_spacing == 0:\n        \n        u_t_snap = u_t.copy()\n        if hardening:\n            u_t_snap[u_t_snap>0] = +1\n            u_t_snap[u_t_snap<0] = -1\n            fft_snap = np.fft.fft2(u_t_snap)\n        else:\n            fft_snap = fft.copy()\n        \n        fft_history.append(fft_snap)\n        u_history.append(u_t_snap.real)\n        rec_time_hist.append((t+1)*delta_t)\n        \n        # Domain Size calculation\n        S_k = np.abs(fft_snap)**2 / N**2\n        shifted_S_k = np.fft.fftshift(S_k)\n        \n        r_val ,radial_S = radial_average(shifted_S_k, center=(N//2,N//2))\n        radial_S_k_history.append(radial_S)\n    \n        # Converting the bin indices to frequency\n        k_val = r_val * 2 * np.pi / (N * delta_x)\n        if zero_freq_masking:\n            mask = (k_val>0)\n            avg_k = np.sum(radial_S[mask] * k_val[mask]) / np.sum(radial_S[mask])\n        else:\n            avg_k = np.sum(radial_S * k_val) / np.sum(radial_S)\n        domain_size = np.pi / avg_k\n        avg_domain_size.append(domain_size)\n        \n        # Azimuthally averaged correlation function\n        corr_2d  = np.fft.fftshift(np.fft.ifft2(S_k))\n        r_val , radial_corr = radial_average(corr_2d.real, center=(N//2,N//2))\n        radial_corr_history.append(radial_corr)\n        \n# Converting the r_val from indices units to real units\nr_val = delta_x*r_val\n        \nu_final_spectral = np.fft.ifft2(fft).real\nu_history = np.array(u_history)\nfft_history = np.array(fft_history)\n\n# Plotting    \nfig, ax = plt.subplots(1, 2, figsize=(9, 4), constrained_layout=True)\nlevels = np.linspace(-1.5, 1.5, 100)\nim1 = ax[0].contourf(X, Y, u_0_filter.real , levels=levels, cmap="bwr")\nim2 = ax[1].contourf(X, Y, u_final_spectral, levels=levels, cmap="bwr")\nax[0].set_title("Initial State")\nax[1].set_title("IMEX Spectral Result")\nfig.colorbar(im2, ax=ax, ticks=[-1.5, 0, 1.5])\nplt.show()\n
\n

The projection part to real space is done to improve stability. I am also introducing hardening to remove finite interfaces so that one can clearly observe the $k^{-3}$ porod's tail decay.

\n

The following results are obtained without hardening:\nFirst, I have turned on the dealiasing mask. This gives me the following solution:\n\"Solution

\n

The domain growth is also well obtained and follows the theoretical 1/3 law.\n\"domain

\n

The problem comes in the structure factor collapse:\n\"Structure

\n

Due to dealiasing, the high frequency modes are getting supressed completely as the $u^3$ term is not contributing anything. Also, the bigger problem is the oscillations present in the solutions. The faint waves present in the solution. I am suspecting the abrupt cutoff to cause this problem.

\n

Next, I tried with no dealiasing filter. This time the problem of structure factor is removed because contributions of the $u^3$ term is present.\n\"Structure

\n

With hardening the slope also comes around to -3. But the problem of oscillation still remains.\n\"Oscillations

\n

I have also plotted the regions which are outside the [-1,1] value range.\n\"Mass

\n

There is clear mass pileup which was also present in the case with dealiasing filter. My best guess is the aliasing is causing some of the oscillations but I have no clue why there is mass pileup (However, the relative magnitude is small. The maximum mass is roughly +1.15 and minimum mass is -1.15).

\n

The main doubts are:

\n
    \n
  1. Why is there mass pileup?
  2. \n
  3. Why is there oscillations in both cases?
  4. \n
  5. How to prevent this? Is it a common problem in psuedospectral implementations? I have seen few PREs and PRRs where they have used psuedospectral solvers with dealiasing filter but none has reported such problems. Is it only specific to my implementation, has someone ever faced this issue?
  6. \n
\n","question_title":"Oscillations & Weird patterns in cahn hilliard IMEX solver","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver","split":"train"} {"accepted_answer":null,"answer_scores":[{"answer_id":45537,"score":2}],"answers":[{"answer_html":"

The key insight (also reflected in this comment) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).

\n

Since you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,

\n
    \n
  1. Union the set of all box-box intersections and all box-axis intersections
  2. \n
  3. From that set, exclude all points that are occluded by a box
  4. \n
  5. Do a tensor contraction to get the squared norm for the remaining intersections
  6. \n
  7. Choose the smallest one.
  8. \n
\n

For small bounding box count, it's very frequent that an axis intersection is selected:

\n

\"small

\n

For 90 bounding boxes, we see a non-axis intersection being selected:

\n

\"90

\n

On my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.

\n
import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n    """\n    Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n    """\n    rand = np.random.default_rng(seed)\n    box = np.empty(shape=(2, 2, n), dtype=np.float32)\n    box[..., 0] = (\n        (-0.3, +0.3),\n        (-0.3, +0.3),\n    )\n    box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n    box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n    return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n    n = box.shape[-1]\n\n    # All segments from bounding boxes min,max, and axis:\n    # segment coordinate values on parallel axis\n    segments_par = np.empty(\n        shape=(2, 2, 2*n + 1),  # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n        dtype=box.dtype,\n    )\n    segments_par[..., :-1] = box.repeat(2, axis=-1)\n    # The last line is the axis. The axis intersecting any bounding box produces candidate points\n    # for the closest-exterior output.\n    segments_par[..., -1] = -np.inf, +np.inf\n\n    # segment coordinate values on perpendicular axis\n    # (y,x), (perp min, perp max)n + axis\n    segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n    segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n    segments_perp[:, -1] = 0  # Axis intersects (0,0)\n\n    x0, x1 = segments_par[0, :, :, np.newaxis]\n    y0, y1 = segments_par[1, :, np.newaxis, :]\n    xp = segments_perp[0, np.newaxis, :]\n    yp = segments_perp[1, :, np.newaxis]\n\n    # Outer product produces boolean intersection predicate\n    hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n    hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n    hits[-1, -1] = 0\n\n    k = segments_par.shape[-1]\n    # Intersection coordinates\n    xi = np.broadcast_to(xp, (k, k))[hits]\n    yi = np.broadcast_to(yp, (k, k))[hits]\n    return np.stack((xi, yi))  # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n    xi, yi = xyi[:, :, np.newaxis]\n    (\n        (x0, x1),\n        (y0, y1),\n    ) = box[:, :, np.newaxis, :]\n\n    return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n    norm2 = np.einsum('ij,ij->j', xyi, xyi)  # x**2 + y**2, product (2,n)\n    return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n    fig, ax = plt.subplots()\n    ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n    ax.set_xlim(-1.1, 1.1)\n    ax.set_ylim(-1.1, 1.1)\n    ax.scatter(*xyi[:, ~free], label='occluded')\n    ax.scatter(*xy_free, label='free')\n    ax.legend()\n\n    for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n        ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n    box = sample_data(90)\n    xyi = intersect_points(box)\n    free = exclude_bounding(box, xyi)\n    xy_free = xyi[:, free]\n    best = choose_closest(xy_free)\n    plot(box, xyi, xy_free, free, best)\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n
\n","answer_id":45537,"answer_text":"The key insight (also reflected in this comment (https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533)) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).\n\n\n\n\nSince you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,\n\n\n\n\n\nUnion the set of all box-box intersections and all box-axis intersections\n\n\n\n\nFrom that set, exclude all points that are occluded by a box\n\n\n\n\nDo a tensor contraction to get the squared norm for the remaining intersections\n\n\n\n\nChoose the smallest one.\n\n\n\n\n\nFor small bounding box count, it's very frequent that an axis intersection is selected:\n\n\n\n\n[image: small problem; source: https://i.sstatic.net/rLLW3nkZ.png] (https://i.sstatic.net/rLLW3nkZ.png)\n\n\n\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:\n\n\n\n\n[image: 90 boxes; source: https://i.sstatic.net/B0XWwMzu.png] (https://i.sstatic.net/B0XWwMzu.png)\n\n\n\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45537","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-07T22:20:58+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":45533,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:20:58+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EA034CBB-245E-47BE-9F83-73186A65FD54","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:53:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"13520681-83F3-4234-8A59-CE187F0BEA29","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}],"score":2,"updated_at":"2026-09-07T22:53:19+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:20:58+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EA034CBB-245E-47BE-9F83-73186A65FD54","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:53:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"13520681-83F3-4234-8A59-CE187F0BEA29","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45537"}],"question_author":"ffbh","question_author_url":"https://scicomp.stackexchange.com/users/57252/ffbh"},"code_blocks":[{"block_index":0,"code_text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","post_id":45537,"sha256":"6637077f835d130cffa7ea8578142da4476921b98d0380a50f965b7d7ccb12a0","source_url":"https://scicomp.stackexchange.com/a/45537"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"d86836aa7b471b88053ba3946e27afb910038bc268b2506894de8ecff8a7a9aa","id":"SCT-93741176d396566b0bc6e060","language":null,"library_or_tool":null,"problem_text":"I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.\n\n\n\n\n\nIf P is not inside any AABB, I don't need to do anything.\n\n\n\n\nIf P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs\n\n\n\n\nA point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.\n\n\n\n\n\nIs there a known algorithm for this problem?\n\n\n\n\nThanks.","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":"ffbh","profile_url":"https://scicomp.stackexchange.com/users/57252/ffbh","user_type":"registered"},"created_at":"2026-09-03T03:48:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"4165EEB0-A429-43DE-A4E0-E9FB5F902B12","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4165EEB0-A429-43DE-A4E0-E9FB5F902B12/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":"45533","source_record_sha256":"6aa8e72f63abb74eb1342729a4b43d888897993bead981495b0e936275456a06","source_url":"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.

\n
    \n
  1. If P is not inside any AABB, I don't need to do anything.
  2. \n
  3. If P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs
  4. \n
  5. A point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.
  6. \n
\n

Is there a known algorithm for this problem?

\n

Thanks.

\n","question_title":"Find the closest point outside overlapping AABBs from a point inside them","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them","split":"holdout"} {"accepted_answer":null,"answer_scores":[{"answer_id":45540,"score":2}],"answers":[{"answer_html":"

The runtime analysis you described for the two algorithms, brute force and your filtered one, looks right. I cannot say whether your algorithm exists in the literature or if there are other better ones out there in the literature of your field.

\n

That said, I have designed a new algorithm that also shares similar benefits when it comes to parallelization but is also asymptotically faster (at least in the "random data" setup). That said, I will only describe the serial algorithm.

\n

Algorithm: The idea is to consider square blocks of the image, blocks that are sufficiently small that at most one local maximum could possible exist. Since we know a pixel is a local maximum if it is the strictly largest pixel in an $R$-radius neighborhood, then we should consider blocks whose diagonals have length $R$. This implies our blocks should have a width of $W := R / \\sqrt{2}$. Within such a block, all pixels are at most a distance $R$ away from each other, so at most one pixel can be a local maximum in a block.

\n

(Note: (1) when I say width here, I mean the Euclidean distance between the first and last pixel in a row of the block, so a $5 \\times 5$ block has a width of $4$; (2) in a practical implementation, you'd have to be more careful with rounding, say using a floor function when computing $W$.)

\n

So from here, partition the image into $O(mn / R^2)$ square blocks of size $(1 + W) \\times (1 + W)$ and grab the local maximum within each block; the local maximum within each block is a candidate solution. Note that this implies we have at most $O(mn / R^2)$ candidate solutions, no matter what input we get.

\n

From here, we apply a similar logic to you and just brute force check each candidate solution to see which are true local maximums. Since there are $O(mn / R^2)$ candidates and it takes $O(R^2)$ time to check if they are local maxima, the overall runtime is $O(mn)$.

\n

Threading: If we have $t$ threads available, we can drop this runtime in theory to $O(mn / t)$ time, while your algorithm would run in say $O(mnR / t)$ time, and brute force would require $O(mnR^2 / t)$ time.

\n

Experiments: Below are comparisons of the three algorithms (I implemented them in C++) at a fixed random square image of width $5000$, with values of $R$ ranging from $2$ pixels to $50$ pixels.

\n

\"enter

\n","answer_id":45540,"answer_text":"The runtime analysis you described for the two algorithms, brute force and your filtered one, looks right. I cannot say whether your algorithm exists in the literature or if there are other better ones out there in the literature of your field.\n\n\n\n\nThat said, I have designed a new algorithm that also shares similar benefits when it comes to parallelization but is also asymptotically faster (at least in the \"random data\" setup). That said, I will only describe the serial algorithm.\n\n\n\n\nAlgorithm: The idea is to consider square blocks of the image, blocks that are sufficiently small that at most one local maximum could possible exist. Since we know a pixel is a local maximum if it is the strictly largest pixel in an $R$-radius neighborhood, then we should consider blocks whose diagonals have length $R$. This implies our blocks should have a width of $W := R / \\sqrt{2}$. Within such a block, all pixels are at most a distance $R$ away from each other, so at most one pixel can be a local maximum in a block.\n\n\n\n\n(Note: (1) when I say width here, I mean the Euclidean distance between the first and last pixel in a row of the block, so a $5 \\times 5$ block has a width of $4$; (2) in a practical implementation, you'd have to be more careful with rounding, say using a floor function when computing $W$.)\n\n\n\n\nSo from here, partition the image into $O(mn / R^2)$ square blocks of size $(1 + W) \\times (1 + W)$ and grab the local maximum within each block; the local maximum within each block is a candidate solution. Note that this implies we have at most $O(mn / R^2)$ candidate solutions, no matter what input we get.\n\n\n\n\nFrom here, we apply a similar logic to you and just brute force check each candidate solution to see which are true local maximums. Since there are $O(mn / R^2)$ candidates and it takes $O(R^2)$ time to check if they are local maxima, the overall runtime is $O(mn)$.\n\n\n\n\nThreading: If we have $t$ threads available, we can drop this runtime in theory to $O(mn / t)$ time, while your algorithm would run in say $O(mnR / t)$ time, and brute force would require $O(mnR^2 / t)$ time.\n\n\n\n\nExperiments: Below are comparisons of the three algorithms (I implemented them in C++) at a fixed random square image of width $5000$, with values of $R$ ranging from $2$ pixels to $50$ pixels.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/L0Ei4zdr.jpg] (https://i.sstatic.net/L0Ei4zdr.jpg)","answer_url":"https://scicomp.stackexchange.com/a/45540","author":"spektr","author_url":"https://scicomp.stackexchange.com/users/9804/spektr","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-13T02:54:46+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":45538,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-13T02:54:46+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"80221BE1-DBDE-45E3-87AC-177466D909E5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/80221BE1-DBDE-45E3-87AC-177466D909E5/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-13T18:42:44+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2C72D0C5-EBE6-41A1-85FC-96140A1EAE56","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2C72D0C5-EBE6-41A1-85FC-96140A1EAE56/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-15T02:58:26+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2363088A-821D-4E01-8E72-C365212D99A4","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2363088A-821D-4E01-8E72-C365212D99A4/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-15T03:51:06+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"86205662-C9FD-4D09-9758-DFFD1E179DE8","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/86205662-C9FD-4D09-9758-DFFD1E179DE8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-15T03:58:56+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B0832F01-0D2D-410B-8F25-01F16AE91294","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B0832F01-0D2D-410B-8F25-01F16AE91294/view-source"}],"score":2,"updated_at":"2026-09-15T03:58:56+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"spektr","author_url":"https://scicomp.stackexchange.com/users/9804/spektr","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-13T02:54:46+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"80221BE1-DBDE-45E3-87AC-177466D909E5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/80221BE1-DBDE-45E3-87AC-177466D909E5/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-13T18:42:44+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2C72D0C5-EBE6-41A1-85FC-96140A1EAE56","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2C72D0C5-EBE6-41A1-85FC-96140A1EAE56/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-15T02:58:26+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"2363088A-821D-4E01-8E72-C365212D99A4","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2363088A-821D-4E01-8E72-C365212D99A4/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-15T03:51:06+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"86205662-C9FD-4D09-9758-DFFD1E179DE8","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/86205662-C9FD-4D09-9758-DFFD1E179DE8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2026-09-15T03:58:56+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B0832F01-0D2D-410B-8F25-01F16AE91294","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B0832F01-0D2D-410B-8F25-01F16AE91294/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45540"}],"question_author":"BmyGuest","question_author_url":"https://scicomp.stackexchange.com/users/28168/bmyguest"},"code_blocks":[{"block_index":0,"code_text":"I(q) > I(p)\n","post_id":"scicomp:45538","sha256":"4de0fa965604908758c1f195bdb513c7cf26ff547c9433af1a4b7697e2d4c280","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":1,"code_text":"I(p) >= I(q)\n","post_id":"scicomp:45538","sha256":"5ffcab0ef8fe3e79f82f7d50e17376114be99c6fa543f783ad2c88bb97f9400f","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":2,"code_text":"||p-q|| <= R\n","post_id":"scicomp:45538","sha256":"5c4789d015cba3468b0cc4cf5c58745771eb462a738e7608c3d6fbcdd223f014","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":3,"code_text":"[x-R, x+R] × [y-R, y+R]\n","post_id":"scicomp:45538","sha256":"00a0558875f65bc6fd5138c48a9217928226f0e50e6323e2591a0c7cb801dde0","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":4,"code_text":"dx = q.x - c.x\ndy = q.y - c.y\n","post_id":"scicomp:45538","sha256":"6f26e562a6c43cd70e96a4fc0bc07bc802b5d925dbde257ecc214118c37a81b0","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":5,"code_text":"dx² + dy² > R²\n","post_id":"scicomp:45538","sha256":"61ec5426226a3339edd1fe13eeea04d41216d9277d3d7584fcf0ae72a6da8682","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":6,"code_text":"I(q) > I(c)\n","post_id":"scicomp:45538","sha256":"a386105c190b7173be2aea88c0a0ce76f24dfe8f5fa708abd6f92ec500551778","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":7,"code_text":"O(N * M * R²)\n","post_id":"scicomp:45538","sha256":"6022746cef5ecc001fffdcb6d435a0958d7681eab010b66496c3ac1dc25e8396","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":8,"code_text":"Candidate generation: O(N * M)\nReverse validation: O(C * R)\nExact 2D check: O(C * R²)\n","post_id":"scicomp:45538","sha256":"70ef90f77c114517c927b779bb49971d9a0f25286bfa2d11cb0d41fdaca8a339","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":9,"code_text":"C << N * M\n","post_id":"scicomp:45538","sha256":"ac635322991af68487a1c3e48f4e40e3ff4a91b12861a94a4859389f125fc80d","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":10,"code_text":"(N * M) / (2R + 1)\n","post_id":"scicomp:45538","sha256":"499e292c8e13aff993aebcfb6527295a1136b7566aa3e0089a6e82251db9e16c","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":11,"code_text":"O(N * M * R)\n","post_id":"scicomp:45538","sha256":"dd2f673331b5f4bb2320ab801c116b38b66b089e3e2de3bb36f520145e2b0be4","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":12,"code_text":"O(N * M * R²)\n","post_id":"scicomp:45538","sha256":"6022746cef5ecc001fffdcb6d435a0958d7681eab010b66496c3ac1dc25e8396","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"},{"block_index":13,"code_text":"INT X Y\n--------------\n65535 30 55\n65125 49 9\n64013 21 62\n63921 60 8\n63768 27 21\n63763 63 41\n63684 38 21\n62182 5 22\n62084 5 35\n61920 6 59\n61791 46 56\n61766 16 22\n61263 54 48\n60585 26 8\n60426 38 8\n60079 16 36\n59995 38 46\n59758 49 21\n59562 14 50\n59489 61 22\n59052 28 36\n58883 47 37\n58220 61 60\n58194 7 7\n50898 37 63\n39297 16 0\n33772 44 15\n33013 0 28\n32096 55 15\n31872 38 55\n30784 62 50\n29796 22 29\n29467 33 28\n29253 14 60\n29249 63 32\n29085 11 16\n28624 0 41\n28116 44 2\n27058 43 28\n26534 54 29\n26127 0 4\n24468 33 1\n23342 17 6\n","post_id":"scicomp:45538","sha256":"8c2ee9a6ab97bb63a26af461f78ec0d07b8895a15d41c2b57459e6d21ac17310","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"96a339625e5b71306347b36d91174659ea79e474f07be601b8f0696ccd36267b","id":"SCT-273d1a6d988370d41f741c0b","language":null,"library_or_tool":null,"problem_text":"Questions\n\n\n\n\n\n\n\nDoes the below described (or a very similar) algorithm already exist in the literature under a specific name?\n\n\n\n\n\n\n\n\n\nAre there known local-maxima detection algorithms that are likely to outperform this candidate-pruning approach (on a multi-core CPU) at the typical conditions described?\n\n\n\n\n\n\n\n\n\n\n\nBackstory\n\n\n\n\nOver a decade ago I was in need of finding local maxima positions in a regular 2D array of numbers within a provided search radius. I was looking for an algorithm that is fast on many such local maxima in a comparably small search-radius range. (The application are atomic resolution electron microscopy images.)\n\n\n\n\n[image: HAADF image acquired with STEM microscopy; source: https://i.sstatic.net/6HQrfCuB.gif] (https://i.sstatic.net/6HQrfCuB.gif)\n\n\n\n\nAt the time I couldn't find a suitable ready-to-implement algorithm, so I came up with my own algorithm and implemented it in C++. It works perfectly well for my needs with satisfactory speed.\n\n\n\n\nHowever, I have never\n\n\n\n\na) searched whether that algorithm idea has been employed already and has a name, or\n\n\n\n\nb) performed serious benchmarking of the algorithm against other algorithms.\n\n\n\n\nI'm posting this here today to possibly have some experts look over it and either fill my knowledge gap on existing algorithms and their names, or, in case there is merit, leave a trace of my algorithm for others to use or improve upon.\n\n\n\n\n\n\n\nProblem statement\n\n\n\n\nIn a regular 2D array of N × M values, identify all local maxima positions within a given search radius R.\n\n\n\n\nA position p is considered a local maximum iff there exists no position q within radius R such that\n\n\n\n\nI(q) > I(p)\n\n\n\n\n\nwhere I(.) denotes the value at a position.\n\n\n\n\nEquivalently,\n\n\n\n\nI(p) >= I(q)\n\n\n\n\n\nfor all q satisfying\n\n\n\n\n||p-q|| <= R\n\n\n\n\n\nTypical dimensions for the problem in which speed should be optimum:\n\n\n\n\n\nArray sizes between 512×512 and 4096×4096 values\n\n\n\n\nSearch radii between 2 and 50 pixels\n\n\n\n\n\nThe algorithm should ideally be able to take advantage of parallelized processing, as total performance on multi-core CPUs is the relevant measure.\n\n\n\n\n\n\n\nMy Algorithm (to be discussed)\n\n\n\n\n\"Candidate-Pruning Algorithm for Circular Local-Maxima Detection in 2D Scalar Fields\"\n\n\n\n\nMain Idea\n\n\n\n\nA true 2D local maximum must also be a local maximum along its image row.\n\n\n\n\nInstead of testing every pixel against its complete circular neighborhood:\n\n\n\n\n\nDetect horizontal maxima only.\n\n\n\n\nUse these as candidate points.\n\n\n\n\nPerform the expensive 2D validation only for candidates.\n\n\n\n\n\nNote that \"row\" is used for simplicity here and refers to the longer dimension of a 2D array. (i.e. \"landscape format\" is assumed)\n\n\n\n\nStep 1: Horizontal candidate generation\n\n\n\n\nProcess each row independently.\n\n\n\n\nFor a current candidate c:\n\n\n\n\n\nExamine up to R pixels to the right.\n\n\n\n\nIf a larger value is found, replace c by that pixel and restart.\n\n\n\n\nIf an equal-valued pixel is found, remember the first such occurrence as a possible restart location.\n\n\n\n\nIf no larger value exists within distance R, mark c as a candidate.\n\n\n\n\nContinue from the remembered equal-valued position, or from the next increasing position.\n\n\n\n\n\nThis produces a superset of the true local maxima while avoiding many redundant comparisons.\n\n\n\n\nStep 2: Reverse validation\n\n\n\n\nFor every candidate from Step 1:\n\n\n\n\n\nExamine all pixels within distance R to the left.\n\n\n\n\nRemove the candidate if a larger value is found.\n\n\n\n\n\nAfter this step, every remaining candidate is a horizontal local maximum within radius R.\n\n\n\n\nStep 3: Exact 2D verification\n\n\n\n\nFor each remaining candidate c:\n\n\n\n\n\n\n\nConstruct the bounding box\n\n\n\n\n[x-R, x+R] × [y-R, y+R]\n\n\n\n\n\n\n\n\n\n\nFor each position q inside this box compute\n\n\n\n\ndx = q.x - c.x\ndy = q.y - c.y\n\n\n\n\n\n\n\n\n\n\nIgnore positions satisfying\n\n\n\n\ndx² + dy² > R²\n\n\n\n\n\n\n\n\n\n\nReject c if any remaining position satisfies\n\n\n\n\nI(q) > I(c)\n\n\n\n\n\n\n\n\n\nAll surviving candidates are reported as local maxima.\n\n\n\n\nComplexity\n\n\n\n\nNaive circular neighborhood search:\n\n\n\n\nO(N * M * R²)\n\n\n\n\n\nCandidate-pruning approach:\n\n\n\n\nCandidate generation: O(N * M)\nReverse validation: O(C * R)\nExact 2D check: O(C * R²)\n\n\n\n\n\nwhere C is the number of horizontal candidates.\n\n\n\n\nFor typical images,\n\n\n\n\nC << N * M\n\n\n\n\n\nand empirically the runtime appears substantially lower than a brute-force search.\n\n\n\n\nFor random data, C is roughly proportional to\n\n\n\n\n(N * M) / (2R + 1)\n\n\n\n\n\nsuggesting an expected runtime closer to\n\n\n\n\nO(N * M * R)\n\n\n\n\n\nthan\n\n\n\n\nO(N * M * R²)\n\n\n\n\n\nParallelization\n\n\n\n\n\nCandidate generation and Reverse validation are independent for each row.\n\n\n\n\nExact 2D verification is independent for each candidate.\n\n\n\n\n\nAll performance-critical stages can thus be parallelized efficiently.\n\n\n\n\nPlateaus handling\n\n\n\n\nPlateaus are treated as local maxima regions. The current implementation\nsuppresses duplicate detections within large plateaus, but does not perform explicit plateau-component analysis. Having large plateaus could lead to false positives (in the plateau) under some pathological conditions. Given the statistic nature and noise of the data I need to analyze, plateaus are generally not a concern so no extra guardrail against it is currently implemented. Simple cases like \"all equal value\" arrays are easily ruled out beforehand.\n\n\n\n\n\n\n\n\n\n\nSource Code\n\n\n\n\nI have not yet found the time to put that algorithm on GitHub or the like, but the relevant method can be found on Pastbin.com as C++ Source Code (https://pastebin.com/S36vYCyj). (Please ignore some less than optimized coding.)\n\n\n\n\nExample data\n\n\n\n\nAnalyzing this image with radius of 5:\n\n\n\n\n[image: Source Image; source: https://i.sstatic.net/99ssXXKN.png] (https://i.sstatic.net/99ssXXKN.png)\n\n\n\n\nGives these 43 maxima:\n\n\n\n\n[image: Maxim Masked; source: https://i.sstatic.net/4aVojm1L.png] (https://i.sstatic.net/4aVojm1L.png)\n\n\n\n\nINT X Y\n--------------\n65535 30 55\n65125 49 9\n64013 21 62\n63921 60 8\n63768 27 21\n63763 63 41\n63684 38 21\n62182 5 22\n62084 5 35\n61920 6 59\n61791 46 56\n61766 16 22\n61263 54 48\n60585 26 8\n60426 38 8\n60079 16 36\n59995 38 46\n59758 49 21\n59562 14 50\n59489 61 22\n59052 28 36\n58883 47 37\n58220 61 60\n58194 7 7\n50898 37 63\n39297 16 0\n33772 44 15\n33013 0 28\n32096 55 15\n31872 38 55\n30784 62 50\n29796 22 29\n29467 33 28\n29253 14 60\n29249 63 32\n29085 11 16\n28624 0 41\n28116 44 2\n27058 43 28\n26534 54 29\n26127 0 4\n24468 33 1\n23342 17 6","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":"BmyGuest","profile_url":"https://scicomp.stackexchange.com/users/28168/bmyguest","user_type":"registered"},"created_at":"2026-09-10T19:47:17+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EC1D3DC9-E3F4-4AC0-82C6-C9F8EB672BD3","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EC1D3DC9-E3F4-4AC0-82C6-C9F8EB672BD3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"BmyGuest","profile_url":"https://scicomp.stackexchange.com/users/28168/bmyguest","user_type":"registered"},"created_at":"2026-09-14T17:56:05+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"CD9810DA-8580-448F-9576-BB8397379DE5","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/CD9810DA-8580-448F-9576-BB8397379DE5/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"BmyGuest","profile_url":"https://scicomp.stackexchange.com/users/28168/bmyguest","user_type":"registered"},"created_at":"2026-09-14T18:16:29+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"C6FA2A25-8B71-4EED-8967-8E506BA50912","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C6FA2A25-8B71-4EED-8967-8E506BA50912/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"BmyGuest","profile_url":"https://scicomp.stackexchange.com/users/28168/bmyguest","user_type":"registered"},"created_at":"2026-09-14T18:28:24+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"867327B3-688D-48D2-9D4D-2ECEF8C84C03","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/867327B3-688D-48D2-9D4D-2ECEF8C84C03/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":"45538","source_record_sha256":"505366d5f1bb4a3e972a7b500fc776bf7fc2a53ee7c95661cfe0e33cf06dc5d8","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"

Questions

\n
    \n
  1. Does the below described (or a very similar) algorithm already exist in the literature under a specific name?

    \n
  2. \n
  3. Are there known local-maxima detection algorithms that are likely to outperform this candidate-pruning approach (on a multi-core CPU) at the typical conditions described?

    \n
  4. \n
\n
\n

Backstory

\n

Over a decade ago I was in need of finding local maxima positions in a regular 2D array of numbers within a provided search radius. I was looking for an algorithm that is fast on many such local maxima in a comparably small search-radius range. (The application are atomic resolution electron microscopy images.)

\n

\"HAADF

\n

At the time I couldn't find a suitable ready-to-implement algorithm, so I came up with my own algorithm and implemented it in C++. It works perfectly well for my needs with satisfactory speed.

\n

However, I have never

\n

a) searched whether that algorithm idea has been employed already and has a name, or

\n

b) performed serious benchmarking of the algorithm against other algorithms.

\n

I'm posting this here today to possibly have some experts look over it and either fill my knowledge gap on existing algorithms and their names, or, in case there is merit, leave a trace of my algorithm for others to use or improve upon.

\n
\n

Problem statement

\n

In a regular 2D array of N × M values, identify all local maxima positions within a given search radius R.

\n

A position p is considered a local maximum iff there exists no position q within radius R such that

\n
I(q) > I(p)\n
\n

where I(.) denotes the value at a position.

\n

Equivalently,

\n
I(p) >= I(q)\n
\n

for all q satisfying

\n
||p-q|| <= R\n
\n

Typical dimensions for the problem in which speed should be optimum:

\n
    \n
  • Array sizes between 512×512 and 4096×4096 values
  • \n
  • Search radii between 2 and 50 pixels
  • \n
\n

The algorithm should ideally be able to take advantage of parallelized processing, as total performance on multi-core CPUs is the relevant measure.

\n
\n

My Algorithm (to be discussed)

\n

"Candidate-Pruning Algorithm for Circular Local-Maxima Detection in 2D Scalar Fields"

\n

Main Idea

\n

A true 2D local maximum must also be a local maximum along its image row.

\n

Instead of testing every pixel against its complete circular neighborhood:

\n
    \n
  1. Detect horizontal maxima only.
  2. \n
  3. Use these as candidate points.
  4. \n
  5. Perform the expensive 2D validation only for candidates.
  6. \n
\n

Note that "row" is used for simplicity here and refers to the longer dimension of a 2D array. (i.e. "landscape format" is assumed)

\n

Step 1: Horizontal candidate generation

\n

Process each row independently.

\n

For a current candidate c:

\n
    \n
  1. Examine up to R pixels to the right.
  2. \n
  3. If a larger value is found, replace c by that pixel and restart.
  4. \n
  5. If an equal-valued pixel is found, remember the first such occurrence as a possible restart location.
  6. \n
  7. If no larger value exists within distance R, mark c as a candidate.
  8. \n
  9. Continue from the remembered equal-valued position, or from the next increasing position.
  10. \n
\n

This produces a superset of the true local maxima while avoiding many redundant comparisons.

\n

Step 2: Reverse validation

\n

For every candidate from Step 1:

\n
    \n
  1. Examine all pixels within distance R to the left.
  2. \n
  3. Remove the candidate if a larger value is found.
  4. \n
\n

After this step, every remaining candidate is a horizontal local maximum within radius R.

\n

Step 3: Exact 2D verification

\n

For each remaining candidate c:

\n
    \n
  1. Construct the bounding box

    \n
    [x-R, x+R] × [y-R, y+R]\n
    \n
  2. \n
  3. For each position q inside this box compute

    \n
    dx = q.x - c.x\ndy = q.y - c.y\n
    \n
  4. \n
  5. Ignore positions satisfying

    \n
    dx² + dy² > R²\n
    \n
  6. \n
  7. Reject c if any remaining position satisfies

    \n
    I(q) > I(c)\n
    \n
  8. \n
\n

All surviving candidates are reported as local maxima.

\n

Complexity

\n

Naive circular neighborhood search:

\n
O(N * M * R²)\n
\n

Candidate-pruning approach:

\n
Candidate generation: O(N * M)\nReverse validation:   O(C * R)\nExact 2D check:       O(C * R²)\n
\n

where C is the number of horizontal candidates.

\n

For typical images,

\n
C << N * M\n
\n

and empirically the runtime appears substantially lower than a brute-force search.

\n

For random data, C is roughly proportional to

\n
(N * M) / (2R + 1)\n
\n

suggesting an expected runtime closer to

\n
O(N * M * R)\n
\n

than

\n
O(N * M * R²)\n
\n

Parallelization

\n
    \n
  • Candidate generation and Reverse validation are independent for each row.
  • \n
  • Exact 2D verification is independent for each candidate.
  • \n
\n

All performance-critical stages can thus be parallelized efficiently.

\n

Plateaus handling

\n

Plateaus are treated as local maxima regions. The current implementation\nsuppresses duplicate detections within large plateaus, but does not perform explicit plateau-component analysis. Having large plateaus could lead to false positives (in the plateau) under some pathological conditions. Given the statistic nature and noise of the data I need to analyze, plateaus are generally not a concern so no extra guardrail against it is currently implemented. Simple cases like "all equal value" arrays are easily ruled out beforehand.

\n
\n
\n

Source Code

\n

I have not yet found the time to put that algorithm on GitHub or the like, but the relevant method can be found on Pastbin.com as C++ Source Code. (Please ignore some less than optimized coding.)

\n

Example data

\n

Analyzing this image with radius of 5:

\n

\"Source

\n

Gives these 43 maxima:

\n

\"Maxim

\n
INT      X   Y\n--------------\n65535   30  55\n65125   49  9\n64013   21  62\n63921   60  8\n63768   27  21\n63763   63  41\n63684   38  21\n62182   5   22\n62084   5   35\n61920   6   59\n61791   46  56\n61766   16  22\n61263   54  48\n60585   26  8\n60426   38  8\n60079   16  36\n59995   38  46\n59758   49  21\n59562   14  50\n59489   61  22\n59052   28  36\n58883   47  37\n58220   61  60\n58194   7   7\n50898   37  63\n39297   16  0\n33772   44  15\n33013   0   28\n32096   55  15\n31872   38  55\n30784   62  50\n29796   22  29\n29467   33  28\n29253   14  60\n29249   63  32\n29085   11  16\n28624   0   41\n28116   44  2\n27058   43  28\n26534   54  29\n26127   0   4\n24468   33  1\n23342   17  6\n
\n","question_title":"Does this local-maxima search algorithm have a name or is it 'new'?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new","split":"train"}