Example #1
0
    return p


#the initial data being set into the x and y data arrays
xData = array([1718, 1767, 1774, 1775, 1792, 1816, 1828, 1834, 1878, 1906])
yData = array([0.5, 0.8, 1.4, 2.7, 4.5, 7.5, 12.0, 17.0, 17.2, 23.0])

minsdev = float("inf")
minpoly = 0
n = len(xData)
print('Degree  Stdev   2000P')
for m in range(1, 6):  # Try m=1,2,3,4,5 (degree of polynomial)
    # initialize y-coordinates for polynomial curve
    ys = zeros((n), dtype='float')
    # get coefficients for n-th degree polynomial
    coeff = polyFit(xData, yData, m)
    # get stdev of the error in the fit
    stdev = stdDev(coeff, xData, yData)
    # evaluate the polynomial at year 2000
    proj = evalPoly(coeff, 2000)
    #
    #   Year 2000 projections >= 100 or < 0 are meaniningless
    #
    if (stdev < minsdev) and proj < 100 and proj > 0:

        print('{:3d}\t{:5.3f}\t{:5.3f}\t{:s}'.format(m, stdev, proj, 'viable'))
        # get y-coordinates of polynomial using x-coordinates in xData array
        ys = [evalPoly(coeff, x) for x in xData]
        #
        #       Use Matplotlib to plot original data points with validated curve fitting
        #
Example #2
0
## example5_5
from numarray import array
from gaussPivot import *
from polyFit import *

xData = array([0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4])
yData = array([1.9934, 2.1465, 2.2129, 2.1790, \
                2.0683, 1.9448, 1.7655, 1.5891])
while 1:
    try:
        m = eval(raw_input("\nDegree of polynomial ==> "))
        coeff = polyFit(xData,yData,m)
        print "Coefficients are:\n",coeff
        print "Std. deviation =",stdDev(coeff,xData,yData)
    except SyntaxError: break
raw_input("Finished. Press return to exit")
Example #3
0
    return p


xData = array([1718, 1767, 1774, 1775, 1792, 1816, 1828, 1834, 1878, 1906])
yData = array([0.5, 0.8, 1.4, 2.7, 4.5, 7.5, 12.0, 17.0, 17.2, 23.0])

minsdev = float("inf")
minpoly = 0
n = len(xData)
print('Degree  Stdev   2000P')
for m in range(1, 6):  # Try m=1,2,3,4,5 (degree of polynomial)
    ys = zeros((n),
               dtype='float')  # initialize y-coordinates for polynomial curve

    # calculate the polynomial coefficients and standard deviation using polyFit and stdDev from polyFit.py
    coeff = polyFit(xData, yData,
                    m)  # get coefficients for n-th degree polynomial
    stdev = stdDev(coeff, xData, yData)  # get stdev of the error in the fit

    #evaluate the polynomial using the function inside the stdDev function in polyFit.py
    proj = evalPoly(coeff, 2000)  # evaluate the polynomial at year 2000
    #
    #   Year 2000 projections >= 100 or < 0 are meaniningless
    #
    if (stdev < minsdev) and proj < 100 and proj > 0:

        print('{:3d}\t{:5.3f}\t{:5.3f}\t{:s}'.format(m, stdev, proj, 'viable'))
        # get y-coordinates of polynomial using x-coordinates in xData array
        #use the loop and evalPoly function from polyFit.py to calculate the y value for each x value in xData
        for y in range(n):
            ys[y] = evalPoly(coeff, xData[y])
Example #4
0
            else:
                iLeft = i

    i = findSegment(xData, x)
    h = xData[i] - xData[i + 1]
    y = (x - xData[i + 1]) / h * k[i] - (x - xData[i]) / h * k[i + 1]
    return y


yar = []
dy = []
d2y = []
for i in range(len(xar)):
    ydata = evalSpline(xData, yData, kvals, xar[i])
    dydata = SplineDiff(xData, yData, kvals, xar[i])
    d2ydata = SplineDiff2(xData, yData, kvals, xar[i])
    yar.append(ydata)
    dy.append(dydata)
    d2y.append(d2ydata)

plt.plot(xData, yData, 'o', xar, yar, '-', xar, dy, '-', xar, d2y, '-')
plt.legend(['Input Data', 'Cubic Spline', 'diff', '2nd diff'])
plt.grid()
plt.savefig('fig1')
plt.show()

from polyFit import *
m = 2
coeffs = polyFit(kvals, yData, m)
print('Coefficients ', coeffs)
print "\n\n Polynomial interpolation results:"  # printing the numerical value of the function at the given new Re values when using the polynomial/barycentric interpolation

print "Value at Re = 5: " + (str(interpolate.barycentric_interpolate(
    Re, cD, 5)))
print "Value at Re = 50: " + (str(
    interpolate.barycentric_interpolate(Re, cD, 50)))
print "Value at Re = 500: " + (str(
    interpolate.barycentric_interpolate(Re, cD, 500)))
print "Value at Re = 5000: " + (str(
    interpolate.barycentric_interpolate(Re, cD, 5000)))

lRe = np.log(Re)
lcD = np.log(cD)

p = polyFit(
    lRe, lcD, 3
)  # this gives the coefficients of the polynomial on the logged values of Re and cD
print "The polynomial interpolation results are: "
print p

x = np.arange(
    np.log(Re[0]), np.log(Re[5]), 0.1
)  # making a range of the relevant Re log values to use with our polyfit
y = p[0] + x * (p[1]) + (x**2) * (p[2]) + (x**3) * (p[3])  # the polyfit

plt.loglog(np.e**x, np.e**y, '+')  # putting them back into exponentials

plt.show(1)

plt.figure(2)
plt.plot(Re, cD, '-')
#polyFit (least squares fit) (example assesment 1 Q3 part c)
#creates a least squares polynomial fit 

'''
c = polyFit(xData,yData,m).
    Returns coefficients of the polynomial
 
P=polyFit(x,y,m) #uses least squares fit to create a polynomial P of m degrees
yu=P[0]+P[1]*(xu)+P[2]*(xu)**2  #can use coefficients of the polynomial to find yu using P[n]*xu**n
'''
#gives a polynomial of degree n as you specify when using P[n]*xu**n

#example (assesment 1 Q3 part c)

from polyFit import * #where polyFit is a file on study direct
import numpy as np

h=np.array([0.0,1.525,3.050,4.575,6.10,7.625,9.150])
p=np.array([1.0,0.8617,0.7385,0.6292,0.5328,0.4481,0.3741])

P=polyFit(h,p,2) #uses least squares fit to create a quadratic polynomial 
P1=P[0]+P[1]*2+P[2]*2**2   #a[n]*2**n 
P2=P[0]+P[1]*5+P[2]*5**2   #a[n]*5**n

print 'density at 2km using quadratic least squares fit='
print P1

print 'density at 5km using quadratic least squares fit='
print P2

#Question 3
import scipy
import numpy
import matplotlib.pylab as plt
from scipy import *
Pi = numpy.array([1.0000, 0.8617, 0.7385, 0.6292, 0.5328, 0.4481, 0.3741])
hi = numpy.array([0.0000, 1.5250, 3.0500, 4.5750, 6.1000, 7.6250, 9.1500])
h = numpy.linspace(0, 9.15, 100)
P = scipy.interpolate.barycentric_interpolate(hi, Pi, h)
f = scipy.interpolate.interp1d(hi, Pi, kind='cubic')
Pnew = f(h)

plt.plot(h, Pnew, 'r-', label='Cubic')
plt.plot(h, P, 'b--', label='Polynomial fit')
plt.plot(hi, Pi, 'go', label='Data Points')
L = polyFit(hi, Pi, 2)

Pnew2 = L[0] + L[1] * h + L[2] * h**2
plt.plot(h, Pnew2, 'y--', label='Quadratic least-squares fit')

plt.title('Relative density of air at various altitudes')
plt.xlabel('Altitude, h, (Km)')
plt.ylabel('Relative density of air, rho')
plt.legend()
plt.show()
h2 = 2.0000
h5 = 5.0000
rho2p = scipy.interpolate.barycentric_interpolate(hi, Pi, h2)
rho5p = scipy.interpolate.barycentric_interpolate(hi, Pi, h5)
rho2c = f(h2)
rho5c = f(h5)
print "Value at Re = 500: " + (str(f(500)))
print "Value at Re = 5000: " + (str(f(5000)))


print "\n\n Polynomial interpolation results:" # printing the numerical value of the function at the given new Re values when using the polynomial/barycentric interpolation


print "Value at Re = 5: " + (str(interpolate.barycentric_interpolate(Re,cD,5)))
print "Value at Re = 50: " + (str(interpolate.barycentric_interpolate(Re,cD,50)))
print "Value at Re = 500: " + (str(interpolate.barycentric_interpolate(Re,cD,500)))
print "Value at Re = 5000: " + (str(interpolate.barycentric_interpolate(Re,cD,5000)))

lRe=np.log(Re)
lcD=np.log(cD)

p = polyFit(lRe,lcD,3) # this gives the coefficients of the polynomial on the logged values of Re and cD
print "The polynomial interpolation results are: "
print p



x = np.arange(np.log(Re[0]),np.log(Re[5]),0.1) # making a range of the relevant Re log values to use with our polyfit
y = p[0]+x*(p[1])+(x**2)*(p[2])+(x**3)*(p[3]) # the polyfit

plt.loglog(np.e**x, np.e**y, '+') # putting them back into exponentials

plt.show(1)

plt.figure(2)
plt.plot(Re,cD, '-')
plt.title('Re vs cD (not loglog)')
Example #9
0
from scipy import interpolate
from scipy.interpolate import barycentric_interpolate as bi
#when you are given an array of x and corresponding y values you can use them to estimate a value y value at a value of x you have not been given (let the unknown x be called xu and its corresponding y value be called yu) using 

yu=bi(X, Y, xu) #where X is an array of know x values and Y an array of known Y values

#Barycentric interpolate gives a polynomial of n-1 where n is the number of data points 

-------------------------------------------------------------------------------------------------
#polyFit (least squares fit) (example assesment 1 Q3 part c)
#creates a least squares polynomial fit 
from polyFit import * #where polyFit is a file on study direct

c = polyFit(xData,yData,m).
    Returns coefficients of the polynomial
 
P=polyFit(x,y,xu) #uses least squares fit to create a polynomial P
yu=P[0]+P[1]*(xu)+P[2]*(xu)**2  #can use coefficients of the polynomial to find yu using P[n]*xu**n

#gives a polynomial of degree n as you specify when using P[n]*xu**n

------------------------------------------------------------------------------------------------------------------
#cubic spline (interp1d) (example assesment 1 Q3 part b)

from scipy import interpolate

f=interpolate.interp1d(x,y, kind='cubic') #creates a cubic function that fits the graph can use kind= linear, quadratic ect or 1 2,3 for polynomial order

yu=f(xu) #uses interpolation function returned by interp1d to find yu at a point xu
print yu