0% found this document useful (0 votes)
18 views3 pages

Curve Fitting Solution

Uploaded by

Ahmed Mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views3 pages

Curve Fitting Solution

Uploaded by

Ahmed Mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Curve Fitting using Least Squares Approximation

This document contains the Python code and explanation for solving problems related to curve

fitting using the Least Squares Approximation method. The curve fitting is performed with a

polynomial of degree 2 for given data points, and an exponential function is used for fitting the data

of Problem 2.

Problem 1: Polynomial Curve Fitting

Given data points:

x = [5, 6, 7, 8, 9]

y = [1.335, 1.431, 1.247, 1.197, 1.118]

The Python code for fitting the polynomial curve using least squares approximation of degree 2 is as

follows:

import numpy as np

import matplotlib.pyplot as plt

# Function to perform least squares polynomial fitting

def least_squares_polyfit(x, y, degree):

coefficients = np.polyfit(x, y, degree)

return coefficients

# Function to plot data and fitted curve

def plot_curve(x, y, coefficients, title):

plt.scatter(x, y, color="red", label="Data points")


fitted_x = np.linspace(min(x), max(x), 500)

fitted_y = np.polyval(coefficients, fitted_x)

plt.plot(fitted_x, fitted_y, label=f"Fitted curve (degree {len(coefficients)-1})")

plt.xlabel("x")

plt.ylabel("y")

plt.title(title)

plt.legend()

plt.show()

# Problem 1

x1 = np.array([5, 6, 7, 8, 9])

y1 = np.array([1.335, 1.431, 1.247, 1.197, 1.118])

coeffs1 = least_squares_polyfit(x1, y1, 2)

print("Coefficients for Problem 1:", coeffs1)

plot_curve(x1, y1, coeffs1, "Problem 1: Curve Fitting")

Problem 2: Exponential Curve Fitting

Given data points:

x = [1, 2, 3, 4, 5]

y = [5.5, 6.1, 6.7, 7.5, 8.2]

The Python code for fitting the data to the exponential curve y = ae^(bx) is as follows:

import numpy as np

import matplotlib.pyplot as plt


# Problem 2

x2 = np.array([1, 2, 3, 4, 5])

y2 = np.array([5.5, 6.1, 6.7, 7.5, 8.2])

log_y2 = np.log(y2)

coeffs2 = least_squares_polyfit(x2, log_y2, 1)

a = np.exp(coeffs2[1])

b = coeffs2[0]

print("Coefficients for Problem 2: a =", a, ", b =", b)

fitted_y2 = a * np.exp(b * x2)

plot_curve(x2, y2, [a * np.exp(b)], "Problem 2: Exponential Fit")

You might also like