Skip to content
LumenaryAcademy
Motion 75 min

Inverse kinematics

Working backwards from where the hand must be to how every joint must turn — and why the answer may be none, two, eight or infinitely many.

Code tested · 6AI-draftedAwaiting review by a roboticist

Your guides: Chloe · The Builder, Margaret · The Experimenter, Gideon · The Safety Engineer

MotivationH

From where the hand must be to how the joints must turn

A camera above a pharmacy counter in Nairobi finds a box of tablets and reports its pose in the robot's base frame: centre at (0.42,0.18,0.05)(0.42, 0.18, 0.05) m, lying flat, rotated 30°30° about the vertical. A welding cell in Ulsan is told that the torch tip must follow a seam at a fixed angle to the steel. A surgeon in São Paulo moves a hand controller, and the instrument tip inside the patient must move the same way, scaled down. In every case the task is stated where the work happens, in task space: a position and an orientation of the tool. But a robot arm cannot be told "go to (0.42,0.18,0.05)(0.42, 0.18, 0.05)". It can only be told how far to turn each of its motors.

Forward kinematics answered the easy direction: given the joint angles qq, multiply the link transforms together to get the tool pose 0TE(q){}^{0}T_{E}(q). Inverse kinematics (IK) asks the opposite question: given a desired pose 0TE∗{}^{0}T_{E}^{*}, which joint angles produce it? Every pick, place, weld, and every step of a walking robot's foot needs this answer, often hundreds of times a second.

The surprise is how different the two directions are. Forward kinematics always has exactly one answer, computed in a few dozen multiplications. Inverse kinematics may have no answer (the box is out of reach), several (reach it with the elbow up or the elbow down), or infinitely many (your own arm can touch a cup and still swing its elbow). This lesson shows why, solves the classic arm exactly, builds the numerical solver that general-purpose software uses, and ends with how industry and research labs actually do it.

IntuitionH

Running forward kinematics backwards

Take the simplest arm that is not trivial: two links in a plane, of lengths l1=0.5l_1 = 0.5 m and l2=0.4l_2 = 0.4 m, joined by revolute joints at the shoulder and the elbow. Its forward kinematics is a pair of trigonometric sums:

x=l1cos⁡q1+l2cos⁡(q1+q2),y=l1sin⁡q1+l2sin⁡(q1+q2).x = l_1 \cos q_1 + l_2 \cos(q_1 + q_2), \qquad y = l_1 \sin q_1 + l_2 \sin(q_1 + q_2).

Now ask for the hand to be at (0.6,0.3)(0.6, 0.3). Picture it: the shoulder and the target are two fixed points, 0.670.67 m apart, and the two links must bridge them. There is a triangle with sides 0.50.5, 0.40.4 and 0.670.67, and you can build it on either side of the line from shoulder to target. One triangle puts the elbow above that line, the other below. That is the whole story of the two solutions.

target (0.6, 0.3) melbow up (q₂ < 0)elbow down (q₂ > 0)reach 0.9 mhole: 0.1 m
A planar two-link arm reaching the target (0.6, 0.3) m in its two ways. The hand can reach every point between the dashed inner circle (radius 0.1 m) and the outer arc (radius 0.9 m); outside that ring there is no solution at all.

The same picture explains the other cases. Move the target farther away and the triangle flattens; at exactly l1+l2=0.9l_1 + l_2 = 0.9 m the arm must be straight, and the two solutions merge into one. Beyond that, no triangle exists. Move the target very close to the shoulder and the same happens on the inside: a point nearer than ∣l1−l2∣=0.1|l_1 - l_2| = 0.1 m cannot be reached, because the arm folded back on itself still holds the hand 0.10.1 m away. Add a third link and the hand position no longer pins down the arm: there is a whole curve of arm shapes ending at the same point.

Analogy, not a formal construction

Put a fingertip on a spot on the table and keep it there. Your elbow can still swing in a circle, and your wrist can still tilt. Your arm has about seven degrees of freedom that matter here (three at the shoulder, one at the elbow, and three in the forearm and wrist), but a fingertip position fixes only three numbers, so you have four "spare" degrees of freedom for comfort, reach and avoiding the coffee cup. Robot designers copy this: many research arms have seven joints for the same reason.

DefinitionsH

Definitions

Definition— inverse kinematics

Given forward kinematics T(q)=0TE(q)T(q) = {}^{0}T_{E}(q) for joint vector q∈Rnq \in \mathbb{R}^n and a desired pose T∗T^* (or a desired position, if orientation does not matter), the inverse kinematics problem is to find every qq, or a suitable one, with T(q)=T∗T(q) = T^* and qq inside the joint limits.

Definition— workspace

The reachable workspace is the set of tool positions some qq can produce. The dexterous workspace is the smaller set reachable in every orientation. For the two-link arm the reachable workspace is the ring ∣l1−l2∣≤r≤l1+l2|l_1 - l_2| \le r \le l_1 + l_2, and the dexterous workspace is empty, since a two-joint arm cannot choose its hand's angle as well as its position.

Definition— solution branch

The distinct solutions of a non-redundant arm come in branches (or configurations): elbow up or down, shoulder left or right, wrist flipped or not. Inside the workspace, each branch varies smoothly with the target; branches meet only at singular configurations, such as the fully stretched arm.

Definition— redundancy

An arm with nn joints doing a task with mm independent coordinates is redundant when n>mn > m. Its degree of redundancy is n−mn - m, and generically its solutions form a set of dimension n−mn - m, the self-motion manifold. A 6-axis arm placing a tool in full 3-D pose (m=6m = 6) is not redundant; a 7-axis arm doing the same task has one spare degree of freedom; a 6-axis arm whose tool is a drill symmetric about its own axis (m=5m = 5) is redundant too.

ExplanationH

Geometric and algebraic methods, and the six-axis arm

What we just did is a geometric method: draw the arm, spot a triangle, apply the law of cosines. It is quick and gives insight, but it relies on spotting the right picture. The algebraic method is mechanical. Write the forward kinematics equations, substitute ui=tan⁡(qi/2)u_i = \tan(q_i/2) so that cos⁡qi=(1−ui2)/(1+ui2)\cos q_i = (1 - u_i^2)/(1 + u_i^2) and sin⁡qi=2ui/(1+ui2)\sin q_i = 2u_i/(1 + u_i^2), and the trigonometric equations become polynomial ones. Elimination then reduces the system to one polynomial in one unknown, whose real roots are the solutions.

For a general arm with six revolute joints this is hard, and it took decades. Raghavan and Roth presented the elimination for the general 6R arm around 1990 (journal version 1993): it ends in a polynomial of degree 16, so a general 6R arm has at most 16 solutions, and examples are known where all 16 are real. Manocha and Canny (1994) recast the elimination as an eigenvalue problem, fast enough for real-time use.

Industrial arms avoid all this by design. In his 1968 Stanford thesis Donald Pieper showed that if three consecutive joint axes meet in a point, the IK of a six-axis arm separates into two small problems. Most industrial arms put that point in the wrist: the last three axes intersect at the wrist centre, forming a spherical wrist. Then:

  1. Position. The wrist centre is a fixed distance dd behind the tool along the tool's approach axis zEz_E: pw=p∗−d R∗zEp_w = p^* - d\, R^* z_E. It depends only on the first three joints, which form an arm much like our 2R arm with a rotating base. Solve them geometrically: up to four solutions (shoulder front or back, elbow up or down).
  2. Orientation. With q1,q2,q3q_1, q_2, q_3 known, the rotation the wrist must supply is R3⊤R∗R_{3}^{\top} R^*, where R3R_3 is the orientation of frame 3. Three intersecting axes realise it as a set of Euler angles, which the rotations lesson showed how to extract: two solutions (wrist flipped or not), merging when the middle wrist joint is at zero.

So a typical six-axis industrial arm, such as the Lumen-6 of forward kinematics, has up to 4×2=84 \times 2 = 8 solutions for a reachable pose. The planar 3R arm with a target orientation, in the exercises, is the same idea in miniature: step back from the tool along the last link to find the wrist point, solve the 2R arm, then set the last joint to get the angle right.

Modern geometric solvers make Pieper's insight systematic. A handful of subproblems with closed-form solutions (rotate one vector onto another about one axis; about two axes; rotate to a given distance from a point), named after Paden and Kahan, who catalogued them in the 1980s, cover most practical arms. IK-Geo (Elias and Wen, 2022) extends the catalogue so that every 6R arm with three intersecting or parallel axes is solved in closed form, and any other 6R arm by searching over one or two joint angles, returning every solution.

ComputationC

Numerical IK: Newton's method and damped least squares

Closed forms exist only for special geometries, and they say nothing about which of eight answers you want or about joint limits. The general-purpose alternative is to iterate: start from a guess q0q_0, usually the robot's current configuration, and improve it.

Near the current guess, forward kinematics is almost linear. If the joints move by a small Δq\Delta q, the hand moves by about J(q) ΔqJ(q)\,\Delta q, where JJ is the Jacobian, the matrix of partial derivatives Jij=∂fi/∂qjJ_{ij} = \partial f_i / \partial q_j. The next lesson derives JJ exactly from the arm's geometry; for now, estimate each column by wiggling one joint: J:,j≈(f(q+hej)−f(q−hej))/2hJ_{:,j} \approx \big(f(q + h e_j) - f(q - h e_j)\big)/2h with h=10−6h = 10^{-6} rad. To make the error e=x∗−f(q)e = x^* - f(q) vanish, solve the linear system J Δq=eJ\,\Delta q = e and update q←q+Δqq \leftarrow q + \Delta q. This is Newton's method for the equation f(q)=x∗f(q) = x^*, the same method as for roots of one equation in numerical methods, now with a matrix in place of the derivative.

python
import numpy as np

L1, L2 = 0.5, 0.4

def fk(q):
    return np.array([L1 * np.cos(q[0]) + L2 * np.cos(q[0] + q[1]),
                     L1 * np.sin(q[0]) + L2 * np.sin(q[0] + q[1])])

def jacobian_fd(f, q, h=1e-6):
    """Central finite differences: column j is how the hand moves per radian of joint j."""
    q = np.asarray(q, dtype=float)
    cols = []
    for j in range(len(q)):
        dq = np.zeros_like(q)
        dq[j] = h
        cols.append((f(q + dq) - f(q - dq)) / (2 * h))
    return np.column_stack(cols)

def newton_ik(f, q0, target, iters=8):
    q = np.array(q0, dtype=float)
    for k in range(iters):
        e = target - f(q)                       # task-space error (m)
        print(f"  iter {k}: |error| = {np.linalg.norm(e):.3e} m   q = {np.round(np.degrees(q), 3)} deg")
        if np.linalg.norm(e) < 1e-12:
            break
        J = jacobian_fd(f, q)
        q = q + np.linalg.solve(J, e)           # the Newton step: J dq = e
    return q

target = np.array([0.6, 0.3])
print("start near elbow down:")
newton_ik(fk, np.radians([0.0, 60.0]), target)
print("start near elbow up:")
newton_ik(fk, np.radians([90.0, -60.0]), target)
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Each start converges to the solution on its own branch: the same two answers as the closed form, to every printed digit.

Newton's method has two weaknesses, and both come from the Jacobian. If JJ is not square (a redundant arm, or a task with fewer coordinates than joints), J Δq=eJ\,\Delta q = e has no unique solution; the standard choice is the smallest step that does the job, Δq=J+e\Delta q = J^{+} e, using the Moore–Penrose pseudoinverse J+J^{+}. Worse, near a singular configuration, where JJ loses rank, such as our arm at full stretch, the system is nearly unsolvable and Δq\Delta q becomes enormous. An unreachable target is even nastier: the arm stretches towards it, becomes singular, and the steps explode.

The cure, introduced to robotics by Wampler and by Nakamura and Hanafusa in 1986, is damped least squares (DLS), also called the Levenberg–Marquardt step. Instead of insisting that J Δq=eJ\,\Delta q = e exactly, choose the step that best balances the two wishes "reduce the error" and "don't move much":

Δq=arg⁡min⁡Δq ∥J Δq−e∥2+λ2∥Δq∥2=J⊤(JJ⊤+λ2I)−1e.\Delta q = \arg\min_{\Delta q}\ \|J\,\Delta q - e\|^2 + \lambda^2 \|\Delta q\|^2 = J^{\top}\left(J J^{\top} + \lambda^2 I\right)^{-1} e .

The matrix JJ⊤+λ2IJ J^{\top} + \lambda^2 I is always invertible for λ>0\lambda > 0, so the step always exists. Writing JJ through its singular value decomposition shows what damping does: a direction in which the arm can move at rate σ\sigma per radian gets gain σ/(σ2+λ2)\sigma/(\sigma^2 + \lambda^2) instead of 1/σ1/\sigma. For large σ\sigma that is almost 1/σ1/\sigma, so far from singularities DLS behaves like Newton; as σ→0\sigma \to 0 the gain falls to zero instead of exploding, and it never exceeds 1/(2λ)1/(2\lambda).

python
import numpy as np

L1, L2 = 0.5, 0.4

def fk(q):
    return np.array([L1 * np.cos(q[0]) + L2 * np.cos(q[0] + q[1]),
                     L1 * np.sin(q[0]) + L2 * np.sin(q[0] + q[1])])

def jacobian_fd(f, q, h=1e-6):
    cols = []
    for j in range(len(q)):
        dq = np.zeros(len(q))
        dq[j] = h
        cols.append((f(q + dq) - f(q - dq)) / (2 * h))
    return np.column_stack(cols)

def solve_ik(f, q0, target, damping=0.0, iters=100, tol=1e-10):
    """Newton with the pseudoinverse (damping = 0) or damped least squares (damping > 0)."""
    q = np.array(q0, dtype=float)
    biggest_step = 0.0
    for k in range(1, iters + 1):
        e = target - f(q)
        if np.linalg.norm(e) < tol:
            return q, k - 1, np.linalg.norm(e), biggest_step
        J = jacobian_fd(f, q)
        if damping == 0.0:
            dq = np.linalg.pinv(J) @ e
        else:                                   # dq = J^T (J J^T + lambda^2 I)^-1 e
            dq = J.T @ np.linalg.solve(J @ J.T + damping**2 * np.eye(len(e)), e)
        biggest_step = max(biggest_step, np.degrees(np.abs(dq)).max())
        q = q + dq
    return q, iters, np.linalg.norm(target - f(q)), biggest_step

cases = [("reachable, ordinary start", [0.0, 1.0], [0.6, 0.3]),
         ("reachable, start stretched", [0.0, 0.0], [0.6, 0.3]),
         ("unreachable, 1.3 m away", [0.3, 0.5], [1.2, 0.5])]
print(f"{'case':27} {'method':11} {'iterations':>10} {'final error':>12} {'largest step':>13}")
for name, q0, target in cases:
    for label, lam in [("Newton", 0.0), ("DLS 0.05", 0.05), ("DLS 0.2", 0.2)]:
        q, k, err, step = solve_ik(fk, q0, np.array(target), damping=lam)
        print(f"{name:27} {label:11} {k:10d} {err:10.1e} m {step:9.1f} deg")

q, *_ = solve_ik(fk, [0.3, 0.5], np.array([1.2, 0.5]), damping=0.2)
print("\nDLS 0.2, unreachable target: q =", np.round(np.degrees(q), 2), "deg;",
      "the target lies at", round(float(np.degrees(np.arctan2(0.5, 1.2))), 2), "deg")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The table shows the trade-off honestly. From an ordinary start, plain Newton is fastest (4 iterations) and heavier damping is slower (21 iterations at λ=0.2\lambda = 0.2): damping costs speed. Starting from the stretched, singular arm, Newton still gets there but on the way takes a step of almost 500°500°, a wild spin no real controller should command. On the unreachable target, Newton and lightly damped DLS thrash for all 100 iterations, with steps of more than a thousand degrees. DLS with λ=0.2\lambda = 0.2 calmly settles on the closest reachable point: arm straight (q2=0q_2 = 0), pointing at the target (q1=22.62°q_1 = 22.62°), 0.40.4 m short, which is exactly 1.3−0.91.3 - 0.9. Practical solvers therefore damp more near singularities and less away from them, cap the size of each step, and report "closest point, not reached" instead of failing silently.

ExplanationH

Redundancy, joint limits and choosing a solution

A solver that returns a solution has done half the job. Real software must choose which solution, and the right choice depends on the task.

  • Stay close. When following a path, pick the solution nearest the current configuration (in a weighted joint distance), so that the arm moves a little rather than flipping its elbow mid-weld. Numerical IK seeded with the current joints does this naturally; analytic solvers compute all branches and pick the nearest.
  • Respect joint limits. Every real joint has a range, set by cables, hard stops or the motor's design. A solution with q3=134°q_3 = 134° on a joint that stops at 120°120° is useless.
  • Avoid collisions with the robot itself, the table and people, and keep a margin from singularities, where small hand motions demand large joint motions (next lesson).
  • Keep the branch. Moving between two branches of a non-redundant arm along a path means passing through a singular configuration. Industrial controllers therefore store a configuration flag with each taught pose (ABB calls it confdata, KUKA uses Status and Turn bits) and refuse to switch branches implicitly.

For a redundant arm the solutions form a continuous family, and the spare freedom can be put to work. Take a planar arm with three links (0.40.4, 0.30.3 and 0.20.2 m) reaching the point (0.35,0.45)(0.35, 0.45): one equation per coordinate, three unknowns, a one-parameter family of answers.

target (0.35, 0.45) mlast link at 45°at 135°
Two of the infinitely many ways a planar three-link arm can put its tip on the same point. They differ in the angle of the last link: 45° (solid) and 135° (gold).

Two techniques exploit the family. The first is null-space projection. The matrix I−J+JI - J^{+}J projects any joint motion onto the null space of JJ: the motions that, to first order, do not move the hand. So the update

Δq=J+e+(I−J+J)z,z=−k ∇H(q),\Delta q = J^{+} e + \left(I - J^{+} J\right) z, \qquad z = -k\, \nabla H(q),

drives the hand to the target with its first term and, with its second, slides along the family of solutions to reduce a secondary cost HH. A common HH is the squared distance of each joint from the middle of its range, scaled by the range; others measure distance from obstacles or from singularities.

python
import numpy as np

L = np.array([0.4, 0.3, 0.2])                        # a planar 3R arm: 3 joints, 2-D task
LIMITS = np.radians([[-90, 90], [-120, 120], [-120, 120]])

def fk(q):
    a = np.cumsum(q)                                 # absolute angle of each link
    return np.array([L @ np.cos(a), L @ np.sin(a)])

def jacobian(q):
    a = np.cumsum(q)
    J = np.zeros((2, 3))
    for j in range(3):                               # joint j swings links j, j+1, ...
        J[0, j] = -L[j:] @ np.sin(a[j:])
        J[1, j] = L[j:] @ np.cos(a[j:])
    return J

def ik_redundant(q0, target, k_null=0.0, iters=300):
    q = np.array(q0, dtype=float)
    mid = LIMITS.mean(axis=1)
    half = (LIMITS[:, 1] - LIMITS[:, 0]) / 2
    for _ in range(iters):
        e = target - fk(q)
        J = jacobian(q)
        Jp = np.linalg.pinv(J)
        grad_H = (q - mid) / half**2                 # H(q) = 1/2 sum ((q - mid) / half)^2
        dq = Jp @ e + (np.eye(3) - Jp @ J) @ (-k_null * grad_H)
        q = q + 0.5 * dq
    return q

def report(name, q, target):
    inside = np.all((q >= LIMITS[:, 0]) & (q <= LIMITS[:, 1]))
    print(f"{name:36} q = {np.round(np.degrees(q), 1)} deg  error = {np.linalg.norm(target - fk(q)):.0e} m"
          f"  within limits: {inside}")

target = np.array([0.35, 0.45])
for q0 in ([0.2, 0.2, 0.2], [-0.5, 2.0, 0.5], [1.2, -1.0, 1.5]):
    report(f"start {q0}", ik_redundant(q0, target), target)
report("start [1.2, -1.0, 1.5] + null space", ik_redundant([1.2, -1.0, 1.5], target, k_null=0.5), target)

# The solutions form a one-parameter family: choose the last link's absolute angle phi freely.
print("\nphi (deg)    q1      q2      q3    within limits   (elbow-down branch)")
for phi in range(-90, 181, 45):
    p = np.radians(phi)
    wx, wy = target - L[2] * np.array([np.cos(p), np.sin(p)])   # where the wrist must be
    c2 = (wx**2 + wy**2 - L[0]**2 - L[1]**2) / (2 * L[0] * L[1])
    if abs(c2) > 1:
        print(f"{phi:9d}   wrist out of reach")
        continue
    q2 = np.arctan2(np.sqrt(1 - c2**2), c2)
    q1 = np.arctan2(wy, wx) - np.arctan2(L[1] * np.sin(q2), L[0] + L[1] * np.cos(q2))
    q3 = p - q1 - q2
    q3 = (q3 + np.pi) % (2 * np.pi) - np.pi
    q = np.array([q1, q2, q3])
    ok = np.all((q >= LIMITS[:, 0]) & (q <= LIMITS[:, 1]))
    print(f"{phi:9d} {np.degrees(q1):7.1f} {np.degrees(q2):7.1f} {np.degrees(q3):7.1f}    {ok}")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Three starting guesses give three different exact solutions, and the third breaks the limit of joint 3 (134.4°134.4° against 120°120°). Adding the null-space term to the same start leads to (−1.0°,78.6°,47.3°)(-1.0°, 78.6°, 47.3°), comfortably inside every range, with the hand still on target. The table makes the family explicit: for every angle φ\varphi of the last link whose wrist point is reachable there is an elbow-down solution, and only some of them respect the limits.

The second technique is to treat IK as optimisation from the start:

min⁡q 12∥f(q)−x∗∥W2+μ2∥q−qrest∥2subject toqmin⁡≤q≤qmax⁡, collision constraints.\min_{q}\ \tfrac12\|f(q) - x^*\|^2_W + \tfrac{\mu}{2}\|q - q_{\text{rest}}\|^2 \quad \text{subject to}\quad q_{\min} \le q \le q_{\max},\ \text{collision constraints}.

Nonlinear-programming solvers (sequential quadratic programming, interior-point methods) handle the bounds and constraints directly. In differential IK, used in real-time control, each control tick solves a small quadratic program for the joint velocities that best achieve several weighted or prioritised tasks — the hand pose, the gaze direction, the balance of a humanoid — subject to joint position, velocity and torque limits.

ExplanationH

How industry and research solve IK

Industrial arms. Six-axis arms from FANUC, ABB, KUKA, Yaskawa, Kawasaki and others are built with spherical wrists (or, like Universal Robots' arms, with three parallel middle axes, another geometry with closed-form IK), so their controllers solve IK analytically in microseconds, every interpolation cycle, choosing the branch from the stored configuration flags. Offline programming tools use the same closed forms to check reachability before a cell is built.

Open-source and research software. For arms described only by a URDF model, numerical solvers dominate.

  • KDL, the Orocos Kinematics and Dynamics Library, provides Newton–Raphson and Levenberg–Marquardt position solvers; it was long the default IK plugin of MoveIt.
  • TRAC-IK (Beeson and Ames, 2015) runs a KDL-style Newton solver with random restarts and an SQP optimiser in parallel and returns whichever succeeds first, which removed many false "no solution" failures on humanoid arms.
  • IKFast, part of OpenRAVE, analyses an arm's geometry symbolically and generates C++ code for its closed-form solution; MoveIt can use the generated solvers as plugins. IK-Geo does the same job with geometric subproblems.
  • Pinocchio computes kinematics and Jacobians fast, and libraries such as Pink (on Pinocchio) and mink (on MuJoCo) build quadratic-programming differential IK on top, with tasks, priorities and limits. Drake poses IK as a constrained nonlinear program with position, orientation, distance and collision constraints.
  • cuRobo (NVIDIA, 2023) runs thousands of collision-aware IK optimisations from different seeds in parallel on a GPU, trading brute force for reliability.

In Pinocchio, one damped Newton update for a 6-D pose target looks like the sketch below. It is shown, not run here: it needs Pinocchio and a robot model. The error is the 6-D twist that carries the current tool frame to the target, computed with the matrix logarithm of the rotations lesson.

python
import numpy as np
import pinocchio as pin

model = pin.buildModelFromUrdf("my_arm.urdf")         # any arm described in URDF
data = model.createData()
tool = model.getFrameId("tool0")

def ik_step(q, target, lam=0.05):
    pin.forwardKinematics(model, data, q)
    pin.updateFramePlacements(model, data)
    current = data.oMf[tool]                            # pose of the tool in the world
    err = pin.log(current.actInv(target)).vector        # 6-D error, in the tool frame
    J = pin.computeFrameJacobian(model, data, q, tool, pin.LOCAL)
    dq = J.T @ np.linalg.solve(J @ J.T + lam**2 * np.eye(6), err)
    return pin.integrate(model, q, dq)                  # respects how each joint type moves

Graphics and animation use the same mathematics with different priorities: games and animation tools often use cheap heuristics such as cyclic coordinate descent, which adjusts one joint at a time, because a plausible pose every frame matters more than exactness. And learned methods — networks that propose IK seeds, or policies that output joint commands directly, as in the Learning level of this course — still lean on classical IK for checking, for labelling data and for safety limits.

Whatever the method, a solution is checked before it reaches a motor: forward kinematics confirms the pose, the controller confirms the limits, and on a real robot the first test of new IK code is in simulation, then on the real arm at low speed, inside its guarded cell.

Common misconceptionsH

Common misconceptions

Misconception

"Inverse kinematics has an answer." It may have none, a few, or infinitely many. Code that calls an IK function must handle all three: report unreachable targets, choose among branches, and resolve redundancy deliberately rather than by accident of the starting guess.

Misconception

"The numerical solver failed, so the target is unreachable." A local method can stall near a singularity, run into a joint limit, or converge to a different branch, even when a solution exists. Try several seeds, check against the workspace analytically when you can, and treat "not found" and "does not exist" as different results.

Misconception

"Reaching the position is enough." A tool has a pose: position and orientation. A gripper at the right point but rotated 90°90° will not grasp the box. Full IK solves for six numbers; when some orientation does not matter (a symmetric drill, a suction cup), say so explicitly and let the solver use the freedom.

Misconception

"Analytic IK is always better than numerical IK." Closed forms are exact, fast and return every branch, but they exist only for suitable geometries and know nothing of limits, collisions or secondary goals. Numerical and optimisation methods handle any arm and any constraint, at the cost of seeds and convergence checks. Real systems often combine them: analytic solutions as seeds or candidates, optimisation to choose and refine.

Exercises

Exercises

1. Inverse kinematics

Warm-upHuman

A planar two-link arm has l1=0.5l_1 = 0.5 m and l2=0.4l_2 = 0.4 m. A camera reports a target only 0.050.05 m from the shoulder. How many inverse kinematics solutions are there?

Choose one

2. Inverse kinematics

CoreHuman

A planar 2R arm has l1=l2=1l_1 = l_2 = 1 m. For the target (x,y)=(1,1)(x, y) = (1, 1), one solution is q1=0°q_1 = 0°, q2=90°q_2 = 90°. The other solution has q2=−90°q_2 = -90°. What is its q1q_1, in degrees?

3. Inverse kinematics

CoreHuman

A six-axis industrial arm has a spherical wrist and a shoulder–elbow geometry like the one described in the lesson. For a target pose well inside its workspace and away from singularities, ignoring joint limits, how many distinct IK solutions does it have, at most?

4. Inverse kinematics

CoreComputational

A planar arm has three revolute joints and links of lengths l1, l2, l3. Its tool tip must be at (x, y) with the last link pointing at absolute angle phi (radians): a full planar pose. Write ik_3r_pose(l1, l2, l3, x, y, phi) returning a list of every solution (q1, q2, q3): two inside the workspace, one at a boundary, none when the pose cannot be reached.

Use the decoupling idea of the six-axis arm, in miniature: first find the wrist point (joint 3), then solve the 2R arm for it, then choose q3. The tests check every solution with forward kinematics.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

5. Inverse kinematics

StretchComputational

Complete dls_ik(fk, q0, target, lam=0.2, iters=300, tol=1e-10), a damped least squares IK solver for any arm. fk maps a joint vector to a task-space position; numeric_jacobian(fk, q) (provided) estimates the Jacobian by central differences.

Repeat: compute the error e = target - fk(q); stop if its norm is below tol; otherwise update q <- q + J^T (J J^T + lam^2 I)^{-1} e.

The tests use the lesson's 2R arm (including a start at full stretch and an unreachable target, where the arm must end straight and pointing at the target) and a redundant 3-link arm.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

6. Inverse kinematics

CoreHuman

A numerical IK solver, seeded with the robot's current joint angles, stops after its iteration limit without reaching a target pose. Which of these are sound next steps? Select all that apply.

Choose all that apply

7. Inverse kinematics

Warm-upHuman

Most six-axis industrial arms have their last three joint axes meeting at a single point, which lets their inverse kinematics split into a position problem and an orientation problem. What is this kind of wrist called? (Two words.)

Further reading and resources