ARotting's picture
Publish Conservative pendulum state-derivative field
01e81ce verified
Raw
History Blame Contribute Delete
735 Bytes
from __future__ import annotations
import numpy as np
def true_derivative(states: np.ndarray) -> np.ndarray:
angle = states[..., 0]
momentum = states[..., 1]
return np.stack([momentum, -np.sin(angle)], axis=-1).astype(np.float32)
def true_energy(states: np.ndarray) -> np.ndarray:
angle = states[..., 0]
momentum = states[..., 1]
return 0.5 * momentum**2 + 1 - np.cos(angle)
def generate_states(samples: int, seed: int) -> tuple[np.ndarray, np.ndarray]:
rng = np.random.default_rng(seed)
states = np.column_stack(
[
rng.uniform(-np.pi, np.pi, samples),
rng.uniform(-2.0, 2.0, samples),
]
).astype(np.float32)
return states, true_derivative(states)