Implement the R-Learning algorithm, a model-free reinforcement learning method designed for continuing (non-episodic) tasks under the average reward criterion.
Unlike discounted reward methods, R-Learning directly estimates the average reward per time step and learns differential action-values that represent the relative advantage of taking an action compared to the long-run average.
Write a function r_learning that processes a sequence of experience transitions and returns the learned Q-values and average reward estimate.
The function takes:
transitions: a list of (state, action, reward, next_state) tuples representing sequential experiencen_states: number of states (integers 0 to n_states-1)n_actions: number of actions (integers 0 to n_actions-1)alpha: learning rate for Q-value updatesbeta: learning rate for average reward updatesinitial_rho: initial estimate of the average reward (default 0.0)Initialize all Q-values to 0.0 and the average reward estimate rho to initial_rho.
For each transition (s, a, r, s'), compute the differential TD error: delta = r - rho + max_a' Q(s', a') - Q(s, a)
Update Q(s, a) using alpha and delta. Then check whether the action a is the greedy action for state s according to the updated Q-values (ties broken by selecting the lowest action index). If it is the greedy action, update rho using beta and delta.
Return a tuple of (Q, rho) where Q is a nested list of shape (n_states, n_actions) with values rounded to 4 decimal places, and rho is a float rounded to 4 decimal places.