def test_interpolationLagrange(l):
    Xs = l[0]
    Ys = l[1]
    new_x = l[2]
    _, val = interpolationLagrange(Xs, Ys, new_x)
    yn = interpolate.barycentric_interpolate(Xs, Ys, new_x)
    assert np.round(val, 3) == np.round(yn, 3)
def test_interpolateNewton(s):
    Xs = [1, 4, 6, 5, 7]
    Ys = [0, 1.386294, 1.791759, 1.609438, 1.82]
    new_x = 3
    _, val = interpolateNewton(Xs, Ys, x0=new_x)
    yn = interpolate.barycentric_interpolate(Xs, Ys, new_x)
    assert np.round(val, 3) == np.round(yn, 3)
Esempio n. 3
0
def interpolation():
    samples = 77
    rec_period = 4
    sampling_rate = samples/rec_period
    time = np.linspace(0, rec_period, samples)
    sin = np.sin(time*3.75*np.pi)

    pad_count = 23
    padded_sin = np.pad(np.sin(time*3.75*np.pi), (0,pad_count), 'constant')

    fft = np.fft.rfft(sin)
    fft_padded = np.fft.rfft(padded_sin)
    bins = (np.fft.rfftfreq(len(sin))*sampling_rate)[1:]

    #print(np.insert(bins, 7, 1.875))
    new_bins = np.insert(bins, 7, 1.875)
    interpolation_fun = interpolate.interp1d(bins, np.abs(fft)[1:]*2/samples, "linear") #quadratic
    asd = np.fft.rfftfreq(100)[2:-1]*sampling_rate
    interpolationb = interpolate.barycentric_interpolate(bins, np.abs(fft)[1:]*2/samples, new_bins)

    plt.subplot(221)
    plt.plot(time, sin)
    plt.subplot(222)
    plt.plot(bins, (np.abs(fft))[1:]*2/samples)
    plt.plot(new_bins, [interpolation_fun(i) for i in new_bins], "o")
    plt.plot(new_bins, interpolationb)
    plt.subplot(223)
    plt.plot(np.linspace(0, (samples+pad_count)*rec_period/float(samples), samples+pad_count), padded_sin)
    plt.subplot(224)
    plt.plot((np.fft.rfftfreq(len(padded_sin))*sampling_rate)[1:], (np.abs(fft_padded))[1:]*2/samples, "o")
    #matplotlib2tikz.save( 'myfile.tikz' )
    plt.show()
def potential_discret(x_min, x_max, n_point, interp_type, potential_decl):
    """
    discretises the potential by using linear/cubic/polynomial interpolation and saves the results
    into a file named potential.dat

    Args:
        x_min: minimal x-value
        x_max: maximal x-value
        n_point: number of points between x_min and x_max
        interp_type: type of interpolation
        potential_decl: array of points defining the potnetial

    **return**:
        * **potential_dat** - array of the x_values in the first column \
        and the y-values of the potential in the second column
    """
    x_values = np.linspace(x_min, x_max, n_point)
    if interp_type == "linear":
        potential = np.interp(x_values, potential_decl[:, 0], potential_decl[:, 1])
    elif interp_type == "polynomial":
        potential = interpolate.barycentric_interpolate(potential_decl[:, 0],
                                                        potential_decl[:, 1], x_values)
    elif interp_type == "cspline":
        potential = interpolate.CubicSpline(potential_decl[:, 0],
                                            potential_decl[:, 1], bc_type="natural")(x_values)
    potential_dat = np.array(list(zip(x_values, potential)))
    np.savetxt("potential.dat", potential_dat)
    return potential_dat
Esempio n. 5
0
File: 101.py Progetto: Chocla/Euler
def findAnswer(u,deg):
    x = np.arange(1,deg+1,dtype=np.int64)
    y = u(x)
    fitsum = 1
    for i in range(2,len(x)+1):
        fitsum += np.round(interpolate.barycentric_interpolate(x[:i],y[:i],i+1))
  
    return fitsum
Esempio n. 6
0
    def interpolate(self, z, f):
        """"""
        from scipy.interpolate import barycentric_interpolate
        import numpy as np

        msg = "Can't interpolate outside grid domain"
        assert np.array([z]).min() >= self.zmin, msg
        assert np.array([z]).max() <= self.zmax, msg

        return barycentric_interpolate(self.zg, f, z)
Esempio n. 7
0
def update(n: int):
    label = f'{n} uniform nodes'
    print(label)

    samples = np.linspace(-1, 1, n)
    interpolated = barycentric_interpolate(samples, runge_function(samples), x)

    points.set_data(samples, runge_function(samples))
    fit.set_ydata(interpolated)
    text.set_text(label)
    return points, fit, text
Esempio n. 8
0
def update(n: int):
    label = f'{n} Chebyshev distributed nodes'
    print(label)

    samples = chebyshev_nodes(n)
    interpolated = barycentric_interpolate(samples, runge_function(samples), x)

    points.set_data(samples, runge_function(samples))
    fit.set_ydata(interpolated)
    text.set_text(label)
    return points, fit, text
    def test_g(self):
        """Example taken from:
        https://en.wikiversity.org/wiki/Numerical_Analysis/Neville%27s_algorithm_examples"""
        xs = [16, 64, 100]
        ys = [g(x) for x in xs]
        x0 = 81

        y0 = self.algorithm(xs, ys, x0)
        bi0 = barycentric_interpolate(xs, ys, x0)

        self.assertAlmostEqual(bi0, np.array(y0), 4)
Esempio n. 10
0
    def test_g(self):
        """Example taken from:
        https://en.wikiversity.org/wiki/Numerical_Analysis/Neville%27s_algorithm_examples"""
        xs = [16, 64, 100]
        ys = [g(x) for x in xs]
        x0 = 81

        y0 = self.algorithm(xs, ys, x0)
        bi0 = barycentric_interpolate(xs, ys, x0)

        self.assertTrue(isclose(y0, 0.106, rel_tol=1e-02))
        self.assertTrue(isclose(bi0, y0, rel_tol=1e-02))
Esempio n. 11
0
    def interpolate(self, z, f):
        """"""
        # from numpy.polynomial.hermite import hermfit, hermval
        # c, res = hermfit(self.zg, f, deg=self.N, full=True)
        # return hermval(z, c)
        from scipy.interpolate import barycentric_interpolate
        import numpy as np

        msg = "Can't interpolate outside grid domain"
        assert np.array([z]).min() >= self.zmin, msg
        assert np.array([z]).max() <= self.zmax, msg

        return barycentric_interpolate(self.zg, f, z)
Esempio n. 12
0
     def prep_data(self,data,
                   quantile=0.1,nbins=1000,
                   interpolate=False,dB=False,
                   substract_background=False):
          """
          This method preprocesses data (e.g., substract background).
          """

          prov = self.provider
          prep_data = deepcopy(data)
          array = data.get_parameter("intensity")
          nt = data.naxis[0] ; nf = data.naxis[1]
          frequency = data.get_parameter("frequency")
          background = data.get_parameter("background")
          int_time = data.get_parameter("integration_time")
          bandwidth = data.get_parameter("bandwidth")
          rms = 1./np.sqrt(int_time*bandwidth)
		
          if (prov == "gsfc"):
               if (interpolate):
                    where_ok = np.where(background > 0.0)
                    background=barycentric_interpolate(frequency[where_ok],background[where_ok],
                                                       frequency)
	       snr = np.zeros((nt,nf),dtype=np.float32)
               for j in range(nf):
                    array_j = array[:,j]*background[j]
                    if (sum(array_j) == 0.0): continue
                    array_j = array_j - background[j]
                    snr[:,j] = array_j/(background[j]*rms)
                    if (substract_background):
                         array[:,j]=array_j
	
               if (dB):
                    array = to_dB(array.clip(MIN_VAL,array.max()))
                    snr = to_dB(snr.clip(MIN_VAL,snr.max()))
                    background = to_dB(background.clip(MIN_VAL,background.max()))
                    if (substract_background):
                         intensity_units = "Intensity (dB)"
                    else:
                         intensity_units = "Intensity above background (dB)"
               else:
                    if (substract_background):
                         intensity_units = "Intensity"

               prep_data.set_parameter("intensity_units",intensity_units)
               prep_data.set_parameter("intensity",array)
               prep_data.set_parameter("background",background)
               prep_data.set_parameter("snr",snr)
		 
               return prep_data	
    def test_f(self):
        """Interpolation of function f with a polynomial p at the equidistant
        points x[k] = −1 + 2 * (k / n), k = 0, ..., n."""

        n = 20  # n points, so polynomial would be of degree n - 1.
        xs = [-1 + 2 * (k / n) for k in range(n)]
        ys = [f(x) for x in xs]

        for i in range(20):
            x0 = uniform(-1.0, 1.0)

            y0 = self.algorithm(xs, ys, x0)
            bi0 = barycentric_interpolate(xs, ys, x0)

            self.assertAlmostEqual(bi0, np.array(y0), 4)
Esempio n. 14
0
    def test_f(self):
        """Interpolation of function f with a polynomial p at the equidistant
        points x[k] = −1 + 2 * (k / n), k = 0, ..., n."""

        n = 20  # n points, so polynomial would be of degree n - 1.
        xs = [-1 + 2 * (k / n) for k in range(n)]
        ys = [f(x) for x in xs]

        for i in range(20):
            x0 = uniform(-1.0, 1.0)

            y0 = self.algorithm(xs, ys, x0)
            bi0 = barycentric_interpolate(xs, ys, x0)

            # f0 = f(x0)
            # e0 = fabs(y0 - f(x0))
            # print("e(%d) = %f\n" % (x0, e0))

            self.assertTrue(isclose(bi0, y0))
Esempio n. 15
0
 def __call__(self, x):
     return _interpolate.barycentric_interpolate(self.x, self.y, x)
from numpy.polynomial import chebyshev
import numpy as np
from scipy.interpolate import barycentric_interpolate


def runge(x):
    """Función de Runge."""
    return 1 / (1 + 25 * x**2)


N = 3  # Nodos de interpolación
xp = array([3, 8, 20])
fp = runge(xp)
x = np.linspace(0, 20)
y = barycentric_interpolate(xp, fp, x)
#-------
from numpy.polynomial import chebyshev
coeffs_cheb = [0] * 3 + [1]
T3 = chebyshev.Chebyshev(coeffs_cheb, [0, 20])
xp_ch = T3.roots()
plt.loglog(Re, cD, 'o', newRe, newcD,
           '-')  # first plot is circles, new plot is dashes
plt.title('Re vs cD on loglog scale')
plt.xlabel('logRe')
plt.ylabel('logcD')

print "\n\n Cubic spline interpolation results:"  # printing the numerical value of the function at the given new Re values when using the cubic spline interpolation

print "Value at Re = 5: " + (str(f(5)))
print "Value at Re = 50: " + (str(f(50)))
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
    return 1 / (1 + 25 * x**2)


# fine grid for plotting
x_fine = np.linspace(-1, 1, 1000)

# draw the true function
plt.plot(x_fine, runge_fn(x_fine), '--')

if USE_CHEB:
    ns = (10, 20, 30)
else:
    ns = (6, 10, 12, 16)

for n in ns:

    # interpolation points
    if USE_CHEB:
        zi = np.linspace(0, 1, n)
        xi = -1 + (1 + np.cos(np.pi * (1 - zi)))
    else:
        xi = np.linspace(-1, 1, n)
    yi = runge_fn(xi)

    # interpolate the function
    y_fine = barycentric_interpolate(xi, yi, x_fine)

    plt.plot(x_fine, y_fine, label='n = {}'.format(n))

plt.legend()
plt.show()
Esempio n. 19
0
    np.save('ion.npy', ion)
    np.save('lz.npy', lz)
    np.save('dm.npy', dm)
    dm = 1 - dm
else:
    ion = np.load('ion.npy')
    lz = np.load('lz.npy')
    dm = 1 - np.load('dm.npy')

trace = np.einsum('abb->a', dm)
for a, b in zip(ion, trace):
    print(f'{a}  :  {2*b.real}  :  {a-2*b.real}')

cycles_up = np.linspace(min_cycles, max_cycles, 1000)
ion_up = barycentric_interpolate(cycles_sweep, ion, cycles_up)
lz_up = barycentric_interpolate(cycles_sweep, lz, cycles_up)
dm_up = barycentric_interpolate(cycles_sweep, dm, cycles_up, axis=0)

diagonal = np.einsum('abb->ab', dm_up).real
right = (diagonal[:, 2] + diagonal[:, 3]) / 2 + dm_up[:, 2, 3].imag
left = (diagonal[:, 2] + diagonal[:, 3]) / 2 - dm_up[:, 2, 3].imag
diagonal[:, 2] = right
diagonal[:, 3] = left

labels = [
    r'2$\sigma_g$', r'2$\sigma_u$', r'1$\pi_{u+}$', r'1$\pi_{u-}$',
    r'3$\sigma_g$'
]
linestyles = reversed(['-', '--', ':', '-.', '-'])
for d, l, ls in reversed(list(zip(np.transpose(diagonal), labels,
def runge_function(x: float) -> float:
    return 1 / (1 + 25 * x * x)


# Number of datapoints (nodes) to sample from
node_count = 40

spaced_x = np.array(chebyshev_nodes(node_count))
uniform_x = np.linspace(-1, 1, node_count)

interp_cheb_x = np.linspace(min(spaced_x), max(spaced_x), 150)
interp_uniform_x = np.linspace(min(uniform_x), max(uniform_x), 150)
actual_x = np.linspace(-1, 1, 150)

chebyshev_y = barycentric_interpolate(spaced_x, runge_function(spaced_x), interp_cheb_x)
uniform_y = barycentric_interpolate(uniform_x, runge_function(uniform_x), interp_uniform_x)
actual_y = runge_function(actual_x)

# Plotting code
fig, (ax1, ax2) = plt.subplots(nrows=2)

ax1.plot(actual_x, actual_y, 'k')
ax1.plot(interp_cheb_x, chebyshev_y, '--r')
ax2.plot(actual_x, actual_y, 'k')
ax2.plot(interp_uniform_x, uniform_y, '--b')
ax2.set(ylim=(-1, 1.2))

ax1.grid()
ax2.grid()
Esempio n. 21
0
 def __call__(self, x):
     return _interpolate.barycentric_interpolate(self.x, self.y, x)
Esempio n. 22
0
 def test_int_input(self):
     x = 1000 * np.arange(1, 11)  # np.prod(x[-1] - x[:-1]) overflows
     y = np.arange(1, 11)
     value = barycentric_interpolate(x, y, 1000 * 9.5)
     assert_almost_equal(value, 9.5)
Esempio n. 23
0
print(ionization_all)
print('lz_all', lz_all.shape)
print('ionization_all', ionization_all.shape)

lz_all = np.concatenate([np.flip(lz_all, axis=0), [0], lz_all])
ionization_all = np.concatenate(
    [np.flip(ionization_all, axis=0), [0], ionization_all])

intens_test = 1e13 * np.sin(0.5 * np.pi * np.array(range(1, 9)) / 8)**4

efield_low = -np.cos(0.5 * np.pi * np.array(range(0, 17)) / 8)
intens_low = 1e13 * efield_low**2
intens_high = np.geomspace(1e11, 1e13, 100)
efield_high = np.sqrt(intens_high / 1e13)

lz_high = barycentric_interpolate(efield_low, lz_all, efield_high)
ionization_high = barycentric_interpolate(efield_low, ionization_all,
                                          efield_high)

ratio = 0.8
plt.figure(figsize=(6.4 * ratio, 4.8 * ratio))
#final_ionization = np.sum(ionization_high,axis=1)*time_step
#final_lz = lzAll_high[:,-1]
duration = 202.58
rabi_freq = efield_high * 1.81 * np.sqrt(1e13 / (3.51e16))
few_level = 0.78 * np.sin(0.25 * duration * rabi_freq)**2
plt.semilogx(intens_high, lz_high)
plt.semilogx(intens_high, few_level, linestyle='--')
plt.semilogx(intens_high, ionization_high, linestyle=':')
plt.semilogx(intens_low[-8:],
             ionization_all[-8:],
Esempio n. 24
0
def interpola(l, inferior, superior):
    """
    ---------------------------------------------------------------------
    Recibe las lineas con la informacion a interpolar.
    La primera linea es el dato TLE y las otras dos son las lineas
    de los datos CODS cuyas fechas encierran a la fecha del TLE.

    ---------------------------------------------------------------------
    input
        l: cadena con fecha hora x y z vx vy vz (str)
        inferior: cadena con fecha hora x y z vx vy vz (str)
        superior: cadena con fecha hora x y z vx vy vz (str)
    output
        lineaInterpol: cadena con fecha & hora(TLE) + datos interpolados 
    """

    lcampos = l.split()
    dicampos = inferior.split()
    dscampos = superior.split()
    # fecha inferior
    di = inferior[:19]
    di = datetime.strptime(di, '%Y/%m/%d %H:%M:%S')
    di_int = toTimestamp(di)
    #fecha superior
    ds = superior[:19]
    ds = datetime.strptime(ds, '%Y/%m/%d %H:%M:%S')
    ds_int = toTimestamp(ds)
    #fecha tle
    dt = l[:19]
    dt = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
    dt_int = toTimestamp(dt)

    x_array = [di_int, ds_int]
    x_new = dt_int
    # Interpolacion en x
    fx_array = [float(dicampos[2]), float(dscampos[2])]
    yx_new = barycentric_interpolate(x_array, fx_array, x_new)

    # Interpolacion en y
    fy_array = [float(dicampos[3]), float(dscampos[3])]
    yy_new = barycentric_interpolate(x_array, fy_array, x_new)

    # Interpolacion en z
    fz_array = [float(dicampos[4]), float(dscampos[4])]
    yz_new = barycentric_interpolate(x_array, fz_array, x_new)
    #    lineaInterpol=lcampos[0]+' '+lcampos[1]+' '+str(yx_new)+' '+str(yy_new)+' '+str(yz_new)+'\n'

    # Interpolacion en vx
    fvx_array = [float(dicampos[5]), float(dscampos[5])]
    yvx_new = barycentric_interpolate(x_array, fvx_array, x_new)

    # Interpolacion en vy
    fvy_array = [float(dicampos[6]), float(dscampos[6])]
    yvy_new = barycentric_interpolate(x_array, fvy_array, x_new)

    # Interpolacion en vz
    fvz_array = [float(dicampos[7]), float(dscampos[7])]
    yvz_new = barycentric_interpolate(x_array, fvz_array, x_new)
    lineaInterpol = lcampos[0] + ' ' + lcampos[1] + ' ' + str(
        yx_new) + ' ' + str(yy_new) + ' ' + str(yz_new) + ' ' + str(
            yvx_new) + ' ' + str(yvy_new) + ' ' + str(yvz_new) + '\n'

    return lineaInterpol
Esempio n. 25
0
import numpy as np
import polyFit
import scipy
from scipy import interpolate
import matplotlib.pyplot as plt

h=[0.0,1.525,3.050,4.575,6.1,7.625,9.15] #x values
den=[1,0.8617,0.7385,0.6292,0.5328,0.4481,0.3741] #y values
hrang=np.linspace(0,9.15,100)

print 'Using Polynomial Interpolation: ', '\n'

l_001=interpolate.barycentric_interpolate(h,den,(2,5)) #Using interpolate from scipy. Uses barycentric polynomial interpolation. Arguments: (x values, y values, points at which you wish to evaluate)

print 'At 2km the density of air will be ', l_001[0]

print 'At 5km the density of air will be ', l_001[1]

###
print '\n', 'Using Cubic Splines: ', '\n'

l_002=interpolate.interp1d(h,den,kind='cubic') #Interpolatioon from scipy. Uses cubic splines. Arguments: (x values, y values, order of splines)

print 'At 2km the density of air will be ', l_002(2) #Calls for interpolation to be evaluated at argument

print 'At 5km the density of air will be ', l_002(5)


###

print '\n', 'Using Least Squares Fit: ', '\n'
Esempio n. 26
0
import numpy as np
import polyFit
import scipy
from scipy import interpolate
import matplotlib.pyplot as plt

h = [0.0, 1.525, 3.050, 4.575, 6.1, 7.625, 9.15]  #x values
den = [1, 0.8617, 0.7385, 0.6292, 0.5328, 0.4481, 0.3741]  #y values
hrang = np.linspace(0, 9.15, 100)

print 'Using Polynomial Interpolation: ', '\n'

l_001 = interpolate.barycentric_interpolate(
    h, den, (2, 5)
)  #Using interpolate from scipy. Uses barycentric polynomial interpolation. Arguments: (x values, y values, points at which you wish to evaluate)

print 'At 2km the density of air will be ', l_001[0]

print 'At 5km the density of air will be ', l_001[1]

###
print '\n', 'Using Cubic Splines: ', '\n'

l_002 = interpolate.interp1d(
    h, den, kind='cubic'
)  #Interpolatioon from scipy. Uses cubic splines. Arguments: (x values, y values, order of splines)

print 'At 2km the density of air will be ', l_002(
    2)  #Calls for interpolation to be evaluated at argument

print 'At 5km the density of air will be ', l_002(5)
plt.title('Re vs cD on loglog scale')
plt.xlabel('logRe')
plt.ylabel('logcD')

print "\n\n Cubic spline interpolation results:" # printing the numerical value of the function at the given new Re values when using the cubic spline interpolation

print "Value at Re = 5: " + (str(f(5)))
print "Value at Re = 50: " + (str(f(50)))
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
Esempio n. 28
0
    proj_low.append(ionization)
    #proj_low.append(1-np.sum(proj_low,axis=0))
    proj_low = np.array(proj_low)
    proj_low = np.concatenate([
        np.transpose(np.array([[0, 1, 0, 0, 0], [0, 1, 0, 0, 0]]))[:, None, :],
        proj_low
    ],
                              axis=1)
    print(proj_low.shape)

    efield_low = np.sin(0.5 * np.pi * np.array(range(0, 9)) / 8)
    intens_low = 1e13 * efield_low**2
    intens_high = np.linspace(0, 1e13, 100)

    proj_high = barycentric_interpolate(intens_low,
                                        proj_low,
                                        intens_high,
                                        axis=1)

    fig, axs = plt.subplots(1, 2, sharey=True)
    axs[0].plot(intens_high, proj_high[1, :, 0], label='H**O')
    axs[0].plot(intens_high, proj_high[2, :, 0], label='LUMO', linestyle='--')
    axs[0].plot(intens_high,
                proj_high[4, :, 0],
                label='Ionized',
                linestyle=':')
    other_right = 1 - proj_high[1, :, 0] - proj_high[2, :, 0] - proj_high[4, :,
                                                                          0]
    axs[0].plot(intens_high, other_right, label='Other', linestyle='-.')
    axs[0].plot(intens_low[1:],
                proj_low[1, 1:, 0],
                linestyle='None',
Esempio n. 29
0
def runge_function(x: float) -> float:
    return 1 / (1 + 25 * x * x)


fig, ax = plt.subplots()
fig.set_tight_layout(True)
ax.grid()

x = np.linspace(-1, 1, 200)

# Persistent
ax.plot(x, runge_function(x), 'k')

n = 2
samples = chebyshev_nodes(n)
interpolated = barycentric_interpolate(samples, runge_function(samples), x)

# To be updated
points, = ax.plot(samples, runge_function(samples), 'or')
fit, = ax.plot(x, interpolated, ':b')
text = ax.text(-1.08, 0.81, f'{n} uniform nodes')

print(points)
print(fit)


def update(n: int):
    label = f'{n} Chebyshev distributed nodes'
    print(label)

    samples = chebyshev_nodes(n)
Esempio n. 30
0
from pylab import *
from scipy import interpolate, optimize
from numpy import *

# construct data point arrays first
h = array([0.0, 1.525, 3.050, 4.575, 6.100, 7.625, 9.150])
rho = array([1.0, 0.8617, 0.7385, 0.6292, 0.5328, 0.4481, 0.3741])

# Part A
# use Barycentric initally as the most direct path to an answer
print "At 2km, the polynomial, interpolated value is:"
print(str(interpolate.barycentric_interpolate(h, rho, 2.0)))

print "And at 4km, the interpolated value is:"
print(str(interpolate.barycentric_interpolate(h, rho, 4.0)))

print "And at 8km, the interpolated value is:"
print(str(interpolate.barycentric_interpolate(h, rho, 8.0)))

# B: cubic spline
fit = interpolate.interp1d(h, rho,
                           kind='cubic')  #set up fit, called as fit(value)

print "At h=2, h=4 and h=8 respectively, using a cubic spline, rho="
print fit(2.0), ", ", fit(4.0), ", ", fit(8.0)

# C: errors
rho_actual = 0.67

print "Absolute error for polynomial interpolation:"
err_abso_poly = np.abs(
Esempio n. 31
0
 def test_wrapper(self):
     P = BarycentricInterpolator(self.xs, self.ys)
     values = barycentric_interpolate(self.xs, self.ys, self.test_xs)
     assert_almost_equal(P(self.test_xs), values)
Esempio n. 32
0
from pylab import *
from scipy import interpolate, optimize
from numpy import *

# construct data point arrays first
h = array([0.0,1.525,3.050,4.575,6.100,7.625,9.150])
rho = array([1.0,0.8617,0.7385,0.6292,0.5328,0.4481,0.3741])


# Part A
# use Barycentric initally as the most direct path to an answer
print "At 2km, the polynomial, interpolated value is:"
print(str(interpolate.barycentric_interpolate(h,rho,2.0)))

print "And at 4km, the interpolated value is:"
print(str(interpolate.barycentric_interpolate(h,rho,4.0)))

print "And at 8km, the interpolated value is:"
print(str(interpolate.barycentric_interpolate(h,rho,8.0)))


# B: cubic spline
fit = interpolate.interp1d(h,rho,kind='cubic') #set up fit, called as fit(value)

print "At h=2, h=4 and h=8 respectively, using a cubic spline, rho="
print fit(2.0), ", ", fit(4.0), ", ",fit(8.0)


# C: errors
rho_actual = 0.67
Esempio n. 33
0
 def test_wrapper(self):
     P = BarycentricInterpolator(self.xs,self.ys)
     assert_almost_equal(P(self.test_xs),barycentric_interpolate(self.xs,self.ys,self.test_xs))
Esempio n. 34
0
def plot(self, fx, a=-1, b=1, n=1000):
    x = np.linspace(a, b, n)
    T = sp_interp.barycentric_interpolate(self.chebNodes(n=fx.size, a=a, b=b), fx, x)
    plt.plot(x, T)