Skip to content

HandyModRTransform.deriv3 is wrong for m > 2 #347

Closed

Description

@SajalDevX

HandyModRTransform.deriv3 returns the wrong third derivative whenever m >= 3. For m = 1 and m = 2 it is correct, which is the only range the current tests use.

The first term in the numerator is written as 2 * two_m * (m - 2) * (m - 1) * (1 - two_m + size_r) ** 2, but differentiating r(x) three times gives two_m**2 there, not 2 * two_m. The term is multiplied by (m - 1)(m - 2), so the mistake only shows up from m = 3 on.

Because deriv3 feeds deriv3_inverse and the transformed ODE solvers, those are off too. A small example with solve_ode_ivp on y''' = 6, y(-0.5) = y'(-0.5) = y''(-0.5) = 0, whose exact solution is (x + 0.5)**3:

import numpy as np
from grid.ode import solve_ode_ivp
from grid.rtransform import HandyModRTransform

xs = np.array([0.0, 0.25, 0.5])
for m in [2, 3, 4]:
    tf = HandyModRTransform(0.1, 10.0, m)
    sol = solve_ode_ivp((-0.5, 0.5), lambda x: 6 * np.ones_like(x), [0, 0, 0, 1],
                        [0.0, 0.0, 0.0], transform=tf, rtol=1e-10, atol=1e-10)
    print(m, sol(xs)[0], (xs + 0.5) ** 3)

On master:

2 [0.125    0.421875 1.      ] [0.125    0.421875 1.      ]
3 [0.12976934 0.45091849 1.10383533] [0.125    0.421875 1.      ]
4 [0.14209262 0.53001896 1.41016422] [0.125    0.421875 1.      ]

Comparing deriv3 directly against the symbolic third derivative (sympy) of transform for rmin=0.1, rmax=10, the relative error is ~1e-15 for m = 1, 2 and 0.75, 0.87, 0.94 for m = 3, 4, 5.

The fix is a one-line change (2 * two_m to two_m**2) plus a test that checks deriv3 against finite differences for m = 1 to 5. I have a patch ready if that's fine.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions