59
284
5 Array computing and curve plotting
density in the second column. The goal of this exercise is to read the
data in such a file and plot the density versus the temperature as distinct
(small) circles for each data point. Let the program take the name of the
data file as command-line argument. Apply the program to both files.
Filename: read_density_data.py.
Exercise 5.17: Fit a polynomial to data points
The purpose of this exercise is to find a simple mathematical formula for
how the density of water or air depends on the temperature. The idea is to
load density and temperature data from file as explained in Exercise 5.16
and then apply some NumPy utilities that can find a polynomial that
approximates the density as a function of the temperature.
NumPy has a functionpolyfit(x, y, deg) for finding a “best fit”
of a polynomial of degreedeg to a set of data points given by the array
argumentsx andy. Thepolyfit function returns a list of the coefficients
in the fitted polynomial, where the first element is the coefficient for
the term with the highest degree, and the last element corresponds to
the constant term. For example, given points inx andy,polyfit(x,
y, 1)returnsthecoefficients a, binapolynomial a*x + bthatfits
the data in the best way. (More precisely, a liney =ax +b is a “best
fit” to the data points (x
i
,y
i
),i = 0,...,n− 1 ifa andb are chosen to
make the sum of squared errorsR =
�
n−1
j=0
(y
j
−(ax
j
+b))
2
as small as
possible. This approach is known as least squares approximation to data
and proves to be extremely useful throughout science and technology.)
NumPy also has a utilitypoly1d, which can take the tuple or list of
coefficients calculated by, e.g.,polyfit and return the polynomial as
aPython function that can be evaluated. The following code snippet
demonstrates the use of polyfit and poly1d:
coeff = polyfit(x, y, deg)
p = poly1d(coeff)
print p
# prints the polynomial expression
y_fitted = p(x)
# computes the polynomial at the x points
# use red circles for data points and a blue line for the polynomial
plot(x, y, ’ro’, x, y_fitted, ’b-’,
legend=(’data’, ’fitted polynomial of degree %d’ % deg))
a) Writeafunctionfit(x, y, deg)thatcreatesaplotofdatain x
andy arrays along with polynomial approximations of degrees collected
in the list deg as explained above.
b) Wewanttocallfittomakeaplotofthedensityofwaterversus
temperature and another plot of the density of air versus temperature. In
both calls, usedeg=[1,2] such that we can compare linear and quadratic
approximations to the data.