C Program for Linear/Exponential Curve Fitting


In some engineering works or scientific experiments, a certain number of data are available in a fixed interval, but they may not sufficient. A data lying in between the interval may be required. In order to find such data, a function or curve needs to be fitted using available data to get the required data through easy and convenient way.

Such technique of approximation of given data into curve which may be liner or of higher degree or exponential is known as curve fitting. It is based on the principle of least square.

A number of manipulations of data are required in curve fitting problems which take a long time to solve and are quite laborious. In order to simplify such calculations using programming approach, here I have presented source code in for linear and exponential curve fitting in C with sample output.

The working procedure of C program for curve fitting (in general) as linear equation is as follows:

  • When the program is executed, it asks for value of number of data, n.
  • Then, the user has to input the values of x and corresponding y. In the program, x and y are defined as array. Therefore, x and y are input using for loop.
  • After that, the program calculates the sum of x, y, xy, x2 etc.
  • Since the data are required to be approximated to linear equation i.e y = ax + b , the values of a and b are to be calculated which is performed by using following formula:

a= (∑y∑x- n∑xy)/((∑x)2 – n∑x2)

b=(∑y – a∑x)/n

  • Finally, the program prints the equation y = ax+b on screen.

The working principle of curve fitting C program as exponential equation is also similar to linear but this program first converts exponential equation into linear equation by taking log on both sides as follows:

y = ae^(bx)

lny= bx + lna

Y = Bx + A, which is a linear equation.

Source Code for Linear Curve Fitting in C:


C Program for Linear Curve Fitting - Output
Source Code for Exponential Curve Fitting in C:


C Program for Exponential Curve Fitting - Output
Also see,
Numerical Methods Tutorial Compilation

The above given source codes in C language for curve fitting are applicable for linear and exponential approximation of available data or for fitting linear or exponential curves through easy, accurate and fast way.



Please enter your comment!
Please enter your name here