A lightweight C library for fitting polynomials to data—fast, simple, and no external dependencies.
PolyFit is a small, embeddable C library for polynomial regression. It helps you fit a curve through a set of data points so you can interpolate or extrapolate with minimal effort.
Use PolyFit for signal smoothing, approximating system behavior, or forming simple transfer-function polynomials. Include the two source files and call the API; no extra setup required.
Here's a few real-world uses:
Useful in cleaning up noisy data e.g., smoothing biomedical signals like EEGs.
Model sensor noise, trajectory paths, or estimate system motion with smooth, continuous polynomials.
Originally built to model dynamic systems using polynomial-based transfer functions. Great for:
- Root locus
- Frequency response
- Pole-zero plots
- Polynomial curve fitting with configurable order
- Supports both interpolation and extrapolation
- Single-file: just drop in
polyfit.candpolyfit.h - No dependencies beyond the standard library
git clone https://github.com/FinOrr/polyfit.gitThen just copy polyfit.c and polyfit.h into your project.
#include "polyfit.h"Example 1: Simple linear fit (recommended)
#include "polyfit.h"
#include <stdio.h>
int main(void) {
// Your data points
float x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
float y[] = {2.1, 3.9, 6.1, 8.0, 9.9};
// Fit a linear polynomial (degree 1)
Polynomial *poly = polyfit(x, y, 5, 1, NULL);
if (poly) {
float result;
polyfit_evaluate(poly, 6.0f, &result);
printf("f(6.0) = %f\n", result); // Predict at x=6
polyfit_free(poly);
}
return 0;
}Example 2: One-shot evaluation (no memory management)
// Fit and evaluate in one call - perfect for quick predictions
float x[] = {0.0, 1.0, 2.0, 3.0};
float y[] = {1.0, 2.0, 5.0, 10.0};
float result;
if (polyfit_eval_at(x, y, 4, 2, 4.0f, &result) == POLYFIT_SUCCESS) {
printf("f(4.0) = %f\n", result);
}Example 3: Extract coefficients
Polynomial *poly = polyfit(x, y, 5, 2, NULL);
if (poly) {
float coeffs[3]; // degree + 1
if (polyfit_get_coefficients(poly, coeffs, 3) == POLYFIT_SUCCESS) {
printf("y = %.2f + %.2f*x + %.2f*x^2\n",
coeffs[0], coeffs[1], coeffs[2]);
}
polyfit_free(poly);
}Example 4: Error handling
polyfit_error_t err;
Polynomial *poly = polyfit(x, y, num_points, degree, &err);
if (!poly) {
fprintf(stderr, "Error: %s\n", polyfit_error_string(err));
return -1;
}
// Use polynomial...
polyfit_free(poly);Just copy these two files into your project:
polyfit.cpolyfit.h
Then compile with your source code:
gcc -o myapp main.c polyfit.c -lmMore detailed info and examples are available on the Wiki.
Found a bug? Want to improve performance or add features? PRs welcome, just read the contributing guide first.
MIT. See LICENSE for full details.
Open an issue if you get stuck or want to ask anything.