Just sharing my implementation of polynomial:
/// Evaluate a polynomial with coefficients `coeffs` at `x`.
///
/// coeffs are in decreasing order.
///
/// For example:
/// coeffs &.{1.0, 2.0, -3.0} is polynomial y = 1.0*x^2 + 2.0*x - 3.0.
///
/// Special cases:
/// - when coeffs.len == 0, always returns zero.
pub fn poly(coeffs: []const f64, x: f64) f64 {
// Horner's method.
// https://en.wikipedia.org/wiki/Horner%27s_method
var result: f64 = 0;
for (coeffs) |coeff| {
result = result * x + coeff;
}
return result;
}
test poly {
try std.testing.expectEqual(2.0, poly(&.{ 2.0, 0.0 }, 1.0));
try std.testing.expectEqual(4.0, poly(&.{ 2.0, 0.0 }, 2.0));
try std.testing.expectEqual(21.0, poly(&.{ 1.0, 1.0, 1.0 }, 4.0));
}
Surprisingly easy! Would you do it differently?