Skip to content

YahiaJouini/function-plotter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Function Plotter

A real-time 2D mathematical function plotter built with C and SDL2. This program renders mathematical expressions as graphs with interactive panning and zooming capabilities.

Function Plotter Demo

What It Does

This program takes a mathematical expression as input and plots it on a 2D coordinate system. It evaluates the expression across the visible x-axis range and draws the resulting curve on screen. The plotter includes:

  • Real-time rendering of mathematical functions
  • Interactive pan and zoom controls
  • Dynamic grid with adaptive tick marks
  • A resizable fullscreen window

How It Works

Expression Evaluation
The program uses the TinyExpr library to parse mathematical strings and compile them.

Coordinate Mapping
The plotter maintains a View structure with mathematical boundaries ($x_{min}, x_{max}, y_{min}, y_{max}$) and performs two-way mapping between math space and screen pixels for rendering and user interactions.

Adaptive Grid
The grid calculates tick spacing using:

$$step = 10^{\lfloor \log_{10}(range) \rfloor - 1}$$

This formula ensures the grid remains readable at any zoom level. It works by finding what "size class" the current range falls into (ones, tens, hundreds, etc.) using $\log_{10}$, then creating tick marks at intervals one order of magnitude smaller.

For example, if your view spans 0-50, the range is 50, so ticks appear every 1 unit. If you zoom out to 0-500, ticks jump to every 10 units.

Rendering Pipeline
Each frame iterates through every horizontal pixel, maps it to a mathematical $x$ value, evaluates the function, and connects points with a line. Non-finite values (NaN, Infinity) are filtered out to prevent artifacts at discontinuities.

How to Use

Building

Prerequisites: You need SDL2 and SDL2_ttf libraries installed on your system.

Compile the program with:

gcc -Iinclude src/main.c src/core/*.c vendor/tinyexpr/tinyexpr.c -lSDL2 -lSDL2_ttf -lm -o main

Running

Execute the program with the -e flag for the expression and -v flag for the variable:

./main -e 'sin(x)*cos(3*x)*x^2' -v x

Command-line arguments:

  • -e : The mathematical expression to plot
  • -v : The variable name used in the expression

Example expressions:

./main -e 'x^2' -v x
./main -e 'sin(x)' -v x
./main -e '1/x' -v x
./main -e 'exp(-x^2)' -v x

Controls

  • Left Click + Drag: Pan the view
  • Mouse Wheel: Zoom in/out (centered on cursor)
  • Close Window: Exit the program

About

Interactive 2D math graphing tool built in C with SDL2 that plots mathematical functions in real time with pan and zoom support.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages