{"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\nLooking 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.
You should either figure out how to iterate over residues instead, or access the residue through the atom (possibly atom.resn , better atom.resi).
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, inmy attempt , input is protein Acb1 from 7t27.pdb ;
code :
\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\noutput 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\nit does 74 ALA ---> 74 TRP :
\n\n######################################################
\nSecond Script using the cmd.get_model(string "selection", integer "state" ) :
\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\nIt does iterate over atoms so the same output file, is overwritten more than once.
\nThe output file Acb1_74.pdb contains the original protein where
the Alanine 74 , the only closer than 5A to ECI ligand is mutated to Serine (yellow original , blue mutated):
\n\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, inCurrently 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\nHere is the code I used:
\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\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.
\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":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:
\n2pq < p^2\n2pq < q^2\n\nBy division, this means that:
\n2q < p\n2p < q\n\nSince p = 1 - q and q = 1 - p,
2q < 1 - q\n2p < 1 - p\n\nBy adding q or p to both sides of the equations,
\n3q < 1\n3p < 1\n\nDivide:
\nq < 1/3\np < 1/3\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.
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?
\nTotal individuals: 1000
\nGenotype counts:
\nAA: 500\nAa: 200\naa: 300\n\nCalculated allele frequency of a (q):
\nq = [(2 × aa) + Aa] / (2 × total individuals)\nq = [(2 × 300) + 200] / 2000 = 800/2000 = 0.4\n\nExpected frequency of aa under H-W equilibrium:
\nq² = (0.4)² = 0.16 (16%)\n\nObserved frequency of aa:
\n300/1000 = 0.3 (30%)\n\nCore issue:\nThe observed frequency of aa (30%) is much higher than the expected q² (16%) for q = 0.4.
\nDoes 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.
\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\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.
\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.
\nWikipedia lists the following
\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.
\nI 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.
\nAs 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.
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.
\nOtherwise, 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.
\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.
\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?
\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":{"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}
\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.
\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}
\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.
\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$$
\nwhere:
\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.
\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?
\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.
\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.
\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.
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;
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).
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_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\nAnd 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\nAny 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).
\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\ncould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\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).
\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\ncould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\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?
\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.
Count ~ All seagrass cover (%) + random site intercept\n\nCould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\nWould this be sufficient to avoid a claim for a causal link?
\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.
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"...
First, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.
\nNote that the "typical" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.
\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.
Wrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).
\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).
Last, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n
\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?
\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.
\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...
\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?
\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).
\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.
\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).
I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.
\nHere is an example of how the data is collected:
\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.
\nWhat I did to solve the issue:
\nThis left me with ~3000 rows of data for each cat.
\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:
\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("weighted OUF AKDE"["C"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("OUF AKDE"["C"]))\n\nHere is the resulting home range plots of 1 cat:\n
Here is the summary of wAKDE and AKDE respectively:\n
Here is the plot points of 1 cat across the campus (~2.5 months of data):\n
The issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.
\nMy questions:
\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)
\n","question_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:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n","answer_id":677089,"answer_text":"I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n","answer_id":677089,"answer_text":"I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.
Data here
\nshiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = "no food")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs="ts", k=5) +\n s(DO, bs="ts", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs="re"),\n \n data = shiny_toad,\n method = "REML", \n family = nb(link = "log"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n\n\n","question_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.
\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.
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\n\nFull code:
\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)\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.
\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.
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\n\nFull code:
\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)\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$$
\nFor a single unit,
\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$
\nand
\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$
\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).
\nThe 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)$$
\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).
\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):
\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\nHere are the results:
\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).
\nWhy 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":{"answer_html":"You are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n","answer_id":677139,"answer_text":"You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).","answer_url":"https://stats.stackexchange.com/a/677139","author":"J-J-J","author_url":"https://stats.stackexchange.com/users/164936/j-j-j","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T07:32:22+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T07:32:22+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"23216BD3-49D3-422F-8020-02B7D9CD2B5A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T08:09:51+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CB4779A0-4EA1-4BB0-99F8-7FFB266F646D","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}],"score":16,"updated_at":"2026-09-11T08:09:51+00:00"},"answer_scores":[{"answer_id":677136,"score":5},{"answer_id":677139,"score":16},{"answer_id":677141,"score":7}],"answers":[{"answer_html":"Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
Can you provide a {reprex}? I'm getting a warning when I run your code
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\nCreated on 2026-09-10 with reprex v2.1.1
\nEDIT: I was using an old version of R. Here is the reprex from using 4.6
\n(R.version.string)\n#> [1] "R version 4.6.0 (2026-04-24)"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nCreated on 2026-09-11 with reprex v2.1.1
\nNote, no warning. See J-J-J's comment for an explanation.
\n","answer_id":677136,"answer_text":"Can you provide a {reprex} (https://reprex.tidyverse.org/)? I'm getting a warning when I run your code\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\n\n\n\n\nCreated on 2026-09-10 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nEDIT: I was using an old version of R. Here is the reprex from using 4.6\n\n\n\n\n(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\n\n\n\n\nCreated on 2026-09-11 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nNote, no warning. See J-J-J's comment for an explanation.","answer_url":"https://stats.stackexchange.com/a/677136","author":"Demetri Pananos","author_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T01:34:59+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Demetri Pananos","profile_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","user_type":"registered"},"created_at":"2026-09-11T01:34:59+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"3461E410-C604-4E94-BBD3-042259374DDF","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Demetri Pananos","profile_url":"https://stats.stackexchange.com/users/111259/demetri-pananos","user_type":"registered"},"created_at":"2026-09-11T17:41:38+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"C692081B-A074-4F0B-985E-9AECEBE88DE5","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}],"score":5,"updated_at":"2026-09-11T17:41:38+00:00"},{"answer_html":"You are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n","answer_id":677139,"answer_text":"You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).","answer_url":"https://stats.stackexchange.com/a/677139","author":"J-J-J","author_url":"https://stats.stackexchange.com/users/164936/j-j-j","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T07:32:22+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T07:32:22+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"23216BD3-49D3-422F-8020-02B7D9CD2B5A","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"J-J-J","profile_url":"https://stats.stackexchange.com/users/164936/j-j-j","user_type":"registered"},"created_at":"2026-09-11T08:09:51+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CB4779A0-4EA1-4BB0-99F8-7FFB266F646D","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}],"score":16,"updated_at":"2026-09-11T08:09:51+00:00"},{"answer_html":"Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.
\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.
\n\nHere we range from evident to speculative:
\nInteger scores, so ties are more likely than otherwise.
\nIs there an upper limit of 32?
\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.
\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?
\n","answer_id":677141,"answer_text":"This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.\n\n\n\n\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/7o9W87he.png] (https://i.sstatic.net/7o9W87he.png)\n\n\n\n\nHere we range from evident to speculative:\n\n\n\n\n\n\n\nInteger scores, so ties are more likely than otherwise.\n\n\n\n\n\n\n\n\n\nIs there an upper limit of 32?\n\n\n\n\n\n\n\n\n\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.\n\n\n\n\n\n\n\n\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?","answer_url":"https://stats.stackexchange.com/a/677141","author":"Nick Cox","author_url":"https://stats.stackexchange.com/users/22047/nick-cox","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-11T08:47:46+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":677135,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-11T08:47:46+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"F5E781A6-F63A-4F3B-897E-03303213674F","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Nick Cox","profile_url":"https://stats.stackexchange.com/users/22047/nick-cox","user_type":"registered"},"created_at":"2026-09-11T09:20:25+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"2F24FDA3-AB03-426F-84C2-A097A0D37730","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}],"score":7,"updated_at":"2026-09-11T09:20:25+00:00"}],"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:
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n"tbl", "data.frame"))\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?
Here is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.
\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c("tbl_df", "tbl", "data.frame")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```\n\n","question_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.
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.
\nI 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.
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).
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).
| method | \ntest | \nType‑I error | \nbinom.test p | \n
|---|---|---|---|
| glmmTMB_wald (asymptotic Wald χ², uncorrected — original post's test) | \nanova | \n0.090 | \n9e-32 | \n
| glmmTMB_none (asymptotic LRT, uncorrected) | \nanova | \n0.068 | \n3e-8 | \n
| glmmTMB_satterthwaite | \nanova | \n0.052 | \n0.48 | \n
| glmmTMB_kenward-roger | \nanova | \n0.053 | \n0.40 | \n
| lme_varIdent | \nanova | \n0.052 | \n0.44 | \n
| lmerTest (no heteroscedasticity accommodation, baseline) | \nanova | \n0.055 | \n0.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.
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 ...
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\nBlog Post: https://lgraz.com/posts/lmm-heteroskedastic/
\nCurrent Model output:
\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\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":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.
There are monotonic versions of some of the methods.
\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (Code) and Monotonicity and Restart in Fast Gradient Methods.
I have this Exercise in my Numerical Optimization class and here it is:
\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:
\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:
\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.
\nThis is my code in Python:
\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = "Gradient Descent")\n plt.semilogy(agd_values, label = "Accelerated Gradient Descent")\n plt.xlabel("Iteration")\n plt.ylabel("Objective Value with Logarithmic Scale")\n plt.title("Ridge Regression: Objective Value vs Iteration "+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm , https://ibb.co/2DN3bnV , and https://ibb.co/Zpn0JY7z .
\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.
\n","question_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)).
Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.
\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:
\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.
\nHere is my code and these are the images that generate:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label="Gradient Descent")\n plt.semilogy(agd_values, label="Accelerated Gradient Descent")\n plt.xlabel("Iteration")\n plt.ylabel("Objective Value with Logarithmic Scale")\n plt.title("Logistic Regression: Objective Value vs Iteration "+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\nThese are the plots that generate:
\n\nWhy are my plots increasing in general and not generally decreasing?
\nWhat line of code do I need to fix?
\n","question_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*}$$
\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n
If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n
My python code used to compute this and make the animation is below:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r"$\\phi(t)$", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f"Updating frame{frame}")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n\n","answer_id":45119,"answer_text":"There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45119","author":"spektr","author_url":"https://scicomp.stackexchange.com/users/9804/spektr","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-06-17T21:04:45+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45112,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"spektr","profile_url":"https://scicomp.stackexchange.com/users/9804/spektr","user_type":"registered"},"created_at":"2025-06-17T21:04:45+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"E3F7E841-70B0-4D84-AA38-D0BBD92FA08E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}],"score":3,"updated_at":"2025-06-17T21:04:45+00:00"}],"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 i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.
\nBelow i listed some input files
\nUnstable simulation
\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\nHere is much more stable simulation with this input file
\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\nThis is my C++ code.
\nsimulation.cpp
\n#include <iostream>\n#include <fstream>\n#include <cmath>\nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin("input.txt");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = new int[nx];\n double *phi = new double[nx];\n double *pi = new double[nx];\n double *psi = new double[nx];\n double *chi = new double[nx];\n for (int x = 0; x < nx; ++x) {\n if (x == 0) {\n sup[x] = x+1;\n sdn[x] = nx-1;\n }\n else if (x == nx-1) {\n sup[x] = 0;\n sdn[x] = x-1;\n }\n else {\n sup[x] = x+1;\n sdn[x] = x-1;\n }\n phi[x] = cos(x*dx);\n pi[x] = sin(x*dx);\n }\n std::ofstream fout;\n for (int t = 0; t < nt; ++t) {\n fout.open("output_"+std::to_string(t)+".txt");\n for (int x = 0; x < nx; ++x) {\n psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n fout << x*dx << '\\t' << phi[x] << '\\n';\n }\n for (int x = 0; x < nx; ++x) {\n phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n }\n for (int x = 0; x < nx; ++x) {\n chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n }\n for (int x = 0; x < nx; ++x) {\n pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n }\n fout.close();\n }\n delete[] psi;\n delete[] chi;\n delete[] pi;\n delete[] phi;\n delete[] sup;\n delete[] sdn;\n}\n\n\n","question_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:
\nI wrote a symbolic regression tool in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?
import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n "abs": (sympy.Abs, operator.abs),\n "inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n "sqrt": (sympy.sqrt, np.sqrt),\n "cos": (sympy.cos, np.cos),\n "sin": (sympy.sin, np.sin),\n "exp": (sympy.tan, np.tan),\n "log": (sympy.log, np.log),\n "exp": (sympy.exp, np.exp),\n "sinh": (sympy.sinh, np.sinh),\n "cosh": (sympy.cosh, np.cosh),\n "floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n "ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor)}\n\nbinary_operators = {"+": (operator.add, operator.add),\n "-": (operator.sub, operator.sub),\n "*": (operator.mul, operator.mul),\n "/": (operator.truediv, operator.truediv),\n "//": (operator.floordiv, operator.floordiv),\n "%": (operator.mod, operator.mod),\n "**": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False}\nsymbols = sympy.symbols("x1 x2")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint("Top 10 features les plus corrélées (Pearson):\\n")\nfor name in correlations_sorted.head(10).index:\n print(f"{name:30} corr: {correlations[name]:+.4f}")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint("Top 10 features les plus utiles :\\n")\nfor name, score, r in features_sorted[:10]:\n print(f"{name:30} importance: {score:.4f} {r:.4f}")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint("un_ops", un_ops)\nprint("bin_ops", bin_ops)\n\nThe corresponding output is:
\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.
\nThe corresponding code could approach this:
\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = "a" + str(self.index)\n b = "b" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + "*" + str(self.leaf1) + "+" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr())) + ")+" + b)\n \n return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + ")+" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, "", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n #"abs": (sympy.Abs, operator.abs),\n #"inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n "sqrt": (sympy.sqrt, np.sqrt),\n "cos": (sympy.cos, np.cos),\n #"sin": (sympy.sin, np.sin),\n #"tan": (sympy.tan, np.tan),\n "log": (sympy.log, np.log),\n #"exp": (sympy.exp, np.exp),\n #"sinh": (sympy.sinh, np.sinh),\n #"cosh": (sympy.cosh, np.cosh),\n #"floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n #"ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor),\n }\n\nbinary_operators = {#"+": (operator.add, operator.add),\n #"-": (operator.sub, operator.sub),\n #"*": (operator.mul, operator.mul),\n #"/": (operator.truediv, operator.truediv),\n #"//": (operator.floordiv, operator.floordiv),\n #"%": (operator.mod, operator.mod),\n #"**": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False, "fmin": True, "fmax": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol("x1")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols("x1 x2"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:
\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == "a"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\nAnd the associated output (cos(log) optimization failed):
\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]\n\n","question_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\nPoincaré section obtained by conditions in the code
\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\nThe code can also be improved, so if anyone has any suggestions
\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:
\ng is both wrong and unnecessary; get the correct value from Scipy insteadmath module; stick to Numpyf() 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().solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.plt.show() once.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!
\nHere is the code: https://github.com/DJopek/chaos/blob/main/double_pendulum.py
\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\nPoincaré section obtained by conditions in the code:\n
EDIT:\nPoincaré section obtained by conditions in the code with labels
The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:
\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n930.8341950323121\n\n","answer_id":45249,"answer_text":"The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121","answer_url":"https://scicomp.stackexchange.com/a/45249","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-05T23:39:31+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45236,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-05T23:39:31+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"75229101-2A2D-4D73-B2A6-80096500FF72","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2025-10-05T23:51:10+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"11E4EE0D-659A-4B05-9326-A45AF5CAE292","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}],"score":3,"updated_at":"2025-10-05T23:51:10+00:00"}],"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
\nOn page 4 I am trying to turn this:
\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'
\nHere is my code, where am I going wrong? Thanks.
\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f"The result of the expression is: {result}")\n\n\n","question_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":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.
\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.
\n","answer_id":45279,"answer_text":"The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.","answer_url":"https://scicomp.stackexchange.com/a/45279","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-11-11T08:18:46+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45261,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-11T08:18:46+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2025-11-11T08:58:34+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"A797FC73-4FE4-442D-9FE9-D187BC73817D","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}],"score":2,"updated_at":"2025-11-11T08:58:34+00:00"}],"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":"#includeI'm trying to code the path integral simulation described in this article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?
\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.
\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:
\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\nAs you can see the matrix elements match the propagator at first time step.
\nHere i my code written in C.
\n#include <stdio.h>\n#include <complex.h>\n#include <math.h>\nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n for (int i = 0; i < size; ++i) {\n for (int j = 0; j < size; ++j) {\n B[i][j] = 0.0+I*0.0;\n for (int k = 0; k < size; ++k) {\n B[i][j] += A[i][k]*A[k][j];\n }\n B[i][j] *= pow(dx,n+1);\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n complex A[size][size];\n complex B[size][size];\n double x_a = 0;\n double x_b = 0;\n for (int i = 0; i < size; ++i) {\n double xi = -xmax+i*dx;\n for (int j = 0; j < size; ++j) {\n double xj = -xmax+j*dx;\n A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n if (i == 0 && j == 6) {\n x_a = xi;\n x_b = xj;\n printf("x_a = %f, x_b = %f\\n",xi,xj);\n }\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n for (int n = 0; n < 4; ++n) {\n if (n % 2 == 0) {\n mult(A,B,x_a,x_b,n);\n }\n else {\n mult(B,A,x_a,x_b,n);\n }\n }\n}\n\n\n","question_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.
Assuming the matrix $\\boldsymbol{A}$ is dense:
\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\nRemark: 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.
\nSet:
\nsparse_jacobian = Truefactorization_method = 'AugmentedSystem'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.bounds by your $l$ and $u$constraints to a LinearConstraint by your $A$ and using a scipy sparse arrayx0 to a sensible initial estimateIn 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","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$$
\nWhere $\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$ with independent rows.
\nI want to solve it for the cases:
\nIn most efficient way without using high level solvers.
\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.
Currently my approach is to use Dykstra Projection Algorithm.
\nI wonder if there are some acceleration tricks.
In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.
Here is the fixed code:
\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\nI 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.
Here is the fixed code:
\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\nI 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:
\nWith 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):
\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\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, with some modifications to preserve compatibility with the Scipy version ($A = QHQ^*$ instead of $H = QAQ^*$):
\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\nHowever, I haven't been able to get the actual algorithm working. So far, I have the following function:
\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\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
\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\nI 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\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.
\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.
\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)$.
\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.
\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.
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.
\nWith 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.
\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\\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}
\nNote 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$$
\nWe can use the Chebyshev polynomial of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\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$$
\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$$
\nand
\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$$
\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$$
\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$$
\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:
\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$$
\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$$
\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$$
\nNow 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$$
\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$$
\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$$
\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$$
\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$$
\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\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199
\nTime Taken: 0.001180 seconds
\nError 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$$
\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$$
\nAfter four iterations, $\\pi$ is accurate to $761$ digits:
\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131
\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\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.
\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?
\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$$\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$$
\nThanks!
\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.
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.
\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.
\nHere is win input:
\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\nHere are the fatbands:
\n| Index | \nOrbital | \nWeight | \nEnergy_min | \nEnergy_max | \n
|---|---|---|---|---|
| 1 | \nMnB-s | \n9.881649e-01 | \n-66.668270 | \n-66.667510 | \n
| 2 | \nMnB-s | \n9.879660e-01 | \n-66.668270 | \n-66.667510 | \n
| 3 | \nMnA-s | \n9.868490e-01 | \n-66.666030 | \n-66.665820 | \n
| 4 | \nMnA-s | \n9.867413e-01 | \n-66.666030 | \n-66.665820 | \n
| 5 | \nMnB-p | \n8.400973e-01 | \n-36.325620 | \n-36.323540 | \n
| 6 | \nMnB-p | \n8.317571e-01 | \n-36.325620 | \n-36.323540 | \n
| 7 | \nMnA-p | \n8.318057e-01 | \n-36.323460 | \n-36.317360 | \n
| 8 | \nMnA-p | \n8.401787e-01 | \n-36.323460 | \n-36.317360 | \n
| 9 | \nMnB-p | \n8.161489e-01 | \n-35.099230 | \n-35.097040 | \n
| 10 | \nMnB-p | \n8.040838e-01 | \n-35.099220 | \n-35.097020 | \n
| 11 | \nMnA-p | \n8.036925e-01 | \n-35.098130 | \n-35.089650 | \n
| 12 | \nMnA-p | \n8.164002e-01 | \n-35.098110 | \n-35.089650 | \n
| 13 | \nMnB-p | \n8.358367e-01 | \n-35.036260 | \n-35.031930 | \n
| 14 | \nMnB-p | \n8.179446e-01 | \n-35.036260 | \n-35.031850 | \n
| 15 | \nMnA-p | \n8.182119e-01 | \n-35.030990 | \n-35.025720 | \n
| 16 | \nMnA-p | \n8.356700e-01 | \n-35.030900 | \n-35.025720 | \n
| 17 | \nAs-s | \n8.392833e-01 | \n-0.831000 | \n1.316030 | \n
| 18 | \nAs-s | \n8.338588e-01 | \n-0.831000 | \n1.316030 | \n
| 19 | \nAs-s | \n9.058134e-01 | \n-0.209240 | \n1.324800 | \n
| 20 | \nAs-s | \n9.062729e-01 | \n-0.209240 | \n1.324800 | \n
| 21 | \nAs-p | \n6.143355e-01 | \n5.342380 | \n6.637930 | \n
| 22 | \nAs-p | \n6.134158e-01 | \n5.342380 | \n6.638240 | \n
| 23 | \nAs-p | \n5.129997e-01 | \n5.401290 | \n7.767510 | \n
| 24 | \nAs-p | \n5.125643e-01 | \n5.401290 | \n7.768130 | \n
| 25 | \nAs-p | \n4.726773e-01 | \n6.626010 | \n8.053720 | \n
| 26 | \nAs-p | \n4.721743e-01 | \n6.626520 | \n8.053720 | \n
| 27 | \nCu-d | \n4.986890e-01 | \n7.390900 | \n8.116920 | \n
| 28 | \nCu-d | \n4.998003e-01 | \n7.390900 | \n8.116970 | \n
| 29 | \nCu-d | \n6.113203e-01 | \n7.854560 | \n8.416970 | \n
| 30 | \nCu-d | \n6.121870e-01 | \n7.854630 | \n8.417060 | \n
| 31 | \nCu-d | \n6.305895e-01 | \n8.095260 | \n9.091470 | \n
| 32 | \nCu-d | \n6.304399e-01 | \n8.096400 | \n9.091470 | \n
| 33 | \nCu-d | \n9.469474e-01 | \n8.514170 | \n9.141630 | \n
| 34 | \nCu-d | \n9.472102e-01 | \n8.514250 | \n9.141630 | \n
| 35 | \nCu-d | \n8.649751e-01 | \n8.578920 | \n9.369690 | \n
| 36 | \nCu-d | \n8.651089e-01 | \n8.578920 | \n9.369690 | \n
| 37 | \nCu-d | \n8.952000e-01 | \n8.690770 | \n9.548950 | \n
| 38 | \nCu-d | \n8.955303e-01 | \n8.690900 | \n9.549270 | \n
| 39 | \nCu-d | \n8.297525e-01 | \n8.696380 | \n9.812650 | \n
| 40 | \nCu-d | \n8.296666e-01 | \n8.696380 | \n9.812870 | \n
| 41 | \nCu-d | \n9.651834e-01 | \n9.459160 | \n10.066180 | \n
| 42 | \nCu-d | \n9.651335e-01 | \n9.459450 | \n10.066180 | \n
| 43 | \nCu-d | \n7.823033e-01 | \n9.462930 | \n10.346490 | \n
| 44 | \nCu-d | \n7.823292e-01 | \n9.462930 | \n10.346490 | \n
| 45 | \nCu-d | \n6.928074e-01 | \n9.652790 | \n10.470370 | \n
| 46 | \nCu-d | \n6.929086e-01 | \n9.653110 | \n10.470370 | \n
| 47 | \nCu-d | \n7.334994e-01 | \n9.653590 | \n10.643890 | \n
| 48 | \nCu-d | \n7.336775e-01 | \n9.653590 | \n10.644060 | \n
| 49 | \nCu-d | \n4.933639e-01 | \n9.910510 | \n10.936240 | \n
| 50 | \nCu-d | \n4.946027e-01 | \n9.910660 | \n10.936620 | \n
| 51 | \nCu-d | \n3.412474e-01 | \n9.921660 | \n11.233320 | \n
| 52 | \nMnB-d | \n3.405554e-01 | \n9.921660 | \n11.233320 | \n
| 53 | \nMnB-d | \n4.567662e-01 | \n10.756070 | \n11.584470 | \n
| 54 | \nMnA-d | \n4.462384e-01 | \n10.756210 | \n11.584470 | \n
| 55 | \nMnB-d | \n4.871784e-01 | \n10.775950 | \n11.728830 | \n
| 56 | \nMnA-d | \n4.970518e-01 | \n10.775950 | \n11.728860 | \n
| 57 | \nMnB-d | \n5.524834e-01 | \n11.372610 | \n12.116350 | \n
| 58 | \nMnA-d | \n5.359463e-01 | \n11.372900 | \n12.116520 | \n
| 59 | \nMnB-d | \n5.310759e-01 | \n11.460860 | \n12.139320 | \n
| 60 | \nMnA-d | \n5.498770e-01 | \n11.460860 | \n12.139440 | \n
| 61 | \nMnA-d | \n6.319939e-01 | \n11.760980 | \n12.225210 | \n
| 62 | \nMnB-d | \n5.944707e-01 | \n11.760980 | \n12.225220 | \n
| 63 | \nMnA-d | \n5.561498e-01 | \n11.859100 | \n12.476320 | \n
| 64 | \nMnB-d | \n5.952141e-01 | \n11.859100 | \n12.476390 | \n
| 65 | \nMnA-d | \n4.443856e-01 | \n11.906640 | \n13.647540 | \n
| 66 | \nMnB-d | \n4.382827e-01 | \n11.906640 | \n13.647540 | \n
| 67 | \nMnA-d | \n4.037192e-01 | \n12.546070 | \n14.155400 | \n
| 68 | \nMnB-d | \n4.076979e-01 | \n12.546260 | \n14.155410 | \n
| 69 | \nMnA-d | \n3.818132e-01 | \n12.935250 | \n15.122080 | \n
| 70 | \nMnB-d | \n3.625459e-01 | \n12.935250 | \n15.122080 | \n
| 71 | \nMnA-d | \n3.490791e-01 | \n12.935300 | \n15.298100 | \n
| 72 | \nMnB-d | \n3.679672e-01 | \n12.935300 | \n15.298100 | \n
| 73 | \nAs-p | \n2.463906e-01 | \n13.337000 | \n17.231180 | \n
| 74 | \nAs-p | \n2.471224e-01 | \n13.337000 | \n17.231940 | \n
| 75 | \nAs-p | \n2.612448e-01 | \n13.338310 | \n17.238990 | \n
| 76 | \nAs-p | \n2.613523e-01 | \n13.338310 | \n17.239860 | \n
| 77 | \nCu-s | \n5.382811e-01 | \n15.735610 | \n18.080020 | \n
| 78 | \nCu-s | \n5.381753e-01 | \n15.735610 | \n18.080100 | \n
| 79 | \nCu-s | \n4.345647e-01 | \n15.735650 | \n19.014880 | \n
| 80 | \nCu-s | \n4.345746e-01 | \n15.735650 | \n19.015010 | \n
| 81 | \nCu-p | \n6.307476e-01 | \n17.150360 | \n21.672600 | \n
| 82 | \nCu-p | \n6.301829e-01 | \n17.150360 | \n21.672600 | \n
| 83 | \nCu-p | \n6.360863e-01 | \n17.151180 | \n21.688920 | \n
| 84 | \nCu-p | \n6.360073e-01 | \n17.151180 | \n21.689040 | \n
| 85 | \nCu-p | \n5.066000e-01 | \n18.637610 | \n21.999160 | \n
| 86 | \nCu-p | \n5.068897e-01 | \n18.637610 | \n22.000310 | \n
| 87 | \nCu-p | \n3.637123e-01 | \n18.842430 | \n22.443620 | \n
| 88 | \nCu-p | \n3.633814e-01 | \n18.842430 | \n22.443800 | \n
| 89 | \nCu-p | \n6.450014e-01 | \n20.094510 | \n25.706380 | \n
| 90 | \nCu-p | \n6.453492e-01 | \n20.094580 | \n25.706380 | \n
| 91 | \nCu-p | \n4.970763e-01 | \n20.505080 | \n25.707220 | \n
| 92 | \nCu-p | \n4.970011e-01 | \n20.505140 | \n25.707220 | \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.
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":"The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n","answer_id":45312,"answer_text":"Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.","answer_url":"https://scicomp.stackexchange.com/a/45312","author":"Federico Poloni","author_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-12-13T10:03:37+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45311,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-13T10:03:37+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"BFC0D245-EF3B-4C7B-9150-73518AFD2D2A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Federico Poloni","profile_url":"https://scicomp.stackexchange.com/users/4405/federico-poloni","user_type":"registered"},"created_at":"2025-12-18T09:34:32+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"74B8DDDA-9B0B-40CA-BE67-18501D69153F","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}],"score":6,"updated_at":"2025-12-18T09:34:32+00:00"}],"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
\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\nI am validating my code with the svd method that comes with numpy
\nU_, s_, Vt_ = np.linalg.svd(A)\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:
array([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\nbut for U_ (numpy code) it gives
\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\nthe second column of the U and U_ are not same. What did I wrong in my code?
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.
\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.
\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 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\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 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: [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.
\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.
\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 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\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 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: [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.
\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.".
\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.
\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.
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":{"answer_html":"The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n","answer_id":45327,"answer_text":"The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).","answer_url":"https://scicomp.stackexchange.com/a/45327","author":"Wolfgang Bangerth","author_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-03T02:46:44+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Wolfgang Bangerth","profile_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","user_type":"registered"},"created_at":"2026-01-03T02:46:44+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-23T14:37:58+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B49E063C-3F0D-471B-956C-B179F2F73567","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}],"score":10,"updated_at":"2026-01-23T14:37:58+00:00"},"answer_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.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n","answer_id":45327,"answer_text":"The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).","answer_url":"https://scicomp.stackexchange.com/a/45327","author":"Wolfgang Bangerth","author_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-03T02:46:44+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Wolfgang Bangerth","profile_url":"https://scicomp.stackexchange.com/users/393/wolfgang-bangerth","user_type":"registered"},"created_at":"2026-01-03T02:46:44+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-23T14:37:58+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B49E063C-3F0D-471B-956C-B179F2F73567","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}],"score":10,"updated_at":"2026-01-23T14:37:58+00:00"},{"answer_html":"I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.
\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).
\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.
\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.
\n","answer_id":45328,"answer_text":"I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.\n\n\n\n\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).\n\n\n\n\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.\n\n\n\n\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.","answer_url":"https://scicomp.stackexchange.com/a/45328","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-05T07:08:57+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2026-01-05T07:08:57+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"E5705B06-7DAC-4324-A752-C8064C49BB6C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}],"score":3,"updated_at":"2026-01-05T07:08:57+00:00"},{"answer_html":"Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.
\n","answer_id":45348,"answer_text":"Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.","answer_url":"https://scicomp.stackexchange.com/a/45348","author":"Donte Lightfoot","author_url":"https://scicomp.stackexchange.com/users/56387/donte-lightfoot","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-22T23:46:46+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45326,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Donte Lightfoot","profile_url":"https://scicomp.stackexchange.com/users/56387/donte-lightfoot","user_type":"registered"},"created_at":"2026-01-22T23:46:46+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"790DF00C-3B67-42CD-A314-653CD46193C9","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}],"score":2,"updated_at":"2026-01-22T23:46:46+00:00"}],"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.
\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.
\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):
\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$
\nwhere:
\nInitial conditions:
\nBoundary conditions:
\n$\\partial_t u + c\\,\\partial_n u = 0$
\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer
\nActivation: sin
Training:
\nCollocation points:
\nBoundary conditions:
\nVisualization:
\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.
\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.
\n","question_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":{"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
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
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.
\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5<g<0.5$. In other words, it doesn't matter how strong or weak $J$ is (as long as it is positive), there is always ferromagnetic order as long as $|g|$ is smaller than $0.5$, and $M=0$ everywhere else.
\nThis is a very odd result that doesn't make sense to me, so I am inclined to believe there is something wrong with my computational methods. I attach the code I used and the diagram that it produced. My code closely mirrors the example from MPSKit.jl's github:
\nusing MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n H = transverse_field_ising(; J=J, g=g)\n groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n return abs(expectation_value(groundstate, 1 => σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel="J", ylabel="g", title="Magnetization M(g, J)")\n\nAnd here is the resulting heatmap:
\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.
\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":{"answer_html":"Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n","answer_id":45388,"answer_text":"Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.","answer_url":"https://scicomp.stackexchange.com/a/45388","author":"wim","author_url":"https://scicomp.stackexchange.com/users/5286/wim","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-02-27T09:44:31+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45387,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-27T09:44:31+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"42AA8384-A67D-4B93-8A67-6F2708905EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-28T23:54:12+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"3E89E9AE-7857-41C4-8456-59AB2D1A01FD","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-02T09:09:00+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"98F99AB1-1D15-4C9A-942A-7E8E8455BA0F","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}],"score":7,"updated_at":"2026-03-02T09:09:00+00:00"},"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.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n","answer_id":45388,"answer_text":"Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.","answer_url":"https://scicomp.stackexchange.com/a/45388","author":"wim","author_url":"https://scicomp.stackexchange.com/users/5286/wim","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-02-27T09:44:31+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45387,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-27T09:44:31+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"42AA8384-A67D-4B93-8A67-6F2708905EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"wim","profile_url":"https://scicomp.stackexchange.com/users/5286/wim","user_type":"registered"},"created_at":"2026-02-28T23:54:12+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"3E89E9AE-7857-41C4-8456-59AB2D1A01FD","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Damien","profile_url":"https://scicomp.stackexchange.com/users/761/damien","user_type":"registered"},"created_at":"2026-03-02T09:09:00+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"98F99AB1-1D15-4C9A-942A-7E8E8455BA0F","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}],"score":7,"updated_at":"2026-03-02T09:09:00+00:00"}],"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:
\nfunction [x, y] = ThreeProduct(a, b, c)\n\nSuch that:
\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nBackground
\nOgita et al. (2005) introduced a method of computing a dot product based on "Error Free Transformation" primitives, such as TwoSum() (due to Knuth) and TwoProduct():
function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name "Error Free Transformation". That is, for TwoSum():
$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$
\nAnd for TwoProduct():
$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$
\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.
\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.
\nMy question is whether there is a known algorithm for the product of three floating point numbers ("ThreeProduct()"). That is, something where the following holds:
$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.
\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.
References:
\nOgita, T. et al., "Accurate Sum and Dot Product", SIAM Journal of Scientific Computing, 2005.
\nGraillat, S. "Accurate Floating Point Product and Exponentiation". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.
\n","question_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: &NodeI have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):
\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.
\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.
\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:
\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.
\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:
\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.
\nI am going to describe the logic in a high level:
\nThe actual code is this:
\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node<HpNode<f32, 10>>| {\n // Legendre coefficients.\n let cfs = node.data.coeffs(); \n let coeff_count = node.data.coeff_count();\n\n let pos = box_position + box_dims / 2.;\n let p = (cam_pos - pos) / box_dims;\n let v = ray / box_dims;\n\n let mut a = 0.;\n let mut b = 0.;\n let mut c = 0.;\n // Shift and scale the ray and pos to the local node.\n let ray = v;\n let ray_pos = p;\n for i in 0..coeff_count\n {\n // Coefficient + the degree of each legendre polynomial that was\n // tensor producted to make the basis element, i.e. one of\n // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n let (s, powers) = cfs[i as usize];\n // Compute coefficients for each dimension's Legendre polynomial\n // restricted to line.\n let mut poly = [1., 0., 0.];\n // accumulates as [t^0, t^1, t^2] coefficients.\n\n for axis in 0..3\n {\n // Get teh axial coefficients of this ray\n let (v, p) = match axis\n {\n 0 => (ray.x, ray_pos.x),\n 1 => (ray.y, ray_pos.y),\n 2 => (ray.z, ray_pos.z),\n _ => unreachable!(),\n };\n\n let power = powers[axis];\n\n // Legendre polynomial P_n(vt + p) coefficients in t.\n let leg_coeffs = match power\n {\n 0 => [1., 0., 0.],\n 1 => [p, v, 0.],\n // coefficients of the legendre polynomial of degree 2\n 2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n _ => unreachable!(),\n };\n\n // Multiply poly *= leg_coeffs.\n let temp = [\n poly[0] * leg_coeffs[0],\n poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n poly[0] * leg_coeffs[2]\n + poly[1] * leg_coeffs[1]\n + poly[2] * leg_coeffs[0],\n ];\n poly = temp;\n }\n\n a += s * poly[2];\n b += s * poly[1];\n c += s * poly[0];\n }\n\n let disc = b * b - 4. * a * c;\n if disc < 0.\n {\n return f32::INFINITY;\n }\n\n let sqrt_disc = disc.sqrt();\n let inv_2a = 1. / (2. * a);\n\n // Quadratic solutions.\n let x1 = (-b - sqrt_disc) * inv_2a;\n let x2 = (-b + sqrt_disc) * inv_2a;\n\n // Branchless valid selection: if x < 0, replace with infinity.\n let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n // Take minimum of valid solutions.\n let quad_t = valid_x1.min(valid_x2);\n\n // Handle linear case.\n let is_linear = a.abs() < 0.0001;\n let linear_t = -c / b;\n\n let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n if is_linear { linear_t } else { quad_t }\n };\n\nTo add further context, to generate the image with the additional spheres all you need to do is hard code the coefficients for a sphere:
\n let cfs = [\n (-0.1 + 1., [0, 0, 0]),\n (2./3., [2, 0, 0]),\n (2./3., [0, 2, 0]),\n (2./3., [0, 0, 2]),\n ];\n let coeff_count = 4;\n\nTo override the ones coming in. But the input coefficients cannot eb wrong because then the first image would not work.
\nThere's something wrong with the way I am computing my ray quadric collisions that is specific to the Legendre case. When I modify my logic to work with the sphere quadrics it works, as shown, so I must have messed something up with when computing the coefficients, but when I see the written code I fail to see what.
\n","question_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":{"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$$
\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$.
\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$$\nh_{new} = \\beta \\, h \\, err^{-1/(\\min(p+m, p) + 1)}\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
\nSo to answer your questions
\n\n\nAre these two acceptance criteria strictly equivalent in practice
\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\nIs one approach considered more robust or standard in modern implementations
\n
Criteria 1 is not robust, 2 is somewhat robust, and what I provided above most robust.
\n\n\nAre there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?
\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$$
\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$.
\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$$\nh_{new} = \\beta \\, h \\, err^{-1/(\\min(p+m, p) + 1)}\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
\nSo to answer your questions
\n\n\nAre these two acceptance criteria strictly equivalent in practice
\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\nIs one approach considered more robust or standard in modern implementations
\n
Criteria 1 is not robust, 2 is somewhat robust, and what I provided above most robust.
\n\n\nAre there known situations (e.g., stiff/chaotic systems) where comparing via ( s ) is preferable?
\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:
\nCompute two solutions: $$ y^{[p]} \\text{ and } y^{[p+m]} $$
\nEstimate local error: $$ \\text{err} = \\left| y^{[p+m]} - y^{[p]} \\right|$$
\nCompute scaling factor:
\n$$\n s = \\beta \\left( \\frac{\\text{tol}}{\\text{err}} \\right)^{1/p}\n $$
Update step:
\n$$\n h_{\\text{new}} = s \\cdot h\n $$
My question is about the accept/reject criterion:
\nif (s >= 1) accept step\nelse reject\n\nif (err <= tol) accept step\nelse reject\n\nFrom what I understand, these should be mathematically equivalent if ( s ) is defined as above.
\nHowever:
\nI tested both approaches on the double pendulum problem, counting rejected steps. Using:
\nI observed:
\nUsing ( s $\\ge$ 1 ):
\nUsing ( $ \\text{err} \\le \\text{tol} $):
\nBoth solutions remain within the requested tolerance band.
\nIf anyone can clarify whether there is a theoretical or practical reason to prefer one over the other, I would really appreciate it.
\nThanks!
\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.
\nThe given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).
\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.
\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.
\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.
\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.
\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).
\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:
\n| First polynomial | \nSecond polynomial | \n
|---|---|
| $1$ or $q^0$ | \n$q^{8+2x_{13}}$ | \n
| $q^2$ | \n$q^{10+2x_{13}}$ | \n
| $q^8$ | \n$q^{4+2x_{15}}$ | \n
| $q^{10}$ | \n$q^{6+2x_{15}}$ | \n
| $q^{12}$ | \n$q^{2x_{17}}$ | \n
| $q^{14}$ | \n$q^{2+2x_{17}}$ | \n
| $q^{16}$ | \n$q^{2x_{35}}$ | \n
| $q^{18}$ | \n$q^{2+2x_{35}}$ | \n
| $q^{20}$ | \n$q^{-4+2x_{37}}$ | \n
| $q^{22}$ | \n$q^{-2+2x_{37}}$ | \n
| $q^{24}$ | \n$q^{-8+2x_{57}}$ | \n
| $q^{26}$ | \n$q^{-6+2x_{57}}$ | \n
Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.
\nThis resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.
\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.
\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.
\n","answer_id":45473,"answer_text":"The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.","answer_url":"https://scicomp.stackexchange.com/a/45473","author":"hardmath","author_url":"https://scicomp.stackexchange.com/users/651/hardmath","author_user_type":"moderator","content_license":"CC BY-SA 4.0","created_at":"2026-06-24T21:53:31+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45472,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"hardmath","profile_url":"https://scicomp.stackexchange.com/users/651/hardmath","user_type":"moderator"},"created_at":"2026-06-24T21:53:31+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"6B10CE88-2D26-43C8-9F27-870834FE5FB3","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}],"score":2,"updated_at":"2026-06-24T21:53:31+00:00"},{"answer_html":"Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative "pulls down" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:
restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.
\n","answer_id":45482,"answer_text":"Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative \"pulls down\" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:\n\n\n\n\nrestart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\n\n\n\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.","answer_url":"https://scicomp.stackexchange.com/a/45482","author":"dharr","author_url":"https://scicomp.stackexchange.com/users/50934/dharr","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-06-28T17:22:41+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45472,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-28T17:22:41+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"17B5B435-530D-44FB-A531-8C7EBC69DAB0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-28T17:30:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"B335F14D-BC1A-4871-8C8E-AA1A1574CE8E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T00:34:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE6B318A-E224-4873-94DF-796E47B0400A","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T01:28:55+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"E46B4CBF-9F68-49D7-885E-BE0F07FBA25B","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-06-29T02:02:10+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"BE24CE57-475F-48DB-8B09-676A64E891E3","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"dharr","profile_url":"https://scicomp.stackexchange.com/users/50934/dharr","user_type":"registered"},"created_at":"2026-07-06T01:31:28+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"64B9EB1B-7407-427F-BF22-4AF94181F69C","revision_number":6,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}],"score":3,"updated_at":"2026-07-06T01:31:28+00:00"}],"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.
\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.
\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.
\nDo you guys know of any hint or solution on how to tackle these problems?
\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$
\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$
\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.
\n","question_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.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n","answer_id":45503,"answer_text":"The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.","answer_url":"https://scicomp.stackexchange.com/a/45503","author":"Omar Osman Mahamoud","author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-29T16:42:27+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-29T16:42:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"DD32D002-9E3F-4398-BC22-FB7FBF667951","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}],"score":2,"updated_at":"2026-07-29T16:42:27+00:00"},"answer_scores":[{"answer_id":45490,"score":6},{"answer_id":45491,"score":7},{"answer_id":45503,"score":2}],"answers":[{"answer_html":"Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\nFor n=5000, dt=0.001, the output is closer yet:
\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n","answer_id":45490,"answer_text":"From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n[image: comparison; source: https://i.sstatic.net/ZOXbZlmS.png] (https://i.sstatic.net/ZOXbZlmS.png)\n\n\n\n\nFor n=5000, dt=0.001, the output is closer yet:\n\n\n\n\n[image: dt=0.001; source: https://i.sstatic.net/mLRffKQD.png] (https://i.sstatic.net/mLRffKQD.png)\n\n\n\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine (https://www.sciencedirect.com/science/article/pii/0893965989900797) form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: RK32; source: https://i.sstatic.net/DgMDrx4E.png] (https://i.sstatic.net/DgMDrx4E.png)","answer_url":"https://scicomp.stackexchange.com/a/45490","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-13T01:47:13+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T01:47:13+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"06EC415F-DC78-49A5-97D0-ED020CE6C74F","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T03:28:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"88B016CA-5B2E-46C7-99DA-7F374A3A0853","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-07-13T21:27:38+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"51F9060A-E0B8-4FC6-AAA1-D61ED8331962","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}],"score":6,"updated_at":"2026-07-13T21:27:38+00:00"},{"answer_html":"When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.
\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!
\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)
\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods "symplectic integrators", because they preserve energy and impulse better, but my memory may be leaky.
\n","answer_id":45491,"answer_text":"When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.\n\n\n\n\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!\n\n\n\n\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)\n\n\n\n\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods \"symplectic integrators\", because they preserve energy and impulse better, but my memory may be leaky.","answer_url":"https://scicomp.stackexchange.com/a/45491","author":"MPIchael","author_url":"https://scicomp.stackexchange.com/users/28636/mpichael","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-13T06:50:20+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MPIchael","profile_url":"https://scicomp.stackexchange.com/users/28636/mpichael","user_type":"registered"},"created_at":"2026-07-13T06:50:20+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}],"score":7,"updated_at":"2026-07-13T06:50:20+00:00"},{"answer_html":"The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n","answer_id":45503,"answer_text":"The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.","answer_url":"https://scicomp.stackexchange.com/a/45503","author":"Omar Osman Mahamoud","author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-07-29T16:42:27+00:00","is_accepted":true,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45487,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Omar Osman Mahamoud","profile_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","user_type":"registered"},"created_at":"2026-07-29T16:42:27+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"DD32D002-9E3F-4398-BC22-FB7FBF667951","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}],"score":2,"updated_at":"2026-07-29T16:42:27+00:00"}],"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":"Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.
\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.
\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?
\nHere are the three implementations.
\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?
\n","question_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\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
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\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?
\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\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
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\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?
\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.
\nI am implementing a two-dimensional displacement-based finite element code in MATLAB.
\nFor a Q4 element, stress and strain are calculated at four (2\\times2) Gauss integration points. In my current post-processing code, I use:
\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\nI then use the nodal-coordinate arrays X and Y, together with stress_xx, to produce a colored element plot.
\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.
\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.
\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.
\nMy questions are:
\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.
\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\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.
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\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.
I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).
\nAlso, I feel the need to remind you that
\nStopping short of rewriting this as an IVP for you, the vectorised version can look like:
\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","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).
\nThe code is:
\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\nThis produces the following result:
\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.
\nSo I changed
\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\nto
\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\nsince the total acceleration acting on body j should be the sum of the accelerations produced by every other body.
\nHowever, this actually makes the simulation even worse. The result becomes:
\n\nSo I feel that I am missing something more fundamental.
\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?
\nLikewise, why does the += version diverge so quickly instead of improving the simulation?
\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.
\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.
\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":"Your calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n","answer_id":45524,"answer_text":"Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nYour calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n","answer_id":45524,"answer_text":"Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nI am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:
\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:
\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?
\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: "Figure. Regular Heptagon Image taken from a Math Stack Exchange Question", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.
\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:
\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.
\n\n\nFrom the question "What could be this unknown angle in this regular\nheptagon?"
\nThere is the image drawn of a Regular Heptagon:
\n\n\n\n
![]()
Figure. Regular Heptagon Image taken from a\nMath Stack Exchange Question
On the site: https://www.onlinegdb.com/online_c_compiler
\n#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double pid;\n // pid=acos(-1);\n // double DegreesToRadians = 3.14159265358979323846/180.0;\n // double DegreesToRadians = pid/180.0;\n // const double DegreesToRadians=3.14159265358979323846/180.0;\n double DegreesToRadians=acos(-1.0)/180.0;\n \n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n // 3. Print Results\n // %lf is the format specifier for double, %f is for float\n // printf("Double: cos(%.1lf degrees) = %lf\\n", degrees_d, result_double);\n // printf("Float: cos(%.1f degrees) = %f\\n", degrees_f, result_float);\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n\n printf("Double: acos(-1.0) %.15lf \\n",acos(-1.0));\n printf("Double: vec cb dot vec cf %0.15lf\\n", cbdotcf);\n printf("Double: vec ab dot vec af %0.15lf\\n", abdotaf);\n printf("Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf("Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n\n return 0;\n}\n\nTaking the suggestions from Reinderien's answer, the source code was updated. Using the online c compiler https://www.onlinegdb.com/online_c_compiler, the below source code compiled fine and yielded angles very consistent with Reinderien's answer quoted below, with instead of 2 digits precision, 15 digit precision:
\n\n\n\n
n = 7\ncbcf = 88.56°\nabaf = 88.56°
#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double DegreesToRadians = 3.14159265358979323846/180.0;\n\n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-veca[1];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n //Calculate the necessary dot products\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n // Print Results\n // %lf is the format specifier for double %l.15 is for 15 digits to the right\n // That amount of precision is consistant with the constant PI as a double float\n printf("Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \\n");\n printf("Double: acos(-1.0) = %.15lf \\n",acos(-1.0));\n printf("Constant 3.14159265358979323846 = %.15lf \\n",3.14159265358979323846);\n printf("Double: acos(-1.0)/180.0 = %.15lf \\n",acos(-1.0)/180.0);\n printf("Double: 3.14159265358979323846/180.0 = %.15lf \\n",3.14159265358979323846/180.0);\n printf("Double: vec cb dot vec cf %0.15lf\\n", cbdotcf);\n printf("Double: vec ab dot vec af %0.15lf\\n", abdotaf);\n printf("Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf("Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n return 0;\n}\n\n","question_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$.
\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.
\nimport sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\nHere are a few finite element specific resources:
\nFor how to analyze the general stability of numerical discretizations:
\nI need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled "Finite Element Method", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.
\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?
\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided
\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = "Lagrange" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure("dx", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = "preonly" # Preconditioning Matrix Option\nsolver_type = "lu" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix="first_order_ODE", bcs = [bc], petsc_options={"ksp_type": ksp_type, "pc_type": solver_type})\nu_sol = problem.solve()\n\n\nwe can see the solution is infinity at all node values of the functionspace.
\n","question_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$$
\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.
\nExample: left stable, right unstable
\n\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:
\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\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# 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\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# 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\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.
\nThe following results are obtained without hardening:\nFirst, I have turned on the dealiasing mask. This gives me the following solution:\n
The domain growth is also well obtained and follows the theoretical 1/3 law.\n
The problem comes in the structure factor collapse:\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.
\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
With hardening the slope also comes around to -3. But the problem of oscillation still remains.\n
I have also plotted the regions which are outside the [-1,1] value range.\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).
\nThe main doubts are:
\nThe 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.
\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.
\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(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$.)
\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.
\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)$.
\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.
\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","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":"Does the below described (or a very similar) algorithm already exist in the literature under a specific name?
\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?
\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\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.
\nHowever, I have never
\na) searched whether that algorithm idea has been employed already and has a name, or
\nb) performed serious benchmarking of the algorithm against other algorithms.
\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.
\nIn a regular 2D array of N × M values, identify all local maxima positions within a given search radius R.
\nA position p is considered a local maximum iff there exists no position q within radius R such that
\nI(q) > I(p)\n\nwhere I(.) denotes the value at a position.
\nEquivalently,
\nI(p) >= I(q)\n\nfor all q satisfying
\n||p-q|| <= R\n\nTypical dimensions for the problem in which speed should be optimum:
\nThe algorithm should ideally be able to take advantage of parallelized processing, as total performance on multi-core CPUs is the relevant measure.
\n"Candidate-Pruning Algorithm for Circular Local-Maxima Detection in 2D Scalar Fields"
\nA true 2D local maximum must also be a local maximum along its image row.
\nInstead of testing every pixel against its complete circular neighborhood:
\nNote that "row" is used for simplicity here and refers to the longer dimension of a 2D array. (i.e. "landscape format" is assumed)
\nProcess each row independently.
\nFor a current candidate c:
\nThis produces a superset of the true local maxima while avoiding many redundant comparisons.
\nFor every candidate from Step 1:
\nAfter this step, every remaining candidate is a horizontal local maximum within radius R.
\nFor each remaining candidate c:
\nConstruct the bounding box
\n[x-R, x+R] × [y-R, y+R]\n\nFor each position q inside this box compute
\ndx = q.x - c.x\ndy = q.y - c.y\n\nIgnore positions satisfying
\ndx² + dy² > R²\n\nReject c if any remaining position satisfies
\nI(q) > I(c)\n\nAll surviving candidates are reported as local maxima.
\nNaive circular neighborhood search:
\nO(N * M * R²)\n\nCandidate-pruning approach:
\nCandidate generation: O(N * M)\nReverse validation: O(C * R)\nExact 2D check: O(C * R²)\n\nwhere C is the number of horizontal candidates.
\nFor typical images,
\nC << N * M\n\nand empirically the runtime appears substantially lower than a brute-force search.
\nFor random data, C is roughly proportional to
\n(N * M) / (2R + 1)\n\nsuggesting an expected runtime closer to
\nO(N * M * R)\n\nthan
\nO(N * M * R²)\n\nAll performance-critical stages can thus be parallelized efficiently.
\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.
\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. (Please ignore some less than optimized coding.)
\nAnalyzing this image with radius of 5:
\n\nGives these 43 maxima:
\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\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"}