arrufat/zymbol
Symbolic Automatic Differentiation for Zig
Symbolic Automatic Differentiation for Zig
const std = @import("std");
const zymbol = @import("zymbol");
var registry = zymbol.Registry.init(allocator);
defer registry.deinit();
try zymbol.registerBuiltins(®istry);
var expr = try zymbol.Expression.parse(allocator, ®istry, "x^2 + sin(x)");
defer expr.deinit();
var inputs = std.StringHashMap(f32).init(allocator);
defer inputs.deinit();
try inputs.put("x", 1.5);
const value = try expr.evaluate(inputs);
std.debug.print("f(1.5) = {d}\n", .{value});
var grad_expr = try expr.symbolicGradient("x");
defer grad_expr.deinit();
const grad_value = try grad_expr.evaluate(inputs);
std.debug.print("df/dx(1.5) = {d}\n", .{grad_value});
grad(grad(f)) for higher-order derivativesd/dx x^3 -> 3 * (x ^ 2), x + x -> 2 * x)x, foo_bar).2, 3.14).+, -, *, /, ^ with standard precedence.+ and - are supported (-x, -(x + 1)).sin(x), max(x, y), etc.).log, exp, sin, cos, tan, sinh, cosh, and tanh; additional ops can be registered at runtime.Build an interactive derivative playground that runs entirely in the browser:
zig build wasm-example
cd zig-out/wasm
python -m http.server 8080
Then browse to http://localhost:8080. The page lets you type an expression, choose the differentiation variable, toggle simplification, and calls the compiled WASM module to print either the raw or simplified symbolic derivative. The build enables rdynamic so every exported Zig function stays visible to JavaScript.
Changes pushed to master are deployed automatically to https://arrufat.github.io/zymbol via the GitHub Actions workflow in .github/workflows/pages.yml, which builds with the latest Zig master toolchain.