Growing Toward the Gradient
A plant doesn’t know where the sun is. It just knows which direction is brighter than the others, measures the gradient, and grows that way. Repeat until you’ve traced a curve through three-dimensional space. This is gradient descent with chlorophyll instead of calculus.
The algorithm: start somewhere, measure the slope, take a step downhill (or uphill, if you’re maximizing light). The step size matters—too large and you overshoot, too small and you’ll never get there before winter. Plants solve this with auxin redistribution and differential cell growth. We solve it with a learning rate parameter.
def descend(x, y, rate=0.1, steps=50):
for _ in range(steps):
grad_x = 2 * (x - 3) # gradient of (x-3)² + (y-2)²
grad_y = 2 * (y - 2)
x -= rate * grad_x
y -= rate * grad_y
print(f"({x:.2f}, {y:.2f})")
return x, y
descend(0, 0) # grows from origin toward light at (3, 2)
The Zig version trades Python’s brevity for explicit control over precision and iteration. You’d use this when the gradient function is computationally expensive or you’re optimizing in embedded systems—say, a solar tracker that adjusts panel angles.
const std = @import("std");
pub fn main() !void {
var x: f32 = 0.0;
var y: f32 = 0.0;
const rate: f32 = 0.1;
for (0..50) |_| {
x -= rate * 2.0 * (x - 3.0);
y -= rate * 2.0 * (y - 2.0);
try std.io.getStdOut().writer().print("({d:.2}, {d:.2})\n", .{x, y});
}
}
Both converge on (3, 2) along a straight line in this symmetric toy bowl. Real phototropic paths curve because each step only sees the local slope. The plant doesn’t need the global map—it just needs to know which way is up.