Skip to content
RoboticsNovember 18, 2026Intermediate

Forward and Inverse Kinematics for a 6-DOF Arm in Python

RTJ Editor
RoboTechJournal Contributor
Contents1. Describe the arm using standard DH parameters

Forward kinematics turns six joint angles into a tool pose. Inverse kinematics works in the opposite direction: given a target position and orientation, find joint angles that produce them. The NumPy example below implements both for a six-revolute-joint arm and includes a check that shows where a simple numerical solver succeeds and where it fails.

1. Describe the arm using standard DH parameters

Each row of DH holds four Denavit–Hartenberg parameters: link length a, link twist alpha, offset d and a joint zero-angle offset. Dimensions are in metres and angles are in radians. For revolute joint i, the transform uses theta = q[i] + offset. The code uses the standard convention; a modified-DH table is not interchangeable with it. The dimensions describe an example only, not a particular arm kit.

2. Multiply transforms and build the Jacobian

Each row produces a homogeneous 4 × 4 transform. Multiplying from base to tip gives a rotation in the upper-left 3 × 3 block and a translation in the last column. The frames function retains the intermediate transforms so that jacobian can express every joint’s motion in the base frame.

For a revolute joint with axis z through point p, the Jacobian column’s linear part is z × (p_tool − p) and its angular part is z. Stacking those columns maps joint rates to tool linear and angular velocity.

3. Solve inverse kinematics with damping

At each iteration, subtract the current tool position from the desired position and combine that with an axis-angle orientation residual in the base frame. Compute the joint update as Δq = Jᵀ (JJᵀ + λ²I)⁻¹ e. The implementation uses NumPy’s linear-system solver rather than forming the inverse matrix explicitly. The fixed damping is 0.05 and the update norm is capped at 0.3 rad. The example clips each joint to ±π; these are numerical bounds, not hardware safety limits.

The Modern Robotics authors’ numerical inverse kinematics lesson explains iterative Jacobian-based IK and why the starting configuration matters. In this example, the translational and rotational residuals are combined without task-specific weighting, so damping and convergence results are specific to this model and scaling.

4. Run the complete example

Use a Python environment where you can install NumPy. Save the listing as arm_kinematics.py, then run:

bash
python3 --versionpython3 -m pip install 'numpy==1.26.4'python3 -c 'import numpy as np; print(np.__version__)'python3 arm_kinematics.py
python
"""Forward and inverse kinematics for a 6-DOF arm using standard DH parameters. Run:  python3 arm_kinematics.py"""import numpy as np # Example hobby-sized arm. Each row: (a, alpha, d, theta_offset), metres and radians.DH = np.array([    [0.00,  np.pi / 2, 0.100, 0.0],    [0.20,  0.0,       0.000, 0.0],    [0.18,  0.0,       0.000, 0.0],    [0.00,  np.pi / 2, 0.050, 0.0],    [0.00, -np.pi / 2, 0.060, 0.0],    [0.00,  0.0,       0.050, 0.0],])Q_MIN = -np.pi * np.ones(6)Q_MAX = np.pi * np.ones(6)  def dh_matrix(a, alpha, d, theta):    ct, st = np.cos(theta), np.sin(theta)    ca, sa = np.cos(alpha), np.sin(alpha)    return np.array([        [ct, -st * ca,  st * sa, a * ct],        [st,  ct * ca, -ct * sa, a * st],        [0.0,      sa,       ca,      d],        [0.0,     0.0,      0.0,    1.0],    ])  def frames(q):    """Return the base-to-joint transforms T_0, T_1 ... T_6 (T_0 is identity)."""    T = np.eye(4)    out = [T.copy()]    for (a, alpha, d, off), qi in zip(DH, q):        T = T @ dh_matrix(a, alpha, d, qi + off)        out.append(T.copy())    return out  def fk(q):    return frames(q)[-1]  def jacobian(q):    """6x6 geometric Jacobian: top 3 rows linear velocity, bottom 3 angular."""    Ts = frames(q)    p_end = Ts[-1][:3, 3]    J = np.zeros((6, 6))    for i in range(6):        z = Ts[i][:3, 2]          # axis of joint i+1        p = Ts[i][:3, 3]        J[:3, i] = np.cross(z, p_end - p)        J[3:, i] = z    return J  def rotation_error(R_target, R_current):    """Axis-angle vector that rotates the current orientation onto the target."""    R = R_target @ R_current.T    cos_angle = np.clip((np.trace(R) - 1.0) / 2.0, -1.0, 1.0)    angle = np.arccos(cos_angle)    if angle < 1e-9:        return np.zeros(3)    axis = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]])    return angle * axis / (2.0 * np.sin(angle))  def pose_error(T_target, T_current):    return np.concatenate([        T_target[:3, 3] - T_current[:3, 3],        rotation_error(T_target[:3, :3], T_current[:3, :3]),    ])  def ik(T_target, q0, damping=0.05, max_iters=300, tol_pos=1e-4, tol_rot=1e-3,       max_step=0.3):    """Damped least squares inverse kinematics. Returns (q, converged, iterations)."""    q = np.array(q0, dtype=float)    for it in range(max_iters):        e = pose_error(T_target, fk(q))        if np.linalg.norm(e[:3]) < tol_pos and np.linalg.norm(e[3:]) < tol_rot:            return q, True, it        J = jacobian(q)        dq = J.T @ np.linalg.solve(J @ J.T + damping ** 2 * np.eye(6), e)        step = np.linalg.norm(dq)        if step > max_step:            dq *= max_step / step        q = np.clip(q + dq, Q_MIN, Q_MAX)    return q, False, max_iters  if __name__ == "__main__":    rng = np.random.default_rng(0)     # 1) Round trip: pick joints, compute pose, solve IK from a random start    n, ok, iters, pos_err, rot_err = 200, 0, [], [], []    for _ in range(n):        q_true = rng.uniform(-2.5, 2.5, 6)        target = fk(q_true)        q0 = rng.uniform(-2.5, 2.5, 6)        q, converged, it = ik(target, q0)        e = pose_error(target, fk(q))        if converged:            ok += 1            iters.append(it)        pos_err.append(np.linalg.norm(e[:3]))        rot_err.append(np.linalg.norm(e[3:]))    print(f"single start, {n} random reachable poses: converged {ok}/{n}")    print(f"  median iterations when converged: {np.median(iters):.0f}")    print(f"  median final error: {np.median(pos_err)*1000:.3f} mm, {np.degrees(np.median(rot_err)):.3f} deg")     # 2) Same test with up to 5 random restarts    ok2 = 0    rng = np.random.default_rng(0)    for _ in range(n):        q_true = rng.uniform(-2.5, 2.5, 6)        target = fk(q_true)        for _try in range(5):            q0 = rng.uniform(-2.5, 2.5, 6)            _, converged, _ = ik(target, q0)            if converged:                ok2 += 1                break    print(f"up to 5 random restarts: converged {ok2}/{n}")     # 3) Singularity: straighten the elbow (q3 -> 0) and ask for a 1 cm move outward    base = np.array([0.3, 0.9, 1.4, 0.2, 0.7, 0.1])    print("elbow q3 | smallest sigma | condition | plain pinv step | damped step")    for q3 in (1.4, 0.3, 0.05, 0.01):        q = base.copy()        q[2] = q3        J = jacobian(q)        s = np.linalg.svd(J, compute_uv=False)        Ts = frames(q)        radial = Ts[-1][:3, 3] - Ts[1][:3, 3]        task = np.zeros(6)        task[:3] = 0.01 * radial / np.linalg.norm(radial)        dq_pinv = np.linalg.pinv(J, rcond=1e-12) @ task        dq_dls = J.T @ np.linalg.solve(J @ J.T + 0.05 ** 2 * np.eye(6), task)        print(f"{q3:8.2f} | {s[-1]:13.4f} | {s[0] / s[-1]:9.1f} | "              f"{np.linalg.norm(dq_pinv):10.3f} rad | {np.linalg.norm(dq_dls):6.3f} rad")

5. Read the round-trip results correctly

The script generates reachable targets with its own forward model and then solves for each target from a random initial guess. Success requires position error below 0.1 mm and orientation error below 0.001 rad within the iteration budget. It does not require recovering the original joint angles: more than one configuration may produce the same pose.

  • One random start: 80 of 200 targets converged. The median for converged runs was 24 iterations.
  • Median final error across all single-start runs: 13.896 mm and 1.357°, including runs that did not converge.
  • Up to five random starts per target: 166 of 200 converged in the second run. It resets the seed, but draws targets and guesses from one shared generator, so it does not reuse the identical target set. These counts are not a paired comparison or a general success rate.

6. Compare joint steps near a singularity

The diagnostic varies the elbow angle while keeping the other joints fixed, then requests a 1 cm outward translation. It reports the norm of a single unconstrained update before any step cap or joint clipping. The comparison uses NumPy’s SVD-based pseudoinverse and the same damped update as the solver.

text
Elbow q3 | Min singular value | Condition | Pseudoinverse | Damped   1.40  |             0.0215 |      89.9 |     0.161 rad | 0.079 rad   0.30  |             0.0228 |      85.1 |     0.404 rad | 0.075 rad   0.05  |             0.0038 |     508.0 |     2.409 rad | 0.029 rad   0.01  |             0.0008 |    2538.8 |    12.046 rad | 0.026 rad

At the closest sampled pose, a small singular value makes the undamped solver ask for a much larger joint step. Damping keeps the update smaller but does not make a singular direction achievable; some requested tool motion can remain uncorrected.

Limits to check before using your own arm

  • Half-turn orientation error: the example extracts the axis by dividing by sin(angle), which approaches zero near 180°. It is ill-conditioned there and does not implement a robust half-turn branch. Do not treat it as a general rotation-error routine.
  • Wrong zero pose: check standard versus modified DH convention, each joint’s zero offset, and the tool frame. If the gripper changes the tool centre, model that offset explicitly.
  • Stalling or a different solution: a seed can lead to a different branch or stall at a limit. A failed solve does not prove that a target is unreachable, and a converged pose does not prove there is a collision-free path to it.

For a physical build, use the geometry and limits for the actual arm. The robot arm kit guide covers hardware options, while the robot gripper design comparison explains end-effector trade-offs this solver does not model.

More from Robotics

Robot Gripper Design: Servo vs Pneumatic vs Vacuum/Suction
RoboticsJul 8, 2026Intermediate

Robot Gripper Design: Servo vs Pneumatic vs Vacuum/Suction

Choose a robot gripper design by object surface, required holding force, cycle time and available utilities. Compare servo, pneumatic and vacuum/suction systems, including mobile-robot and safety constraints.

Top 7 Robot Arm Kits for Hobbyists in 2026
RoboticsApr 8, 2026Foundational

Top 7 Robot Arm Kits for Hobbyists in 2026

A skill-level breakdown of the best robot arm kits in 2026, from beginner acrylic kits to ROS 2-ready 6-DOF arms.