{"accepted_answer_id":null,"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_license":"CC BY-SA 4.0","question_score":1,"question_text":"I have this Exercise in my Numerical Optimization class and here it is:\n\n\n\n\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:\n\n\n\n\n\nthe underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$\n\n\n\n\nthe measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$\n\n\n\n\nthe observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$\n\n\n\n\n\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:\n\n\n\n\n\nGradient descent\n\n\n\n\nAccelerated gradient descent\n\n\n\n\n\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.\n\n\n\n\nThis is my code in Python:\n\n\n\n\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm (https://ibb.co/KjKshhKm) , https://ibb.co/2DN3bnV (https://ibb.co/2DN3bnV) , and https://ibb.co/Zpn0JY7z (https://ibb.co/Zpn0JY7z) .\n\n\n\n\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.","question_text_sha256":"22785281a3f101c82e88dc0425b55a038f82fe44cc4075bbca1b74e401f740e0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Sid Meka","profile_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","user_type":"registered"},"created_at":"2025-06-07T03:14:18+00:00","raw_file":"raw/codex_api_v1/18019c65cead443968e23d401a2956091deb8b40ada648e04bed5e2f03ce54b5_1790825348716030900_0.json","raw_sha256":"05729e3e9dd3f73dae19eda7639475c736dfb4d5818353d669924bc12ddae880","revision_guid":"211F9448-16A8-4E36-8763-3B16D1CD1986","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/211F9448-16A8-4E36-8763-3B16D1CD1986/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"validation","split_group":"1fe7ba3ca3f859465e473df309f25bf7b5692a6de860e2cd0386b157f8ac2c00","tags":["optimization","python","numerics","regression","data-analysis"],"thread_id":45100,"thread_url":"https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent","title":"Gradient Descent vs Accelerated Gradient Descent"} {"accepted_answer_id":null,"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_license":"CC BY-SA 4.0","question_score":1,"question_text":"Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.\n\n\n\n\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:\n\n\n\n\n\n$\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$\n\n\n\n\n$X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$\n\n\n\n\n$z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$\n\n\n\n\n$y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$\n\n\n\n\n$\\theta_0$ has independent and identically distributed standard normal entries\n\n\n\n\n\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.\n\n\n\n\nHere is my code and these are the images that generate:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\nThese are the plots that generate:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/M60t0s9p.png] (https://i.sstatic.net/M60t0s9p.png)\n\n\n\n\nWhy are my plots increasing in general and not generally decreasing?\n\n\n\n\nWhat line of code do I need to fix?","question_text_sha256":"e75202803552f0dfef935eb29c627b64165b6cb3a962e57310f8cbeb7f8e686c","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Sid Meka","profile_url":"https://scicomp.stackexchange.com/users/51369/sid-meka","user_type":"registered"},"created_at":"2025-06-09T03:53:39+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"6C5B17A4-CCFF-4791-B573-A3BEFEA6E971","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6C5B17A4-CCFF-4791-B573-A3BEFEA6E971/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Anton Menshov","profile_url":"https://scicomp.stackexchange.com/users/20688/anton-menshov","user_type":"moderator"},"created_at":"2025-06-10T17:23:33+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"04CCF3DF-8003-43DC-8B20-604199CED7CE","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/04CCF3DF-8003-43DC-8B20-604199CED7CE/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"M. A.","profile_url":"https://scicomp.stackexchange.com/users/54367/m-a","user_type":"registered"},"created_at":"2025-08-03T03:10:56+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"432A63F6-E7D4-4894-AE88-DA68EC44307B","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/432A63F6-E7D4-4894-AE88-DA68EC44307B/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"6cb3c632d9188ff6520de774a0da40d2c3e0b1e5cb90a81a9637f07c3a5b16e8","tags":["optimization","numpy","regression"],"thread_id":45105,"thread_url":"https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting","title":"Logistic Regression: Gradient Descent and Accelerated Version Thereof not acting as intended"} {"accepted_answer_id":null,"answers":[{"answer_html":"There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.
\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$
\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n
If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n
My python code used to compute this and make the animation is below:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r"$\\phi(t)$", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f"Updating frame{frame}")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n\n","answer_id":45119,"answer_text":"There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45119","author_display_name":"spektr","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Peter","question_author_url":"https://scicomp.stackexchange.com/users/46677/peter","question_author_user_type":"registered","question_created_at":"2025-06-13T14:05:56+00:00","question_html":"i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.
\nBelow i listed some input files
\nUnstable simulation
\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\nHere is much more stable simulation with this input file
\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\nThis is my C++ code.
\nsimulation.cpp
\n#include <iostream>\n#include <fstream>\n#include <cmath>\nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin("input.txt");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = new int[nx];\n double *phi = new double[nx];\n double *pi = new double[nx];\n double *psi = new double[nx];\n double *chi = new double[nx];\n for (int x = 0; x < nx; ++x) {\n if (x == 0) {\n sup[x] = x+1;\n sdn[x] = nx-1;\n }\n else if (x == nx-1) {\n sup[x] = 0;\n sdn[x] = x-1;\n }\n else {\n sup[x] = x+1;\n sdn[x] = x-1;\n }\n phi[x] = cos(x*dx);\n pi[x] = sin(x*dx);\n }\n std::ofstream fout;\n for (int t = 0; t < nt; ++t) {\n fout.open("output_"+std::to_string(t)+".txt");\n for (int x = 0; x < nx; ++x) {\n psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n fout << x*dx << '\\t' << phi[x] << '\\n';\n }\n for (int x = 0; x < nx; ++x) {\n phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n }\n for (int x = 0; x < nx; ++x) {\n chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n }\n for (int x = 0; x < nx; ++x) {\n pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n }\n fout.close();\n }\n delete[] psi;\n delete[] chi;\n delete[] pi;\n delete[] phi;\n delete[] sup;\n delete[] sdn;\n}\n\n\n","question_license":"CC BY-SA 4.0","question_score":1,"question_text":"i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog (https://en.wikipedia.org/wiki/Leapfrog_integration) method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.\n\n\n\n\nBelow i listed some input files\n\n\n\n\nUnstable simulation (https://jumpshare.com/s/zPqlo3o0AGXPfadHQmxG)\n\n\n\n\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nHere is much more stable simulation (https://jumpshare.com/s/IyNNcFdCeCTAcpIShWLY) with this input file\n\n\n\n\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nThis is my C++ code.\n\n\n\n\nsimulation.cpp\n\n\n\n\n#include In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:
\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_license":"CC BY-SA 4.0","question_score":0,"question_text":"I wrote a symbolic regression tool (https://github.com/Julien-Livet/SymbolicRegression) in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?\n\n\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n \"abs\": (sympy.Abs, operator.abs),\n \"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n \"sin\": (sympy.sin, np.sin),\n \"exp\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n \"exp\": (sympy.exp, np.exp),\n \"sinh\": (sympy.sinh, np.sinh),\n \"cosh\": (sympy.cosh, np.cosh),\n \"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n \"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor)}\n\nbinary_operators = {\"+\": (operator.add, operator.add),\n \"-\": (operator.sub, operator.sub),\n \"*\": (operator.mul, operator.mul),\n \"/\": (operator.truediv, operator.truediv),\n \"//\": (operator.floordiv, operator.floordiv),\n \"%\": (operator.mod, operator.mod),\n \"**\": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False}\nsymbols = sympy.symbols(\"x1 x2\")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint(\"Top 10 features les plus corrélées (Pearson):\\n\")\nfor name in correlations_sorted.head(10).index:\n print(f\"{name:30} corr: {correlations[name]:+.4f}\")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint(\"Top 10 features les plus utiles :\\n\")\nfor name, score, r in features_sorted[:10]:\n print(f\"{name:30} importance: {score:.4f} {r:.4f}\")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint(\"un_ops\", un_ops)\nprint(\"bin_ops\", bin_ops)\n\n\n\n\n\nThe corresponding output is:\n\n\n\n\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\n\n\n\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.\n\n\n\n\nThe corresponding code could approach this:\n\n\n\n\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = \"a\" + str(self.index)\n b = \"b\" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + \"*\" + str(self.leaf1) + \"+\" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr())) + \")+\" + b)\n \n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + \")+\" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, \"\", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n #\"abs\": (sympy.Abs, operator.abs),\n #\"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n #\"sin\": (sympy.sin, np.sin),\n #\"tan\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n #\"exp\": (sympy.exp, np.exp),\n #\"sinh\": (sympy.sinh, np.sinh),\n #\"cosh\": (sympy.cosh, np.cosh),\n #\"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n #\"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor),\n }\n\nbinary_operators = {#\"+\": (operator.add, operator.add),\n #\"-\": (operator.sub, operator.sub),\n #\"*\": (operator.mul, operator.mul),\n #\"/\": (operator.truediv, operator.truediv),\n #\"//\": (operator.floordiv, operator.floordiv),\n #\"%\": (operator.mod, operator.mod),\n #\"**\": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False, \"fmin\": True, \"fmax\": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol(\"x1\")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols(\"x1 x2\"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\n\n\n\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:\n\n\n\n\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == \"a\"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\n\n\n\n\nAnd the associated output (cos(log) optimization failed):\n\n\n\n\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]","question_text_sha256":"211ccd764b5745b19e65264c399aca1c805436d6f69437d58ccd4bd318bc7ba7","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-15T09:46:23+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"6EC977E1-3082-4152-AE79-21C738DBF959","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/6EC977E1-3082-4152-AE79-21C738DBF959/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-15T17:29:07+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"B4A3E844-33AB-4467-864F-D74942286C5A","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B4A3E844-33AB-4467-864F-D74942286C5A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-16T18:01:50+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"4E41E649-9940-470F-BD64-37949F9902D3","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4E41E649-9940-470F-BD64-37949F9902D3/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"P'tit Ju","profile_url":"https://scicomp.stackexchange.com/users/54117/ptit-ju","user_type":"registered"},"created_at":"2025-06-17T08:11:19+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"C61EE61B-3C64-482A-BAC2-3A48B78BE0AE","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C61EE61B-3C64-482A-BAC2-3A48B78BE0AE/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"test","split_group":"c60046cebb2604b9000a0728000b0fece1c2a7221faa51282758a10c688b5e28","tags":["python","regression","sympy"],"thread_id":45114,"thread_url":"https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression","title":"Find necessary operators for symbolic regression"}
{"accepted_answer_id":null,"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_display_name":"Reinderien","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Dávid Jopek","question_author_url":"https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek","question_author_user_type":"registered","question_created_at":"2025-07-15T18:16:26+00:00","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
I might have found the solution, of which I'm listing the main points/observations here below:
\nOf course, if you have any further comments or observations let me know!
\n","answer_id":45186,"answer_text":"I might have found the solution, of which I'm listing the main points/observations here below:\n\n\n\n\n\nthe FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok\n\n\n\n\nthe dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output\n\n\n\n\nSPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)\n\n\n\n\na spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)\n\n\n\n\n\nOf course, if you have any further comments or observations let me know!","answer_url":"https://scicomp.stackexchange.com/a/45186","author_display_name":"Lorenzo Iori","author_profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-07-29T14:07:20+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45185,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-29T14:07:20+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"163AA634-CBFB-456A-AD54-8FFDF16B1F6A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}],"score":3,"updated_at":"2025-07-29T14:07:20+00:00"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Lorenzo Iori","question_author_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","question_author_user_type":"registered","question_created_at":"2025-07-28T09:04:03+00:00","question_html":"I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.
\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).
\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.
\nHere are the fundamental cells of the notebook:
\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention
\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...
\n","question_license":"CC BY-SA 4.0","question_score":2,"question_text":"I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.\n\n\n\n\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).\n\n\n\n\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.\n\n\n\n\nHere are the fundamental cells of the notebook:\n\n\n\n\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\n\n\n\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention\n\n\n\n\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\n\n\n\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...","question_text_sha256":"d181be256325da38fe68fa8ceb2da41172bca5bfea689d70a579e52bc185dc3a","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T09:04:03+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T09:15:52+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"BE26735D-FCBC-47F1-A566-F341DD41F55C","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/BE26735D-FCBC-47F1-A566-F341DD41F55C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T14:07:20+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"67CC67B8-AC93-4C69-9C21-0E6BDBF43102","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/67CC67B8-AC93-4C69-9C21-0E6BDBF43102/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-28T14:32:46+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"3BBDD6A2-8D30-430A-8EAF-A458144119BA","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3BBDD6A2-8D30-430A-8EAF-A458144119BA/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Lorenzo Iori","profile_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","user_type":"registered"},"created_at":"2025-07-29T14:04:04+00:00","raw_file":"raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json","raw_sha256":"33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0","revision_guid":"B35F7AAE-2953-45D0-AD16-97CC9997095D","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B35F7AAE-2953-45D0-AD16-97CC9997095D/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"7be9f71292d1bf888dba09fb08b628318d904aa4df046b5f908f3641c52dea34","tags":["python","computational-physics","fourier-transform","wave-propagation","operator-splitting"],"thread_id":45185,"thread_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything","title":"Split-step Fourier method for ultrashort pulse propagation predicts everything, but not the spectral phase"} {"accepted_answer_id":null,"answers":[{"answer_html":"The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:
\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n930.8341950323121\n\n","answer_id":45249,"answer_text":"The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121","answer_url":"https://scicomp.stackexchange.com/a/45249","author_display_name":"Reinderien","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"gregb","question_author_url":"https://scicomp.stackexchange.com/users/54734/gregb","question_author_user_type":"registered","question_created_at":"2025-09-15T21:46:02+00:00","question_html":"I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf
\nOn page 4 I am trying to turn this:
\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'
\nHere is my code, where am I going wrong? Thanks.
\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f"The result of the expression is: {result}")\n\n\n","question_license":"CC BY-SA 4.0","question_score":2,"question_text":"I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)\n\n\n\n\nOn page 4 I am trying to turn this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)\n\n\n\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'\n\n\n\n\nHere is my code, where am I going wrong? Thanks.\n\n\n\n\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")","question_text_sha256":"da01231d96229828d4167e347d93464f7c3dff58f259629e8220fd709881cfc8","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"test","split_group":"e28b01df57bb20a31ec24e606c73512f1963d92331c51743a46755ebddf69039","tags":["python"],"thread_id":45236,"thread_url":"https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere","title":"Panini sticker python coding problem - bug in my code somewhere"}
{"accepted_answer_id":null,"answers":[{"answer_html":"Dear Lutz Lehmann and community,
\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.
\nFor reference, here is the corresponding code.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label="Velocity (m/s) at pipe center")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity at the middle of the pipe (m/s)")\nplt.title("Velocity evolution at the middle of the pipe")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f"t = {temps_selectionnes[i]:.1f} s")\nplt.xlabel("Position x (m)")\nplt.ylabel("Velocity (m/s)")\nplt.title("Velocity profile along the pipe at different times")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\nBest regards,\nRaphaël
\n","answer_id":45250,"answer_text":"Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël","answer_url":"https://scicomp.stackexchange.com/a/45250","author_display_name":"Ev0Cation","author_profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-07T14:19:16+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45246,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-07T14:19:16+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C3CA863F-650C-4C2D-BD76-4C6863DC85E0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}],"score":2,"updated_at":"2025-10-07T14:19:16+00:00"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Ev0Cation","question_author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","question_author_user_type":"registered","question_created_at":"2025-10-03T16:37:31+00:00","question_html":"I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.
\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.
\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.
\nCould you please give me some guidance on how to solve this problem please?
\nI will include my current code and figure below for reference.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label="Velocity (m/s)")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity")\nplt.title("Velocity evolution")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n","question_license":"CC BY-SA 4.0","question_score":1,"question_text":"I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)","question_text_sha256":"886e0d7ea581900bf8fedcd683e6d96c46d968e011872185c132dc58906f4e05","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-03T16:37:31+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"10D2B924-C266-46E3-844E-A857A83DB2A0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/10D2B924-C266-46E3-844E-A857A83DB2A0/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"test","split_group":"9f3717535b35a99ca712d918b086bd672aead7606c87f0225057f8747406bb69","tags":["python","fluid-dynamics","boundary-conditions","navier-stokes"],"thread_id":45246,"thread_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation","title":"Oscillations in 1D compressible Navier–Stokes simulation"}
{"accepted_answer_id":null,"answers":[{"answer_html":"The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.
\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.
\n","answer_id":45279,"answer_text":"The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.","answer_url":"https://scicomp.stackexchange.com/a/45279","author_display_name":"MPIchael","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Peter","question_author_url":"https://scicomp.stackexchange.com/users/46677/peter","question_author_user_type":"registered","question_created_at":"2025-10-19T14:49:08+00:00","question_html":"I'm trying to code the path integral simulation described in this article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?
\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.
\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:
\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\nAs you can see the matrix elements match the propagator at first time step.
\nHere i my code written in C.
\n#include <stdio.h>\n#include <complex.h>\n#include <math.h>\nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n for (int i = 0; i < size; ++i) {\n for (int j = 0; j < size; ++j) {\n B[i][j] = 0.0+I*0.0;\n for (int k = 0; k < size; ++k) {\n B[i][j] += A[i][k]*A[k][j];\n }\n B[i][j] *= pow(dx,n+1);\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n complex A[size][size];\n complex B[size][size];\n double x_a = 0;\n double x_b = 0;\n for (int i = 0; i < size; ++i) {\n double xi = -xmax+i*dx;\n for (int j = 0; j < size; ++j) {\n double xj = -xmax+j*dx;\n A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n if (i == 0 && j == 6) {\n x_a = xi;\n x_b = xj;\n printf("x_a = %f, x_b = %f\\n",xi,xj);\n }\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n for (int n = 0; n < 4; ++n) {\n if (n % 2 == 0) {\n mult(A,B,x_a,x_b,n);\n }\n else {\n mult(B,A,x_a,x_b,n);\n }\n }\n}\n\n\n","question_license":"CC BY-SA 4.0","question_score":2,"question_text":"I'm trying to code the path integral simulation described in this (https://arxiv.org/pdf/quant-ph/9511042) article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?\n\n\n\n\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.\n\n\n\n\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:\n\n\n\n\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\n\n\n\n\nAs you can see the matrix elements match the propagator at first time step.\n\n\n\n\nHere i my code written in C.\n\n\n\n\n#include The 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_display_name":"Royi","author_profile_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_display_name":"Reinderien","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Royi","question_author_url":"https://scicomp.stackexchange.com/users/7951/royi","question_author_user_type":"registered","question_created_at":"2025-10-25T07:56:29+00:00","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_display_name":"DMDemon","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"DMDemon","question_author_url":"https://scicomp.stackexchange.com/users/55920/dmdemon","question_author_user_type":"registered","question_created_at":"2025-10-28T18:12:37+00:00","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_license":"CC BY-SA 4.0","question_score":1,"question_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.","question_text_sha256":"1283c316892d2b9c6c59d09a9cb41a7e52c89287ebfa055e18b7f5595dca7469","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"44acef578e9c05780327dc39179f6687e373930c874253169525f35807c93419","tags":["linear-algebra","python","qr"],"thread_id":45269,"thread_url":"https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api","title":"Help implementing the Hessenberg QR algorithm using the Keras Ops API"} {"accepted_answer_id":null,"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_display_name":"njuffa","author_profile_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_display_name":"MPIchael","author_profile_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_display_name":"vengy","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"vengy","question_author_url":"https://scicomp.stackexchange.com/users/56070/vengy","question_author_user_type":"registered","question_created_at":"2025-11-26T20:12:50+00:00","question_html":"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_license":"CC BY-SA 4.0","question_score":6,"question_text":"I have this recurrence formula for $\\pi$ with convergence order $2m+1$:\n\n\n\n\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$\n\n\n\n\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$\n\n\n\n\nAfter four iterations, $\\pi$ is accurate to $761$ digits:\n\n\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n\n\n\n\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.\n\n\n\n\nQuestion\n\n\n\n\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?\n\n\n\n\nUpdate\n\n\n\n\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:\n\n\n\n\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$\n\n\n\n\nThanks!","question_text_sha256":"bc9b8a4d834a34d9a6068c8c238473162a65203bf24f3aefdc7b7b0a02b16b7a","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"8f36e1bcd2b33cd4ffa628a2386cda6ce0eaf7936b3632b7a940b6d196b58805","tags":["optimization","numerics"],"thread_id":45291,"thread_url":"https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms","title":"Efficient computation of $\\sin(k x_n)$ in iterative algorithms"} {"accepted_answer_id":null,"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_display_name":"Federico Poloni","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Argha Nilanjon Nondi","question_author_url":"https://scicomp.stackexchange.com/users/56165/argha-nilanjon-nondi","question_author_user_type":"registered","question_created_at":"2025-12-12T11:42:59+00:00","question_html":"Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code
\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\nI am validating my code with the svd method that comes with numpy
\nU_, s_, Vt_ = np.linalg.svd(A)\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:
array([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\nbut for U_ (numpy code) it gives
\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\nthe second column of the U and U_ are not same. What did I wrong in my code?
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_license":"CC BY-SA 4.0","question_score":4,"question_text":"I have a quadratic programming problem\n$$\n\\begin{matrix}\n\\textrm{minimise} & x^TQx \\\\\n\\textrm{subject to} & Ax = b\n\\end{matrix}\n$$\nwhere $x$ is a vector of unknowns, $Q$ is a positive semi-definite matrix, $A$ is a matrix of constraint coefficients, and $b$ is a vector of constraint rhs values. The constraints represented by $Ax=b$ are linearly dependent. To give an idea of the extent of linear dependency, $A$ could be something $350 \\times 300$, so 350 constraints with 300 unknowns, but this reduces to 280 linearly independent constraints. It can be safely assumed that the constraints are consistent and $\\textrm{null}(Q)\\cap\\textrm{null}(A)=\\{0\\}$ such that the problem has a unique solution. I would like to find a way to solve this problem for large and sparse $Q$ and $A$. I have attempted the following.\n\n\n\n\nFirst, I tried reducing $A$ to only have linearly independent rows, denoted $A_R$, and solving the KKT system\n$$\n\\begin{bmatrix}\nQ & A_R^T \\\\\nA_R & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nI reduced $A$ to linearly independent rows by performing a sparse rank-revealing QR decomposition on $A^T$ to get the linearly independent columns of $A^T$. If this succeeded, I solved the KKT system using a sparse LU decomposition. Solving the KKT system didn't have any issues, however the sparse rank-revealing QR decomposition on $A^T$ was quite fragile and failed on larger systems. I used the C++ library Eigen with Eigen::SparseQR to perform the decomposition. In the Eigen documentation it says \"The numerical pivoting strategy and default threshold are the same as in SuiteSparse QR ... even though it is qualified as \"rank-revealing\", this strategy might fail for some rank deficient problems.\".\n\n\n\n\nSecond, I tried solving the KKT system directly without reducing $A$\n$$\n\\begin{bmatrix}\nQ & A^T \\\\\nA & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nThis is a singular system, so I tried solving it with MINRES. Again I used the Eigen library (Eigen::MINRES). The convergence was extremely poor and solutions usually had a large error. I didn't use a preconditioner as I wasn't sure how to form one for this scenario.\n\n\n\n\nThird, I tried using nonlinear optimiser Ipopt. This did not work at all since Ipopt immediately exits with error Not_Enough_Degrees_Of_Freedom. There is an option in Ipopt to detect and remove linearly dependent constraints but in the docs it says \"This is experimental and does not work well.\", so I'm assuming this will have the same issues as the first approach.\n\n\n\n\nSo, what approaches could I use to solve this problem for large and sparse $Q$ and $A$?. Simply converting everything to dense matrices is not feasible as I need to solve this sort of system for millions of unknowns and constraints.","question_text_sha256":"52d0917e614932aba0b94504467ba28b73757772a408fea6eea811a047041632","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"BenPol","profile_url":"https://scicomp.stackexchange.com/users/56185/benpol","user_type":"registered"},"created_at":"2025-12-16T01:29:04+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"52AB4280-FF49-4A54-8177-8AFB5BBE2030","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/52AB4280-FF49-4A54-8177-8AFB5BBE2030/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"bd2f6dbe43adc2d1563d6e606547bb3bbb20919dbde2c004f93e4348466b0516","tags":["constrained-optimization","convex-optimization","quadratic-programming"],"thread_id":45313,"thread_url":"https://scicomp.stackexchange.com/questions/45313/quadratic-programming-with-linearly-dependent-equality-constraints","title":"Quadratic programming with linearly dependent equality constraints"} {"accepted_answer_id":null,"answers":[{"answer_html":"this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.
\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.
\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.
\n","answer_id":45329,"answer_text":"this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.\n\n\n\n\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.\n\n\n\n\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.","answer_url":"https://scicomp.stackexchange.com/a/45329","author_display_name":"Linda Anderson","author_profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-05T09:26:54+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45322,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Linda Anderson","profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","user_type":"registered"},"created_at":"2026-01-05T09:26:54+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"8F296337-1611-4B90-B028-6FDD3F098E8A","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/8F296337-1611-4B90-B028-6FDD3F098E8A/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Linda Anderson","profile_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","user_type":"registered"},"created_at":"2026-01-05T09:27:15+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"317C93D3-B055-47E3-8255-35BB56F95C1B","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/317C93D3-B055-47E3-8255-35BB56F95C1B/view-source"}],"score":5,"updated_at":"2026-01-05T09:27:15+00:00"},{"answer_html":"The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):
\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distribution<real_type> local_dis(0.0, 1.0);\n\n real_type local_count = 0;\n real_type local_count_plus = 0;\n\n // Update progress every N iterations to reduce atomic overhead\n const long long unsigned int progress_update_interval = 10000;\n long long unsigned int local_progress = 0;\n\n for (long long unsigned int i = start_idx; i < end_idx; i++)\n {\n vector_3 location = random_unit_vector(local_gen, local_dis);\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n\n // A) Newtonian gravitation\n //vector_3 normal =\n // surface_normal;\n\n // B) Schwarzschild gravitation\n //vector_3 normal = \n // random_cosine_weighted_hemisphere(\n // surface_normal, local_gen, local_dis);\n\n // C) Quantum gravitation\n vector_3 r = random_unit_vector(local_gen, local_dis);\n r.x *= emitter_radius;\n r.y *= emitter_radius;\n r.z *= emitter_radius;\n vector_3 normal = (location - r).normalize();\n\n\n local_count += intersect(\n location, normal,\n receiver_distance, receiver_radius);\n\n local_count_plus += intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n // Update global progress periodically\n local_progress++;\n if (local_progress >= progress_update_interval)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n \n local_progress = 0;\n }\n }\n\n // Add any remaining progress\n if (local_progress > 0)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n }\n\n result_count = local_count;\n result_count_plus = local_count_plus;\n}\n\n","answer_id":45343,"answer_text":"The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):\n\n\n\n\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distributionWhat is the name of the numerical technique used to generate the appropriate gravitational acceleration by using a set of gravitational field lines that are not necessarily normal to the surface of the emitter?
\nI have found that using cosine weighted pseudorandom field lines produces the result predicted by Schwarzschild's general relativity. It's a very simple calculation. Please help me identify its owner.
\nIn the past, I have written a short tutorial for C++ programmers on isotropic Newtonian gravitation.\nIn that old tutorial, I build an isotropic gravitational field through the use of pseudorandomly generated field lines.\nIn that old tutorial I use a sphere as the receiver.\nThe paper for that old tutorial is at Newtonian gravitation from scratch, for C++ programmers.
\nIn this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book Gravitation, by Misner et al).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.
\nIn this question I use Planck units, where $c = G = \\hbar = k = 1$.
\nWhere $r_{e}$ is the emitter's Schwarzschild radius, $r_{r}$ is the receiver AABB radius (e.g. half of the AABB side length), and $1\\mathrm{e}11$ and $0.01$ are arbitrary constants:\n\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}\n\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}\nThe event horizon area is:\n\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}\nWhere $R$ is the distance from the emitter's centre, the derivative is:\n\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}\nHere $\\beta$ is the get intersecting line density function.\nThe gradient strength is:\n\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}\nFrom this I get the Newtonian acceleration $a_N$, where $r_e \\ll R$:\n\\begin{equation}\na_N =\\frac{g R \\log 2}{8 M_{e}} = \\sqrt{\\frac{n_e \\log 2}{4 \\pi R^4}} = \\frac{M_{e}}{R^2}.\n\\end{equation}\nI can also get a general relativistic acceleration $a_S$, where $r_e < R$:\n\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}\nAt close proximity, where $r_e \\approx R$, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}\n\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}\n\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}\nAt far proximity, where $r_e \\ll R$, $t \\approx 1$, and $dt/dR \\approx 0$, the metric produced is Newtonian -- curved space, practically flat time.
\nUsing numerical relativity, I tried pseudorandom hemisphere and pseudorandom tangent plane field lines, but they did not work.\nThe only technique that works is cosine weighted pseudorandom field lines.\nThat is to say, as per the code for this tutorial (https://github.com/sjhalayka/schwarzschild_falloff_field_lines), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of $2 / \\pi$.
\nThis figure shows an axis-aligned bounding box and an isotropic emitter, looking from slightly above.\nAn example field line (red) and intersecting line segment (green) are given.\nThe bounding box is filled with these green intersecting line segments.\nIt is the gradient of the density of these line segments that forms the gravitational acceleration.\nNote that the field line is normal to the surface of the emitter (producing Newtonian gravitation).
\ndouble get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_cast<unsigned>(0));\n\n for (long long unsigned int i = 0; i < n; i++)\n {\n vector_3 location = random_unit_vector();\n\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n vector_3 normal = \n random_cosine_weighted_hemisphere(\n surface_normal);\n\n std::optional<double> i_hit = intersect(\n location, normal, \n receiver_distance, receiver_radius);\n\n if (i_hit)\n count += *i_hit / (2.0 * receiver_radius);\n \n i_hit = intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n if (i_hit)\n count_plus += *i_hit / (2.0 * receiver_radius);\n }\n\n return count_plus - count;\n}\n\nThank you for your time!
\n","question_license":"CC BY-SA 4.0","question_score":5,"question_text":"Question\n\n\n\n\nWhat is the name of the numerical technique used to generate the appropriate gravitational acceleration by using a set of gravitational field lines that are not necessarily normal to the surface of the emitter?\n\n\n\n\nI have found that using cosine weighted pseudorandom field lines produces the result predicted by Schwarzschild's general relativity. It's a very simple calculation. Please help me identify its owner.\n\n\n\n\nIntroduction\n\n\n\n\nIn the past, I have written a short tutorial for C++ programmers on isotropic Newtonian gravitation.\nIn that old tutorial, I build an isotropic gravitational field through the use of pseudorandomly generated field lines.\nIn that old tutorial I use a sphere as the receiver.\nThe paper for that old tutorial is at Newtonian gravitation from scratch, for C++ programmers (https://www.techrxiv.org/users/685306/articles/1250456-newtonian-gravitation-from-scratch-for-c-programmers).\n\n\n\n\nIn this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book Gravitation, by Misner et al (https://search.worldcat.org/title/585119)).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.\n\n\n\n\nIn this question I use Planck units, where $c = G = \\hbar = k = 1$.\n\n\n\n\nMethod\n\n\n\n\nWhere $r_{e}$ is the emitter's Schwarzschild radius, $r_{r}$ is the receiver AABB radius (e.g. half of the AABB side length), and $1\\mathrm{e}11$ and $0.01$ are arbitrary constants:\n\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}\n\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}\nThe event horizon area is:\n\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}\nWhere $R$ is the distance from the emitter's centre, the derivative is:\n\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}\nHere $\\beta$ is the get intersecting line density function.\nThe gradient strength is:\n\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}\nFrom this I get the Newtonian acceleration $a_N$, where $r_e \\ll R$:\n\\begin{equation}\na_N =\\frac{g R \\log 2}{8 M_{e}} = \\sqrt{\\frac{n_e \\log 2}{4 \\pi R^4}} = \\frac{M_{e}}{R^2}.\n\\end{equation}\nI can also get a general relativistic acceleration $a_S$, where $r_e < R$:\n\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}\nAt close proximity, where $r_e \\approx R$, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}\n\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}\n\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}\nAt far proximity, where $r_e \\ll R$, $t \\approx 1$, and $dt/dR \\approx 0$, the metric produced is Newtonian -- curved space, practically flat time.\n\n\n\n\nUsing numerical relativity, I tried pseudorandom hemisphere and pseudorandom tangent plane field lines, but they did not work.\nThe only technique that works is cosine weighted pseudorandom field lines.\nThat is to say, as per the code for this tutorial (https://github.com/sjhalayka/schwarzschild_falloff_field_lines (https://github.com/sjhalayka/schwarzschild_falloff_field_lines)), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of $2 / \\pi$.\n\n\n\n\nFigure\n\n\n\n\n[image: axis-aligned bounding box; source: https://i.sstatic.net/XWbsh2qc.png] (https://i.sstatic.net/XWbsh2qc.png)\n\n\n\n\nThis figure shows an axis-aligned bounding box and an isotropic emitter, looking from slightly above.\nAn example field line (red) and intersecting line segment (green) are given.\nThe bounding box is filled with these green intersecting line segments.\nIt is the gradient of the density of these line segments that forms the gravitational acceleration.\nNote that the field line is normal to the surface of the emitter (producing Newtonian gravitation).\n\n\n\n\nC++ code\n\n\n\n\ndouble get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_castThe 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_display_name":"Wolfgang Bangerth","author_profile_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_display_name":"MPIchael","author_profile_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_display_name":"Donte Lightfoot","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Anwesh Saha","question_author_url":"https://scicomp.stackexchange.com/users/56260/anwesh-saha","question_author_user_type":"registered","question_created_at":"2026-01-01T19:29:53+00:00","question_html":"I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.
\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.
\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):
\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$
\nwhere:
\nInitial conditions:
\nBoundary conditions:
\n$\\partial_t u + c\\,\\partial_n u = 0$
\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer
\nActivation: sin
Training:
\nCollocation points:
\nBoundary conditions:
\nVisualization:
\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.
\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.
\n","question_license":"CC BY-SA 4.0","question_score":3,"question_text":"I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.\n\n\n\n\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.\n\n\n\n\n[image: output GIF; source: https://i.sstatic.net/9QczcfVK.gif] (https://i.sstatic.net/9QczcfVK.gif)\n\n\n\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/IMsKTvWk.png] (https://i.sstatic.net/IMsKTvWk.png)\n\n\n\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$\n\n\n\n\nwhere:\n\n\n\n\n\n(c = 1)\n\n\n\n\n(f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence\n\n\n\n\n\nInitial conditions:\n\n\n\n\n\n(u(x,y,0) = 0)\n\n\n\n\n$\\partial_t u(x,y,0) = 0$\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nFirst-order absorbing (Sommerfeld):\n\n\n\n\n\n$\\partial_t u + c\\,\\partial_n u = 0$\n\n\n\n\n\nThe wavefronts don't make much sense\n\n\n\n\n\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\n\n\n\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\n\n\n\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\n\n\n\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\n\n\n\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\n\n\n\n\n\n\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer\n\n\n\n\n\n\n\n\n\nActivation: sin\n\n\n\n\n\n\n\n\n\nTraining:\n\n\n\n\n\nAdam optimizer (20k epochs)\n\n\n\n\nLBFGS refinement\n\n\n\n\n\n\n\n\n\n\nCollocation points:\n\n\n\n\n\nUniform tensor-product grid in (x, y, t)\n\n\n\n\n\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nImplemented via additional loss terms using autograd\n\n\n\n\n\n\n\n\n\n\nVisualization:\n\n\n\n\n\nPINN evaluated on a dense grid and animated with Matplotlib\n\n\n\n\n\n\n\n\n\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.\n\n\n\n\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.","question_text_sha256":"a77c89e39603c1ba86e373383d3b58ec62151d770e496ee2cfff31c73cea7de3","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"a8ab0f1fda51c22475d8eca72a125fede5d7fe9181c75de7730fe06d0b3e4863","tags":["fluid-dynamics","computational-physics","machine-learning","physics-informed-neural-networks"],"thread_id":45326,"thread_url":"https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis","title":"Physics-Informed Neural Network for 2D Wave Equation Produces Non-Circular / Distorted Wavefronts"} {"accepted_answer_id":null,"answers":[{"answer_html":"\n\nmonothonic
\n
I'm sure you meant monotonic.
\n\n\nI am looking for a fast way to solve the problem
\n
Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:
\nA traditional LP would express the problem thus. Define the following decision vectors:
\nFind
\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$
\ngiven the following constraints:
\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$
\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$
\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.
\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\nHere we see that the solution does exactly what we tell it to:
\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:
\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):
\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.
\n","answer_id":45335,"answer_text":"monothonic\n\n\n\n\n\n\n\nI'm sure you meant monotonic.\n\n\n\n\n\n\n\nI am looking for a fast way to solve the problem\n\n\n\n\n\n\n\nAre you actually? I think if you were, you would use something off-the-shelf. \"Simple iterative\" and \"fast\" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:\n\n\n\n\n\nLinear, not quadratic\n\n\n\n\nNo manual iteration per se\n\n\n\n\nEnforce inter-reference monotonicity through simple linear constraints\n\n\n\n\nModel cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight\n\n\n\n\n\nA traditional LP would express the problem thus. Define the following decision vectors:\n\n\n\n\n\n$z \\in \\mathbb R^n$, the fit points\n\n\n\n\n$z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error\n\n\n\n\n$z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error\n\n\n\n\n$d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials\n\n\n\n\n$d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials\n\n\n\n\n\nFind\n\n\n\n\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$\n\n\n\n\ngiven the following constraints:\n\n\n\n\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$\n\n\n\n\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$\n\n\n\n\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\nHere we see that the solution does exactly what we tell it to:\n\n\n\n\n[image: example solution; source: https://i.sstatic.net/oTyX0oWA.png] (https://i.sstatic.net/oTyX0oWA.png)\n\n\n\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:\n\n\n\n\n[image: smoothing; source: https://i.sstatic.net/cW1t1avg.png] (https://i.sstatic.net/cW1t1avg.png)\n\n\n\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):\n\n\n\n\n[image: sparsity; source: https://i.sstatic.net/UmVF5qyE.png] (https://i.sstatic.net/UmVF5qyE.png)\n\n\n\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.","answer_url":"https://scicomp.stackexchange.com/a/45335","author_display_name":"Reinderien","author_profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-10T07:56:42+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45334,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T07:56:42+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"49224026-A98C-4DFC-B187-28324764F758","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T15:16:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"0462867C-327F-469E-957B-1FE451F4CE5C","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-01-10T20:00:35+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"302EF20B-4729-4185-A059-5377ED4B7555","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}],"score":3,"updated_at":"2026-01-10T20:00:35+00:00"},{"answer_html":"I managed to create a prototype solver based on ADMM in MATLAB:
\nfunction [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %<! Optimization variable\nvS = zeros(numInEq, 1); %<! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %<! Preious iteration buffer\nvMu = zeros(numInEq, 1); %<! Dual variable for inequality\nvNu = zeros(numEq, 1); %<! Dual variabe for equality\n\n% Factorize the KKT System\n% (Q + rho * A' * A + rho * E' * E) * z = r\nmK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\nsK = decomposition(mK, 'chol', 'CheckCondition', false);\n\nisConv = false;\nupdatedRho = false;\n\nfor ii = 1:numIter\n vS1(:) = vS; %<! Previous iteration\n\n % Solve the Linear System\n vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %<! Right hand vector\n vX = sK \\ vR;\n\n % Proximal / Projection Step\n % s = -A * z with s >= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.
\nI will add mathematical formulation and a memory optimized version using Julia.
On MATLAB with this naive code I could beat quadprog() by 30% with the same output:
I produced an ADMM based solver which I found very efficient.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.
\nThe equality constraints can be turned into matrix form and the problem becomes:
$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe equality constraints are introduced by the Augmented Lagrangian:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe stopping condition is when both residuals are below a threshold:
\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.
\nI also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.
\nI implemented all in Julia and compared to the ECOS / SCS solvers wrapped by Convex.jl.
Run Times:
\nBenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n\nBenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n\nBenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n\nThe ADMM method is an order of magnitude faster than the generic solvers.
\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.
The code is available on my StackExchange Code GitHub Repository (Look at the ComputationalScience\\Q45334 folder).
Another formulation take advantage of the equality constraint to make the problem formulation smaller.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:
\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$
\nThen the above can be formulated as:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.
\nThis formulation reduces the number of constraints to handle.
\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.
The Augmented Lagrangian (Scaled form) is given by:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe rest is similar to above with the needed adjustments for the residuals calculations.
\nThis implementation reduced another 40 [Micro Sec] of the run time.
\n","answer_id":45342,"answer_text":"Another formulation take advantage of the equality constraint to make the problem formulation smaller.\n\n\n\n\nThe problem is given by:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:\n\n\n\n\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$\n\n\n\n\nThen the above can be formulated as:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.\n\n\n\n\nThis formulation reduces the number of constraints to handle.\n\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.\n\n\n\n\nThe Augmented Lagrangian (Scaled form) is given by:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.\n\n\n\n\n\nThe rest is similar to above with the needed adjustments for the residuals calculations.\n\n\n\n\nThis implementation reduced another 40 [Micro Sec] of the run time.","answer_url":"https://scicomp.stackexchange.com/a/45342","author_display_name":"Royi","author_profile_url":"https://scicomp.stackexchange.com/users/7951/royi","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-17T12:18:23+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45334,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-17T12:18:23+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}],"score":1,"updated_at":"2026-01-17T12:18:23+00:00"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Royi","question_author_url":"https://scicomp.stackexchange.com/users/7951/royi","question_author_user_type":"registered","question_created_at":"2026-01-09T11:12:06+00:00","question_html":"Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.
\nI want to smooth the curve with the following properties:
\nI came up with the following model:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.
\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.
\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.
\n","question_license":"CC BY-SA 4.0","question_score":4,"question_text":"Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.\n\n\n\n\nI want to smooth the curve with the following properties:\n\n\n\n\n\nThe result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.\n\n\n\n\nFor a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.\n\n\n\n\nThe smoothed values between 2 reference points must be monotonic.\n\n\n\n\n\nI came up with the following model:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.\n\n\n\n\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.\n\n\n\n\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.","question_text_sha256":"f5065ce33631c2246929b0b2a0a1cd325bb9e26356f470d900663ac25117e5cf","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-09T11:12:06+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"47824E2B-27A9-4037-A643-E3F6522A8C95","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/47824E2B-27A9-4037-A643-E3F6522A8C95/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-09T11:26:36+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Royi","profile_url":"https://scicomp.stackexchange.com/users/7951/royi","user_type":"registered"},"created_at":"2026-01-10T07:58:10+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"2599F6AB-3F4E-455C-9665-0A36994C9F01","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/2599F6AB-3F4E-455C-9665-0A36994C9F01/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-01-10T17:02:45+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"DE676BCF-D21E-4A19-B947-DB9D0FD71DA6","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/DE676BCF-D21E-4A19-B947-DB9D0FD71DA6/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"c92e5b5485ea3a6a096a02902ba7a39021dd4152bd3019480c417cd072f32049","tags":["linear-algebra","optimization","constrained-optimization","convex-optimization","curve-fitting"],"thread_id":45334,"thread_url":"https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con","title":"Solving Regularized Least Squares with Linear Equality and Linear Inequality Constraints for Curve Smoothing"} {"accepted_answer_id":45345,"answers":[{"answer_html":"Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n
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_license":"CC BY-SA 4.0","question_score":1,"question_text":"If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.\n\n\n\n\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)
\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}
\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.
\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}
\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.
\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:
\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f"Numerical Result: {result:.10f}")\n# Result from WolframAlpha = 0.0187983\n\n","answer_id":45394,"answer_text":"The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983","answer_url":"https://scicomp.stackexchange.com/a/45394","author_display_name":"mle","author_profile_url":"https://scicomp.stackexchange.com/users/46538/mle","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-03-04T18:29:45+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45362,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"mle","profile_url":"https://scicomp.stackexchange.com/users/46538/mle","user_type":"registered"},"created_at":"2026-03-04T18:29:45+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"D8A9E199-F055-462B-8A0D-91FD9CE698F5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}],"score":2,"updated_at":"2026-03-04T18:29:45+00:00"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"vibe","question_author_url":"https://scicomp.stackexchange.com/users/28440/vibe","question_author_user_type":"registered","question_created_at":"2026-02-04T15:10:39+00:00","question_html":"I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.
\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.
\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.
\n","question_license":"CC BY-SA 4.0","question_score":3,"question_text":"I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.\n\n\n\n\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.\n\n\n\n\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.","question_text_sha256":"a088cd265cfdd15b5443339bfdda722888d07a2aa20562a7f808ef5388881c21","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"vibe","profile_url":"https://scicomp.stackexchange.com/users/28440/vibe","user_type":"registered"},"created_at":"2026-02-04T15:10:39+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9B775FCA-6689-4886-BE87-22C985705EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9B775FCA-6689-4886-BE87-22C985705EFF/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"e0a746be99090534e3a6679a55ab8c31f6158e49ac7c699dcdc52654d84b7636","tags":["integration","quadrature","polynomials"],"thread_id":45362,"thread_url":"https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials","title":"Quadrature rule for ratio of polynomials"} {"accepted_answer_id":null,"answers":[{"answer_html":"it seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature fields will look different than what you have shown in the picture. For clarity, can you check the following steps 1) Simulate a moving cavity lid at different Re numbers and compare against standard literature (like Ghia et.al (1982)). This freezes multiple things like verification of upwind schemes etc. 2) Recheck the enthalpy/heat equation whether the convection terms are taken care properly. For reference, typically over time, it should develop into convection cells. Please find my simulations for omega-psi attached in below picture
Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:
\n\n\n$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\\ldots$1e7.\nLeft and right walls are insulated. At the bottom wall $q_1= 1000$ and at\nthe upper wall $q_2=0.5*q_1$
\n
The temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.
\nThe isotherms are straight horizontal lines. It looks like the heat conduction of a block of copper when one of the wall has higher constant temperature
\nMay be a problem when defining the heat flux in solveTemperature function. Shouldnt the isotherms be waivier? The walls are nonpermeable (no liquid passes trouht them).
I tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n
Here is the piece of code for calculating the temperatures
\n // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n\nVortex solver
\n// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n\nStream function solver
\n// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n\nVelocity calculator
\n// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n\nSetting boundary conditions
\n // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n\nThis is the main code
\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\nconstexpr int Nx = 180;\nconstexpr int Ny = 60;\n\n int main()\n {\n const double Lx = 1.5, Ly = 1.0;\n const double hx = Lx / Nx, hy = Ly / Ny;\n const double Pr = 0.7, Ra = 1e8, dt = 0.001;\n const double eps = 1e-6, relax = 1.0;\n \n double t = 0.0, t_k = 10.0;\n \n static double psi[Nx + 1][Ny + 1]{}, psik[Nx + 1][Ny + 1]{}, omega[Nx + 1][Ny + 1]{};\n static double theta[Nx + 1][Ny + 1]{}, u[Nx + 1][Ny + 1]{}, v[Nx + 1][Ny + 1]{};\n static double alpha[(Nx > Ny ? Nx : Ny) + 1]{}, beta[(Nx > Ny ? Nx : Ny) + 1]{}; // if Nx > Ny then take Nx\n // otherwise take Ny\n \n while (t < t_k)\n {\n applyPsiBC(psi);\n solvePsi(psi, psik, omega, hx, hy, relax, eps);\n computeVelocity(psi, u, v, hx, hy);\n solveOmegaX(psi, theta, u, omega, alpha, beta, hx, dt, Pr, Ra);\n solveOmegaY(psi, v, omega, alpha, beta, hy, dt, Pr, Ra);\n solveTemperature(theta, u, v, alpha, beta, hx, hy, dt, Pr, Ra);\n \n t += dt;\n cout << t << endl;\n }\n \n // OUTPUT to files\n ofstream fpsi("psitest.txt"), fomega("omegatest.txt"), ftheta("thetatest.txt");\n \n for (int i = 0; i <= Nx; i++)\n {\n for (int j = 0; j <= Ny; j++)\n {\n double x = i * hx;\n double y = j * hy;\n fomega << x << " " << y << " " << omega[i][j] << "\\n";\n ftheta << x << " " << y << " " << theta[i][j] << "\\n";\n fpsi << x << " " << y << " " << psi[i][j] << "\\n";\n }\n }\n \n cout << "Calculation completed. Files: psitest.txt, omegatest.txt, thetatest.txt\\n";\n return 0;\n }\n\n","question_license":"CC BY-SA 4.0","question_score":0,"question_text":"Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:\n\n\n\n\n\n\n\n$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\\ldots$1e7.\nLeft and right walls are insulated. At the bottom wall $q_1= 1000$ and at\nthe upper wall $q_2=0.5*q_1$\n\n\n\n\n\n\n\nThe temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.\n\n\n\n\nThe isotherms are straight horizontal lines. It looks like the heat conduction of a block of copper when one of the wall has higher constant temperature\n\n\n\n\nMay be a problem when defining the heat flux in solveTemperature function. Shouldnt the isotherms be waivier? The walls are nonpermeable (no liquid passes trouht them).\n\n\n\n\nI tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n[image: for Ra = 1e3; source: https://i.sstatic.net/Z4fMSBrm.png] (https://i.sstatic.net/Z4fMSBrm.png)\n\n\n\n\nThis image is for Ra = 1e7\n[image: for Ra = 1e7; source: https://i.sstatic.net/4a2ls0zL.png] (https://i.sstatic.net/4a2ls0zL.png)\n\n\n\n\nHere is the piece of code for calculating the temperatures\n\n\n\n\n // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n\n\n\n\n\nVortex solver\n\n\n\n\n// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n\n\n\n\n\nStream function solver\n\n\n\n\n// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n\n\n\n\n\nVelocity calculator\n\n\n\n\n// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n\n\n\n\n\nSetting boundary conditions\n\n\n\n\n // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n\n\n\n\n\nThis is the main code\n\n\n\n\n#include Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n","answer_id":45388,"answer_text":"Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.","answer_url":"https://scicomp.stackexchange.com/a/45388","author_display_name":"wim","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Damien","question_author_url":"https://scicomp.stackexchange.com/users/761/damien","question_author_user_type":"registered","question_created_at":"2026-02-27T05:27:22+00:00","question_html":"TL;DR: I am looking for a function that computes the product of three floating point numbers:
\nfunction [x, y] = ThreeProduct(a, b, c)\n\nSuch that:
\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nBackground
\nOgita et al. (2005) introduced a method of computing a dot product based on "Error Free Transformation" primitives, such as TwoSum() (due to Knuth) and TwoProduct():
function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name "Error Free Transformation". That is, for TwoSum():
$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$
\nAnd for TwoProduct():
$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$
\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.
\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.
\nMy question is whether there is a known algorithm for the product of three floating point numbers ("ThreeProduct()"). That is, something where the following holds:
$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.
\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.
References:
\nOgita, T. et al., "Accurate Sum and Dot Product", SIAM Journal of Scientific Computing, 2005.
\nGraillat, S. "Accurate Floating Point Product and Exponentiation". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.
\n","question_license":"CC BY-SA 4.0","question_score":10,"question_text":"TL;DR: I am looking for a function that computes the product of three floating point numbers:\n\n\n\n\nfunction [x, y] = ThreeProduct(a, b, c)\n\n\n\n\n\nSuch that:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\n\n\n\nBackground\n\n\n\n\nOgita et al. (2005) introduced a method of computing a dot product based on \"Error Free Transformation\" primitives, such as TwoSum() (due to Knuth) and TwoProduct():\n\n\n\n\nfunction [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\n\n\n\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name \"Error Free Transformation\". That is, for TwoSum():\n\n\n\n\n$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$\n\n\n\n\nAnd for TwoProduct():\n\n\n\n\n$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$\n\n\n\n\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.\n\n\n\n\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.\n\n\n\n\nMy question is whether there is a known algorithm for the product of three floating point numbers (\"ThreeProduct()\"). That is, something where the following holds:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.\n\n\n\n\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.\n\n\n\n\n\n\n\nReferences:\n\n\n\n\nOgita, T. et al., \"Accurate Sum and Dot Product\", SIAM Journal of Scientific Computing, 2005.\n\n\n\n\nGraillat, S. \"Accurate Floating Point Product and Exponentiation (https://hal.science/hal-00164607v1)\". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.","question_text_sha256":"47aa81f3a07c0f87e4c0e08472fd61c87e118ae135bf884ef031760081cb5d48","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"b805214f9e8f725bbfabf92a7da7a182a36f614c8600935602ef8383f1bf9c67","tags":["floating-point"],"thread_id":45387,"thread_url":"https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers","title":"\"Error Free Transformation\" for the product of three floating point numbers"} {"accepted_answer_id":45440,"answers":[{"answer_html":"Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n","answer_id":45440,"answer_text":"Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.","answer_url":"https://scicomp.stackexchange.com/a/45440","author_display_name":"FilmCoder","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Makogan","question_author_url":"https://scicomp.stackexchange.com/users/38908/makogan","question_author_user_type":"registered","question_created_at":"2026-03-05T07:11:11+00:00","question_html":"I have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):
\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.
\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.
\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:
\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.
\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:
\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.
\nI am going to describe the logic in a high level:
\nThe actual code is this:
\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node<HpNode<f32, 10>>| {\n // Legendre coefficients.\n let cfs = node.data.coeffs(); \n let coeff_count = node.data.coeff_count();\n\n let pos = box_position + box_dims / 2.;\n let p = (cam_pos - pos) / box_dims;\n let v = ray / box_dims;\n\n let mut a = 0.;\n let mut b = 0.;\n let mut c = 0.;\n // Shift and scale the ray and pos to the local node.\n let ray = v;\n let ray_pos = p;\n for i in 0..coeff_count\n {\n // Coefficient + the degree of each legendre polynomial that was\n // tensor producted to make the basis element, i.e. one of\n // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n let (s, powers) = cfs[i as usize];\n // Compute coefficients for each dimension's Legendre polynomial\n // restricted to line.\n let mut poly = [1., 0., 0.];\n // accumulates as [t^0, t^1, t^2] coefficients.\n\n for axis in 0..3\n {\n // Get teh axial coefficients of this ray\n let (v, p) = match axis\n {\n 0 => (ray.x, ray_pos.x),\n 1 => (ray.y, ray_pos.y),\n 2 => (ray.z, ray_pos.z),\n _ => unreachable!(),\n };\n\n let power = powers[axis];\n\n // Legendre polynomial P_n(vt + p) coefficients in t.\n let leg_coeffs = match power\n {\n 0 => [1., 0., 0.],\n 1 => [p, v, 0.],\n // coefficients of the legendre polynomial of degree 2\n 2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n _ => unreachable!(),\n };\n\n // Multiply poly *= leg_coeffs.\n let temp = [\n poly[0] * leg_coeffs[0],\n poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n poly[0] * leg_coeffs[2]\n + poly[1] * leg_coeffs[1]\n + poly[2] * leg_coeffs[0],\n ];\n poly = temp;\n }\n\n a += s * poly[2];\n b += s * poly[1];\n c += s * poly[0];\n }\n\n let disc = b * b - 4. * a * c;\n if disc < 0.\n {\n return f32::INFINITY;\n }\n\n let sqrt_disc = disc.sqrt();\n let inv_2a = 1. / (2. * a);\n\n // Quadratic solutions.\n let x1 = (-b - sqrt_disc) * inv_2a;\n let x2 = (-b + sqrt_disc) * inv_2a;\n\n // Branchless valid selection: if x < 0, replace with infinity.\n let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n // Take minimum of valid solutions.\n let quad_t = valid_x1.min(valid_x2);\n\n // Handle linear case.\n let is_linear = a.abs() < 0.0001;\n let linear_t = -c / b;\n\n let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n if is_linear { linear_t } else { quad_t }\n };\n\nTo add further context, to generate the image with the additional spheres all you need to do is hard code the coefficients for a sphere:
\n let cfs = [\n (-0.1 + 1., [0, 0, 0]),\n (2./3., [2, 0, 0]),\n (2./3., [0, 2, 0]),\n (2./3., [0, 0, 2]),\n ];\n let coeff_count = 4;\n\nTo override the ones coming in. But the input coefficients cannot eb wrong because then the first image would not work.
\nThere's something wrong with the way I am computing my ray quadric collisions that is specific to the Legendre case. When I modify my logic to work with the sphere quadrics it works, as shown, so I must have messed something up with when computing the coefficients, but when I see the written code I fail to see what.
\n","question_license":"CC BY-SA 4.0","question_score":1,"question_text":"Background\n\n\n\n\nI have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/mLTa1ZsD.png] (https://i.sstatic.net/mLTa1ZsD.png)\n\n\n\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.\n\n\n\n\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.\n\n\n\n\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/K6cTCsGy.png] (https://i.sstatic.net/K6cTCsGy.png)\n\n\n\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.\n\n\n\n\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/4aqhk3tL.png] (https://i.sstatic.net/4aqhk3tL.png)\n\n\n\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.\n\n\n\n\nI am going to describe the logic in a high level:\n\n\n\n\n\nConsider that an $\\mathbb{R^3}$ legendre polynomial becomes a regular polynomial when restricted to the parametric line of a ray.\n\n\n\n\nGrab the coefficients of the quadric on the current node, knowing these are coefficients of a legendre polynomial, not monomials.\n\n\n\n\nFor each coefficient, add it to the corresponding constant, linear or quadric set of coefficents (for monomials).\n\n\n\n\nGrab the final, properly factored, coeffcients and solve a simple quadratic equation to figure out if and where the ray intersects the quadric on the current node.\n\n\n\n\n\nThe actual code is this:\n\n\n\n\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &NodeThis method appears to be simply Implicit Euler but with broken error control and without any actual ability to measure or ensure convergence to the correct solution.
\n","answer_id":45429,"answer_text":"This method appears to be simply Implicit Euler but with broken error control and without any actual ability to measure or ensure convergence to the correct solution.","answer_url":"https://scicomp.stackexchange.com/a/45429","author_display_name":"Oscar Smith","author_profile_url":"https://scicomp.stackexchange.com/users/33841/oscar-smith","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-04-05T17:38:55+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45422,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Oscar Smith","profile_url":"https://scicomp.stackexchange.com/users/33841/oscar-smith","user_type":"registered"},"created_at":"2026-04-05T17:38:55+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"FF7D6040-9711-407E-AD44-F933FEAD971C","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/FF7D6040-9711-407E-AD44-F933FEAD971C/view-source"}],"score":3,"updated_at":"2026-04-05T17:38:55+00:00"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"fethi gaouer","question_author_url":"https://scicomp.stackexchange.com/users/56574/fethi-gaouer","question_author_user_type":"registered","question_created_at":"2026-04-01T19:04:02+00:00","question_html":"We propose a numerical method for stiff ordinary differential equations (ODEs) based on a geometric transformation. The key ideas are:
\n1-Local geodesic approximation – On a short interval [t1,t2] the solution is approximated by a geodesic in a non‑Euclidean metric space. This geodesic depends on a single free parameter: the value y2=y(t2).
\n2-Calibration – For a given y2,the geodesic provides the midpoint
\n(tm,ym). We then compute the derivative from the geodesic:
\n ym′ = (ym−y1)/(tm-t1)\n\n
\nand evaluate the ODE at the midpoint:
\nfm =f(tm,ym).\nThe residual is\nR(y2 )=∣ ym′−fm ∣.
\n3-Adjustment – Because the interval is short,
\nR is nearly linear in y2 . A few secant iterations (or a simple manual search) suffice to make R negligible.
\n4-Systems – For a system of ODEs we select one component (e.g.y2) as the only free parameter. The geodesic gives (tm,ym). The other components at the midpoint, as well as their derivatives, are then deduced from the equations and the initial conditions. The residual is built on the remaining equations.
\n5-Long intervals – The total time interval is split into short segments where the curvature remains small. Each segment is treated independently using the same single‑parameter calibration.
\n6-Spectral pre‑processing – A coarse scan of the ODE’s right‑hand side estimates the local curvature and detects stiff regions or fast oscillations. This helps choose an optimal segmentation without trial and error.
\nWhy this method differs from classical ones:
\nNo implicit solver, no Jacobian.
\nStability is controlled by curvature, not by a CFL condition.
\nOnly one scalar parameter is adjusted per segment, regardless of the system size.
\nBenchmarks (performed in double precision, reference: Radau with tolerance 1e-12):
\nProthero–Robinson
\ny′ =−1000y+1000sint+cost with y(0.1)=sin(0.1)
\nResult: y(0.101)≈0.10083089255
\nError: 1e-6
Van der Pol,
\nε=1000, 8 segments from
\nResult: y(0.248583)≈0.2477211
\nError: 0.7% (finner subdivision gives 1e-7)
Lorenz system (single\nshort segment)
\nResult: error on all variables
\nError≈1e-7
Brusselator (single segment)
\nResult: residual on second equation
\nerror: <1e-7
Questions to the community:
\nAre there other stiff or multi‑scale benchmarks that you would recommend to test this approach further?
\nHas a similar curvature‑based step control been studied elsewhere?
\nWhat theoretical tools could help analyse the stability of such a method?
\n","question_license":"CC BY-SA 4.0","question_score":0,"question_text":"We propose a numerical method for stiff ordinary differential equations (ODEs) based on a geometric transformation. The key ideas are:\n\n\n\n\n1-Local geodesic approximation – On a short interval [t1,t2] the solution is approximated by a geodesic in a non‑Euclidean metric space. This geodesic depends on a single free parameter: the value y2=y(t2).\n\n\n\n\n2-Calibration – For a given y2,the geodesic provides the midpoint\n\n\n\n\n(tm,ym). We then compute the derivative from the geodesic:\n\n\n\n\n ym′ = (ym−y1)/(tm-t1)\n\n\n\n\n\n\n\n\n\n\nand evaluate the ODE at the midpoint:\n\n\n\n\nfm =f(tm,ym).\nThe residual is\nR(y2 )=∣ ym′−fm ∣.\n\n\n\n\n3-Adjustment – Because the interval is short,\n\n\n\n\nR is nearly linear in y2 . A few secant iterations (or a simple manual search) suffice to make R negligible.\n\n\n\n\n4-Systems – For a system of ODEs we select one component (e.g.y2) as the only free parameter. The geodesic gives (tm,ym). The other components at the midpoint, as well as their derivatives, are then deduced from the equations and the initial conditions. The residual is built on the remaining equations.\n\n\n\n\n5-Long intervals – The total time interval is split into short segments where the curvature remains small. Each segment is treated independently using the same single‑parameter calibration.\n\n\n\n\n6-Spectral pre‑processing – A coarse scan of the ODE’s right‑hand side estimates the local curvature and detects stiff regions or fast oscillations. This helps choose an optimal segmentation without trial and error.\n\n\n\n\nWhy this method differs from classical ones:\n\n\n\n\nNo implicit solver, no Jacobian.\n\n\n\n\nStability is controlled by curvature, not by a CFL condition.\n\n\n\n\nOnly one scalar parameter is adjusted per segment, regardless of the system size.\n\n\n\n\nBenchmarks (performed in double precision, reference: Radau with tolerance 1e-12):\n\n\n\n\nProthero–Robinson\n\n\n\n\ny′ =−1000y+1000sint+cost with y(0.1)=sin(0.1)\n\nResult: y(0.101)≈0.10083089255\n\nError: 1e-6\n\n\n\n\nVan der Pol,\n\n\n\n\nε=1000, 8 segments from\n\nResult: y(0.248583)≈0.2477211\n\nError: 0.7% (finner subdivision gives 1e-7)\n\n\n\n\nLorenz system (single\nshort segment)\n\n\n\n\nResult: error on all variables\n\nError≈1e-7\n\n\n\n\nBrusselator (single segment)\n\n\n\n\nResult: residual on second equation\n\nerror: <1e-7\n\n\n\n\nQuestions to the community:\n\n\n\n\nAre there other stiff or multi‑scale benchmarks that you would recommend to test this approach further?\n\n\n\n\nHas a similar curvature‑based step control been studied elsewhere?\n\n\n\n\nWhat theoretical tools could help analyse the stability of such a method?","question_text_sha256":"01fcd822ffeafd728d9fa09b1246b913cb26c8b18101f31e47dbfc2bb3011d11","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"fethi gaouer","profile_url":"https://scicomp.stackexchange.com/users/56574/fethi-gaouer","user_type":"registered"},"created_at":"2026-04-01T19:04:02+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"C2B7F1EE-558E-4597-AEC8-AB9AD9D0D121","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C2B7F1EE-558E-4597-AEC8-AB9AD9D0D121/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"fethi gaouer","profile_url":"https://scicomp.stackexchange.com/users/56574/fethi-gaouer","user_type":"registered"},"created_at":"2026-04-05T08:48:09+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"EB6BC856-36CA-4681-8A08-B0FD3EB4B53F","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EB6BC856-36CA-4681-8A08-B0FD3EB4B53F/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"validation","split_group":"2b8131042618eb6f11bfb1dd413dd9bd8c21a0bbe8106805752ba4add4a5558d","tags":["numerics","ode"],"thread_id":45422,"thread_url":"https://scicomp.stackexchange.com/questions/45422/stability-analysis-for-a-derivative-free-ode-solver-based-on-local-geodesic-inte","title":"Stability analysis for a derivative‑free ODE solver based on local geodesic interpolation"} {"accepted_answer_id":45426,"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_display_name":"Steven Roberts","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Santiago Iñiguez","question_author_url":"https://scicomp.stackexchange.com/users/56699/santiago-i%c3%b1iguez","question_author_user_type":"registered","question_created_at":"2026-04-03T20:45:39+00:00","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_license":"CC BY-SA 4.0","question_score":4,"question_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!","question_text_sha256":"ae6125a967dd29e93aabe8474b96a93e417c3302c7d173a7922632c512ee8ae3","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"validation","split_group":"bec9a221d6c6e58e534e29df9656d7f8af2bff3cc050de3ef04ce4a2fe2756b0","tags":["ode","error-estimation","runge-kutta"],"thread_id":45425,"thread_url":"https://scicomp.stackexchange.com/questions/45425/acceptance-criterion-in-adaptive-runge-kutta-methods-compare-error-directly-or","title":"Acceptance criterion in adaptive Runge–Kutta methods: compare error directly or via step factor ( s )?"} {"accepted_answer_id":null,"answers":[{"answer_html":"The gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.
\nThe given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).
\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.
\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.
\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.
\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.
\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).
\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:
\n| First polynomial | \nSecond polynomial | \n
|---|---|
| $1$ or $q^0$ | \n$q^{8+2x_{13}}$ | \n
| $q^2$ | \n$q^{10+2x_{13}}$ | \n
| $q^8$ | \n$q^{4+2x_{15}}$ | \n
| $q^{10}$ | \n$q^{6+2x_{15}}$ | \n
| $q^{12}$ | \n$q^{2x_{17}}$ | \n
| $q^{14}$ | \n$q^{2+2x_{17}}$ | \n
| $q^{16}$ | \n$q^{2x_{35}}$ | \n
| $q^{18}$ | \n$q^{2+2x_{35}}$ | \n
| $q^{20}$ | \n$q^{-4+2x_{37}}$ | \n
| $q^{22}$ | \n$q^{-2+2x_{37}}$ | \n
| $q^{24}$ | \n$q^{-8+2x_{57}}$ | \n
| $q^{26}$ | \n$q^{-6+2x_{57}}$ | \n
Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.
\nThis resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.
\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.
\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.
\n","answer_id":45473,"answer_text":"The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.","answer_url":"https://scicomp.stackexchange.com/a/45473","author_display_name":"hardmath","author_profile_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_display_name":"dharr","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"ateixeira82","question_author_url":"https://scicomp.stackexchange.com/users/56972/ateixeira82","question_author_user_type":"registered","question_created_at":"2026-06-21T10:31:05+00:00","question_html":"I am trying to solve a linear system of equations that comes from equating two Laurent polynomials. The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.
\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.
\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.
\nDo you guys know of any hint or solution on how to tackle these problems?
\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$
\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$
\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.
\n","question_license":"CC BY-SA 4.0","question_score":4,"question_text":"I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.\n\n\n\n\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.\n\n\n\n\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.\n\n\n\n\nDo you guys know of any hint or solution on how to tackle these problems?\n\n\n\n\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$\n\n\n\n\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$\n\n\n\n\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.","question_text_sha256":"0fb89bcc4a1afefc17c4b2cf70df21aa253faa7995ac8f11180cdd1d494f362a","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"validation","split_group":"4b9dd6fa598403182fcd4da24a74fb3134757a82420ec9b7e2b9d017f14310a6","tags":["python","linear-system","mathematica","combinatorics"],"thread_id":45472,"thread_url":"https://scicomp.stackexchange.com/questions/45472/solving-linear-system-of-equations-with-combinatorics","title":"Solving linear system of equations with combinatorics"} {"accepted_answer_id":45503,"answers":[{"answer_html":"From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:
\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_display_name":"Reinderien","author_profile_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_display_name":"MPIchael","author_profile_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_display_name":"Omar Osman Mahamoud","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Omar Osman Mahamoud","question_author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","question_author_user_type":"registered","question_created_at":"2026-07-12T12:23:53+00:00","question_html":"Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.
\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.
\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?
\nHere are the three implementations.
\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?
\n","question_license":"CC BY-SA 4.0","question_score":7,"question_text":"I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.\n\n\n\n\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.\n\n\n\n\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?\n\n\n\n\nHere are the three implementations.\n\n\n\n\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\n\n\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?","question_text_sha256":"032464ed4b18ef11eeb39ee289930ab8ed7e70d04a141a76ff59fae5993eabac","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"16adc6a4a6518de2e9c5729e6253032af44cedfe22df6f74e78fe00ee946123c","tags":["python","simulation","runge-kutta","physics"],"thread_id":45487,"thread_url":"https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t","title":"Why do my RK2 and Velocity Verlet implementations produce less accurate orbits than Euler?"} {"accepted_answer_id":45494,"answers":[{"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.
\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_license":"CC BY-SA 4.0","question_score":3,"question_text":"I am implementing a two-dimensional displacement-based finite element code in MATLAB.\n\n\n\n\nFor a Q4 element, stress and strain are calculated at four (2\\times2) Gauss integration points. In my current post-processing code, I use:\n\n\n\n\nfor i = 1:NoE\n\n nl = EL(i,1:NPE);\n\n for j = 1:NPE\n X(j,i) = ENL(nl(j),1) ...\n + scale*ENL(nl(j),4*PD+1);\n\n Y(j,i) = ENL(nl(j),2) ...\n + scale*ENL(nl(j),4*PD+2);\n end\n\n for j = 1:NPE\n val = stress(i,:,1,1);\n stress_xx(j,i) = val(1,j);\n end\nend\n\n\n\n\n\nI then use the nodal-coordinate arrays X and Y, together with stress_xx, to produce a colored element plot.\n\n\n\n\nI now understand that this does not actually calculate stress at the nodes. It simply associates stress at Gauss point (j) with the coordinates of local node (j). The fact that Q4 has four nodes and four Gauss points made this one-to-one assignment appear reasonable, although the Gauss points and nodes have different coordinates.\n\n\n\n\nMy supervisor also pointed out that treating stress as a unique nodal quantity is generally incorrect in a standard displacement-based FEM. Displacement is continuous across element boundaries, but its gradients, strains, and stresses are element-wise quantities and can jump across adjacent elements.\n\n\n\n\nI am now implementing a Q8 element using (3\\times3) Gaussian integration. Therefore, every element has eight nodes but nine Gauss-point stress values. A direct assignment is no longer even numerically possible because there is no Q8 node corresponding to the center Gauss point.\n\n\n\n\nMy questions are:\n\n\n\n\n\nWhat is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?\n\n\n\n\nShould I map the Gauss-point coordinates from the parent element to the physical element and plot the values directly?\n\n\n\n\nHow can I construct an element-wise contour plot that preserves possible stress jumps across element boundaries?\n\n\n\n\nIs Gauss-point-to-node extrapolation appropriate only for a recovered or smoothed visualization field, rather than for representing the original finite element stress field?\n\n\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?\n\n\n\n\n\nI want to avoid discarding the ninth Gauss-point value, arbitrarily attaching Gauss-point values to nodes, or presenting an averaged nodal stress field as though it were the original FEM stress solution.","question_text_sha256":"8edbdfc35030f9afdfdac59b8023b021e80633de026159f8e9cf0be5cbdc0fcc","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Rasa R. Behboud","profile_url":"https://scicomp.stackexchange.com/users/57047/rasa-r-behboud","user_type":"registered"},"created_at":"2026-07-14T08:51:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"0DE2EEFB-055C-46F0-8FDE-C3A7A6127CDE","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0DE2EEFB-055C-46F0-8FDE-C3A7A6127CDE/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"test","split_group":"34f85227cf941851c7361b630d29fbce8fb2b19e4cb26845f618a5675590b611","tags":["finite-element"],"thread_id":45493,"thread_url":"https://scicomp.stackexchange.com/questions/45493/how-should-gauss-point-stresses-be-plotted-for-q8-serendipity-finite-elements-wi","title":"How should Gauss-point stresses be plotted for Q8 Serendipity finite elements without treating them as nodal values?"} {"accepted_answer_id":45500,"answers":[{"answer_html":"Your loop structure to accumulate the acceleration is wrong:
\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n\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_display_name":"Reinderien","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Omar Osman Mahamoud","question_author_url":"https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud","question_author_user_type":"registered","question_created_at":"2026-07-26T12:32:03+00:00","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_license":"CC BY-SA 4.0","question_score":2,"question_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.","question_text_sha256":"06eb036ebb10f2f927acd89baab48fff1aee56969f6d6e854dad48e064ed9927","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"4ff146b35f5f566e3289f2cbe041a3613960e11ecb2818a9ef019f2fa71ed2c8","tags":["python","computational-physics","simulation","numerical-integration","physics"],"thread_id":45499,"thread_url":"https://scicomp.stackexchange.com/questions/45499/n-body-gravitation","title":"N-body gravitation"} {"accepted_answer_id":45511,"answers":[{"answer_html":"You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods. Accordingly, I have implemented the scheme as follows::
\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.
\n","question_license":"CC BY-SA 4.0","question_score":2,"question_text":"I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods (https://open.umich.edu/sites/default/files/downloads/2012-parallel-spectral-numerical-methods.pdf). Accordingly, I have implemented the scheme as follows::\n\n\n\n\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\n\n\n\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.","question_text_sha256":"ce7be271fe35a71fa3b012551346918365fbabfb0dd7f76d0efdbb214153162f","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Manav Jalan","profile_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan","user_type":"registered"},"created_at":"2026-08-05T11:30:29+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"89E117A0-D17A-486B-9AB6-3BFCFC57C353","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/89E117A0-D17A-486B-9AB6-3BFCFC57C353/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-06T12:01:54+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"669E53D8-1766-46EB-8CA1-42CE9017157D","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/669E53D8-1766-46EB-8CA1-42CE9017157D/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"de1de4d05a1e70631948abf57b2a712abcdef0fe16bfaaa31109c47b47434158","tags":["computational-physics","spectral-method","pseudospectral"],"thread_id":45510,"thread_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio","title":"Allen Cahn Psuedospectral solver blowup even after reaching steady state solution"} {"accepted_answer_id":45524,"answers":[{"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\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_license":"CC BY-SA 4.0","question_score":1,"question_text":"I am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:\n\n\n\n\nHow can the Referenced Regular Heptagon inscribed within a Unit Circle, with its center coinciding, be drawn using PostScript Programming Language? (https://scicomp.stackexchange.com/questions/45518/how-can-the-referenced-regular-heptagon-inscribed-within-a-unit-circle-with-its)\n\n\n\n\n[image: Image of the Regular Heptagon; source: https://i.sstatic.net/z1YPOvX5.png] (https://i.sstatic.net/z1YPOvX5.png)\n\n\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:\n\n\n\n\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\n\n\n\n\nThe Question: Where Are my C calculations Going Wrong?\n\n\n\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?\n\n\n\n\nUpdate: Answer Calculated, but Angles $\\angle BCF$ and\n$\\angle BAF$ are equal, but not $90^{\\circ}$\n\n\n\n\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: \"Figure. Regular Heptagon Image taken from a Math Stack Exchange Question\", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.\n\n\n\n\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:\n\n\n\n\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\n\n\n\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.\n\n\n\n\n\n\n\nFrom the question \"What could be this unknown angle in this regular\nheptagon?\" (https://math.stackexchange.com/questions/5146710/what-could-be-this-unknown-angle-in-this-regular-heptagon/5146818#5146818)\n\n\n\n\nThere is the image drawn of a Regular Heptagon:\n\n\n\n\n\n\n\n[image: Regular Heptagon Image taken from a Math Stack Exchange Question; source: https://i.sstatic.net/JpG0VRI2.jpg] (https://i.sstatic.net/JpG0VRI2.jpg) \nFigure. Regular Heptagon Image taken from a\nMath Stack Exchange Question\n\n\n\n\n\n\n\n\n\n\n\nAppendix: C Programming Language Source Code to Calculate Angles for a Regular Heptagon\n\n\n\n\nOn the site: https://www.onlinegdb.com/online_c_compiler (https://www.onlinegdb.com/online_c_compiler)\n\n\n\n\n#include I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.
\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.
\nimport sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\nHere are a few finite element specific resources:
\nFor how to analyze the general stability of numerical discretizations:
\nI 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_license":"CC BY-SA 4.0","question_score":4,"question_text":"I need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled \"Finite Element Method\", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.\n\n\n\n\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?\n\n\n\n\n\n\n\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided\n\n\n\n\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = \"Lagrange\" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure(\"dx\", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = \"preonly\" # Preconditioning Matrix Option\nsolver_type = \"lu\" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix=\"first_order_ODE\", bcs = [bc], petsc_options={\"ksp_type\": ksp_type, \"pc_type\": solver_type})\nu_sol = problem.solve()\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/8M1U5hQT.png] (https://i.sstatic.net/8M1U5hQT.png)\n\n\n\n\nwe can see the solution is infinity at all node values of the functionspace.","question_text_sha256":"f01e34abbf94564d2f01c4ba463b24b45518ab763b5583798a4ad64036b8f6a9","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Researcher R","profile_url":"https://scicomp.stackexchange.com/users/53321/researcher-r","user_type":"registered"},"created_at":"2026-08-30T03:46:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"8A694B8D-C740-489D-AB57-AFCBA245C49D","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/8A694B8D-C740-489D-AB57-AFCBA245C49D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Researcher R","profile_url":"https://scicomp.stackexchange.com/users/53321/researcher-r","user_type":"registered"},"created_at":"2026-08-30T23:41:50+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-31T23:54:34+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8","revision_number":null,"revision_type":"vote_based","revision_url":"https://scicomp.stackexchange.com/revisions/74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"2018b4d0fd67f9b0e75e983194c9766caaff0a6d774ca518687569c797590332","tags":["finite-element","reference-request","least-squares","galerkin","weak-solution"],"thread_id":45530,"thread_url":"https://scicomp.stackexchange.com/questions/45530/are-there-any-resources-which-cover-finding-stable-weak-forms-to-1st-order-diffe","title":"Are there any resources which cover finding stable weak forms to 1st-order differential equations"} {"accepted_answer_id":null,"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_display_name":"ConvexHull","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"Manav Jalan","question_author_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan","question_author_user_type":"registered","question_created_at":"2026-09-02T16:06:42+00:00","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 key insight (also reflected in this comment) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).
\nSince you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,
\nFor small bounding box count, it's very frequent that an axis intersection is selected:
\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:
\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n """\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n """\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n","answer_id":45537,"answer_text":"The key insight (also reflected in this comment (https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533)) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).\n\n\n\n\nSince you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,\n\n\n\n\n\nUnion the set of all box-box intersections and all box-axis intersections\n\n\n\n\nFrom that set, exclude all points that are occluded by a box\n\n\n\n\nDo a tensor contraction to get the squared norm for the remaining intersections\n\n\n\n\nChoose the smallest one.\n\n\n\n\n\nFor small bounding box count, it's very frequent that an axis intersection is selected:\n\n\n\n\n[image: small problem; source: https://i.sstatic.net/rLLW3nkZ.png] (https://i.sstatic.net/rLLW3nkZ.png)\n\n\n\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:\n\n\n\n\n[image: 90 boxes; source: https://i.sstatic.net/B0XWwMzu.png] (https://i.sstatic.net/B0XWwMzu.png)\n\n\n\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45537","author_display_name":"Reinderien","author_profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-07T22:20:58+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45533,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:20:58+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EA034CBB-245E-47BE-9F83-73186A65FD54","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:53:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"13520681-83F3-4234-8A59-CE187F0BEA29","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}],"score":2,"updated_at":"2026-09-07T22:53:19+00:00"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"ffbh","question_author_url":"https://scicomp.stackexchange.com/users/57252/ffbh","question_author_user_type":"registered","question_created_at":"2026-09-03T03:48:42+00:00","question_html":"I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.
\nIs there a known algorithm for this problem?
\nThanks.
\n","question_license":"CC BY-SA 4.0","question_score":3,"question_text":"I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.\n\n\n\n\n\nIf P is not inside any AABB, I don't need to do anything.\n\n\n\n\nIf P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs\n\n\n\n\nA point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.\n\n\n\n\n\nIs there a known algorithm for this problem?\n\n\n\n\nThanks.","question_text_sha256":"cb2b8d5f9df7ee5c94fd6426b266678288262c856d2ffa0cbe91f62daf521e3d","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"ffbh","profile_url":"https://scicomp.stackexchange.com/users/57252/ffbh","user_type":"registered"},"created_at":"2026-09-03T03:48:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"4165EEB0-A429-43DE-A4E0-E9FB5F902B12","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4165EEB0-A429-43DE-A4E0-E9FB5F902B12/view-source"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"train","split_group":"d6a989359c239e0e0a9a762ab56aa27f8f6f0faa170a424f5be1547730b37232","tags":["algorithms","computational-geometry","geometry"],"thread_id":45533,"thread_url":"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them","title":"Find the closest point outside overlapping AABBs from a point inside them"} {"accepted_answer_id":null,"answers":[{"answer_html":"The runtime analysis you described for the two algorithms, brute force and your filtered one, looks right. I cannot say whether your algorithm exists in the literature or if there are other better ones out there in the literature of your field.
\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_display_name":"spektr","author_profile_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"}],"medical_sensitive":false,"patient_specific":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:44.584971+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json","raw_sha256":"27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_author":"BmyGuest","question_author_url":"https://scicomp.stackexchange.com/users/28168/bmyguest","question_author_user_type":"registered","question_created_at":"2026-09-10T19:47:17+00:00","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_license":"CC BY-SA 4.0","question_score":2,"question_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","question_text_sha256":"2a4bfe9828f53a82eea32c830758ec3ca793915632739d160b047ae7dc42cf5a","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"}],"sensitivity_method":"English keyword/first-person heuristic; not clinical review","source_platform":"Stack Exchange","source_site":"scicomp","split":"test","split_group":"2f97ff1a6a73eae5332a6ad03c4362f22746b954669647ac24fd8ec222c4c570","tags":["algorithms","parallel-computing","image-processing"],"thread_id":45538,"thread_url":"https://scicomp.stackexchange.com/questions/45538/does-this-local-maxima-search-algorithm-have-a-name-or-is-it-new","title":"Does this local-maxima search algorithm have a name or is it 'new'?"}