Challenge

Week 5 - Curve fitting

  1. What does popt and pcov mean?

Ans. The curve_fit function returns two items, which we call popt and pcov.

The popt argument is a list of the best-fit parameters for a, b,c. It performs some internal calculations and then finds out the coefficients of the function we pass into it. For eg- in the video, the function we are passing is func in which a,b and c are the coefficients of ‘t’. This means popt will store the value of a,b,c. The pcov variable contains the covariance matrix indicating the correlations and uncertainties between parameters. When the data has uncertainties, it is very useful.

  1. What does np.array(temperature) do?

Ans. np.array() is used to convert any list or tuple into an array. It is used when we have to perform a function on every element of the array. This increases the execution speed of the code and it makes our task of operating on each and every element of the array very easy. In the video we have converted the temperature list into an array using this command so that every element can be changed according to the need.

  1. What does the * in *popt mean?

Ans. Adding ‘*’ before any variable makes it possible to pass as many arguments as we want into the function. Otherwise we won't be able to do so because it creates an upper limit that only these no. of variables must pass into the function.

  1. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    import numpy as np
    
    # Function to read file
    def read_file():
        temperature = []
        cp = []
        for line in open('data','r'):
            values = line.split(',')
            temperature.append(float(values[0]))
            cp.append(float(values[1]))
        return [temperature,cp]
    
    # Function for linear curve fitting
    def linear(t,a,b):
        v = a*t + b
        return v
    
    # Function for cubic curve fitting
    def cubic(t,a,b,c,d):
        v = a*t**3 + b*t**2 + c*t + d
        return v
    
    # storing temperature and Cp values 
    temperature,cp = read_file()
    
    # Performing linear curve fit 
    popt1,pcov1 = curve_fit(linear,temperature,cp)
    fit_cp1 = linear(np.array(temperature),*popt1)
    
    # plotting data of linear curve fit
    plt.figure()
    plt.plot(temperature,cp,label = " Actual Data",linewidth = 2)
    plt.plot(temperature, fit_cp1, label = "Linear Curve fit", linewidth = 2)
    plt.xlabel("Temerature")
    plt.ylabel("Cp")
    plt.legend()
    plt.title("Temperature vs Cp graph ")
    plt.show()
    
    # Performing cubic curve fit
    popt2,pcov2 = curve_fit(cubic,temperature,cp)
    fit_cp2 = cubic(np.array(temperature),*popt2)
    
    # plotting data of cubic fit
    plt.plot(temperature,cp,label = " Actual Data",linewidth = 2)
    plt.plot(temperature, fit_cp2, label = "Cubic Curve fit", linewidth = 2)
    plt.xlabel("Temperature(K)")
    plt.ylabel("Cp")
    plt.legend()
    plt.title("Temperature vs Cp graph ")
    plt.show()

    Explanation of the code:

    1. Imported matplotlib for plotting results, numpy for converting list into array by using np.array() and curve_fit() function from scipy.optimize
    2. Firstly, the data file is read using read_file() function which returns the temperature and cp list.
    3. Then curve_fit() function is called which takes a function linear(), temperature and cp as parameters and returns popt and pocv list.
    4. linear() is a function which tells about the type of system by the equation it consists. In the code it contains a linear polynomial which can fit the data.
    5. Then a graph is plotted with the actual data and the curve which best satisfies it.
    6. Same procedure is used for curve fitting by cubic polynomial.

    Results: From the graphs, it is clearly visible that linear curve fit does not fit the actual data properly. Whereas the cubic fit closely fits the actual data and gives more accurate results.This means that cubic polynomial provides a good fit whereas linear polynomial provides a bad fit.

  2. What needs to be done in order to make the curve fit perfect?

    Ans. In order to make the curve fit perfect, higher degree polynomials can be used. For eg : By using a polynomial of degree 4, the results obtained are better than that obtained with degree 3.

    Code for polynomial of degree 4.

    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    import numpy as np
    
    # Function to read file
    def read_file():
        temperature = []
        cp = []
        for line in open('data','r'):
            values = line.split(',')
            temperature.append(float(values[0]))
            cp.append(float(values[1]))
        return [temperature,cp]
    
    def deg4(t,a,b,c,d,e):
        v = a*t**4 + b*t**3 + c*t**2 + d*t + e
        return v
    
    # storing temperature and Cp values 
    temperature,cp = read_file()
    
    # Performing linear curve fit 
    popt1,pcov1 = curve_fit(deg4,temperature,cp)
    fit_cp1 = deg4(np.array(temperature),*popt1)
    
    # plotting data of linear curve fit
    plt.figure()
    plt.plot(temperature,cp,label = " Actual Data",linewidth = 2)
    plt.plot(temperature, fit_cp1, label = "Curve fit", linewidth = 2)
    plt.xlabel("Temerature")
    plt.ylabel("Cp")
    plt.legend()
    plt.show()

    Result: The polynomial of degree 4 saties the curve best as compared to cubic and linear polynomials.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.