Why initialize values with 'quiet_NaN' in ros2_control?

In controller and hardware interface implementations, variables are often initialized with quiet_NaN. For example, in Unit 4 of the “ROS2_Control Framework Course”, the command and state values are initialized in the on_init() method as follows:

  hw_states_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
  hw_commands_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());

Something similar is done in the on_init method in Unit 5, and the on_activate method in unit 7.

Why use quiet_NaN?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Hello @jeroendm ,

Using quiet_NaN ensures clarity, debugging ease, and safety by marking values as uninitialized rather than assigning potentially misleading default values like 0.0.

Some more specific examples:

  • quiet_NaN (Not-a-Number) is used to clearly indicate that the variable has not been assigned a valid value yet.This helps differentiate between an intentionally set value and an uninitialized or invalid state.
  • If a function or component mistakenly tries to use an uninitialized value, it may propagate NaN, making it easier to catch issues during debugging. Also, some error-checking mechanisms in ROS 2 or other libraries explicitly handle NaN values to prevent undefined behavior.

Hope this helps,

1 Like