def interpolation_matrix_1d(fine_grid, coarse_grid, k=2, return_type="csc", periodic=False, T=1.0): """ We construct the interpolation matrix between two 1d grids, using lagrange interpolation. :param fine_grid: a one dimensional 1d array containing the nodes of the fine grid :param coarse_grid: a one dimensional 1d array containing the nodes of the coarse grid :param k: order of the restriction :return: a interpolation matrix """ M = np.zeros((fine_grid.size, coarse_grid.size)) n_f = fine_grid.size for i, p in zip(range(n_f), fine_grid): if periodic: nn,cont_arr = next_neighbors_periodic(p, coarse_grid, k, T) circulating_one = np.asarray([1.0]+[0.0]*(k-1)) lag_pol = [] for l in range(k): lag_pol.append(intpl.lagrange(cont_arr, np.roll(circulating_one, l))) M[i, nn] = np.asarray(map(lambda x: x(p), lag_pol)) else: nn = next_neighbors(p, coarse_grid, k) # construct the lagrange polynomials for the k neighbors circulating_one = np.asarray([1.0]+[0.0]*(k-1)) lag_pol = [] for l in range(k): lag_pol.append(intpl.lagrange(coarse_grid[nn], np.roll(circulating_one, l))) M[i, nn] = np.asarray(map(lambda x: x(p), lag_pol)) return to_sparse(M, return_type)
def print_table_at_segment_for_g_and_fs(x_segment, xs): fs = map(lambda x: mega_f(x), xs[:]) gs = map(lambda x: mega_g(x), xs[:]) #using the x_i = x_i to make python to close over the value of x_i and not, the name that is "lazy watched" once omega = [(lambda x, x_i=x_i : x - x_i) for x_i in xs] f_lagrange = construct_Lagrange_polynomial(xs, fs, omega) g_lagrange = construct_Lagrange_polynomial(xs, gs, omega) p = sci.lagrange(xs, fs) q = sci.lagrange(xs, gs) #checking the results for i in range(len(xs)): assert abs(eval_Lagrange(g_lagrange, xs[i]) - gs[i]) < float_difference assert p(xs[i]) - eval_Lagrange(f_lagrange, xs[i]) < float_difference assert q(xs[i]) - eval_Lagrange(g_lagrange, xs[i]) < float_difference # our interpolation degree n = len(omega) # prepare lambda functions for absolute of (n+1 derivatives) of f and g abs_nth_der_f = lambda x, n=n, der1=nth_dif_of_cos(n + 1, float(1)/3), der2=nth_dif_of_sin(n + 1, float(1)/2): abs(der1(x) - der2(x)) abs_nth_der_g = lambda x, n=n, g1=nth_dif_of_cos(n + 1, float(5)) : abs(g1(x)) #calculate their max values max_f_der_value = stupid_max(abs_nth_der_f, x_segment) assert max_f_der_value >= 0 max_g_der_value = stupid_max(abs_nth_der_g, x_segment) assert max_g_der_value print abs_nth_der_f(0) >= 0 print "Max values: |f`", n,"|", max_f_der_value, " ; |g`",n,"|", max_g_der_value #construct As A_f = lambda x, omega=omega : (abs(numpy.prod(map(lambda factor : factor(x), omega))) * max_f_der_value) / float(factorial(n + 1)) A_g = lambda x : (abs(numpy.prod(map(lambda factor : factor(x), omega))) * max_g_der_value) / float(factorial(n + 1)) # prepare yourself for iterating h = float(x_segment[-1] - x_segment[0]) / float(part_amount) print h #Print the target tables header = "-" * 11 + "Table for F at" + str(x_segment) + "-" *11 print header print "-" * len(header) print_table(x_segment, h, mega_f, f_lagrange, A_f) print "-" * len(header) print header = "-" * 11 + "Table for G at" + str(x_segment) + "-" * 11 print header print "-" * len(header) print_table(x_segment, h, mega_g, g_lagrange, A_g) print "-" * len(header) #plotting f_eval = lambda x : mega_f(x) g_eval = lambda x : mega_g(x) f_lagr_eval = lambda x: eval_Lagrange(f_lagrange, x) g_lagr_eval = lambda x: eval_Lagrange(g_lagrange, x) #f_lagr_eval = lambda x, f=f_lagrange: numpy.sum(map(lambda factor: factor(x), f_lagrange)) mpmath.plot([f_eval, f_lagr_eval], x_segment) mpmath.plot([g_eval, g_lagr_eval], x_segment)
def return_polynomial_coefficients(curve_list): xdata = [x[0] for x in curve_list] ydata = [x[1] for x in curve_list] np.set_printoptions(precision=6) np.set_printoptions(suppress=True) p = interpolate.lagrange(xdata, ydata) return p
def _pd(self): m2, m3, nd, ld, type = self._m2, self._m3, self._nd, self._ld, self._type if type == 1: dx = ld/(nd-1) p02 = Point(0, 1.0) dy1 = m2*dx p12 = p02 + Point(dx, dy1, 0.0, 0.0) pn2 = Point( ld, self._Aout) dy2 = m3*dx pn_12 = pn2 - Point(dx, dy2, 0.0, 0.0) pint = [p02, p12, pn_12, pn2] n = len(pint) x = np.ones(n) y = np.ones(n) for i in xrange(n): x[i], y[i], nul1, nul2 = pint[i].split() xp = np.ones(nd) for i in xrange(nd): xp[i] = i*dx from scipy import interpolate f = interpolate.lagrange(x, y) yp = f(xp) # print x, y # print xp, yp # f = interpolate.interp1d(x, y) pct = [] for i in xrange(nd): pct.append(Point(xp[i], yp[i])) # pct.append(pn1) return pct
def ployinterp_column(s,n,k=5): # 取数 y = s[list(range(n-k,n))+list(range(n+1,n+1+k))] # 删除空值 y = y[y.notnull()] # 插值并返回插值结果 return lagrange(y.index,list(y))(n)
def _interpolate_boundary_constraints(self, ts): stage_starts = [0.] for i in xrange(self.nk-1): stage_starts += [self.var.h_op[self._get_stage_index(i)] + stage_starts[-1]] stage_starts = pd.Series(stage_starts) stages = stage_starts.searchsorted(ts, side='right') - 1 for ki in range(self.nk): for ji in xrange(1, self.d+1): x = {met : var_op for met, var_op in zip(self.boundary_species, self.var.x_op[k,j])} interp = lagrange(self.col_vars['tau_root'], (self.col_vars['C'].T.dot( self.var.x_op[ki, :, ni]) / self.var.h_op[self._get_stage_index(ki)])) out[stages == ki, ni] = interp( (ts[stages == ki] - stage_starts[ki]) / self.var.h_op[self._get_stage_index(ki)]) return out
def intgl_simp38(f,a,b,steps=-1,h=1): if steps>0: xis = np.linspace(a,b,steps+1) h = xis[1]-xis[0] fxis = f(xis) wis = np.zeros(steps+1) pcs = []; fpcs = [] for i in xrange(0,steps-2,3): wis[i:i+4] += [1,3,3,1] pcs.append(xis[i:i+4]) fpcs.append(fxis[i:i+4]) wis *= 3*h/8 if steps%3==2: wis[-3:] += [h/3,4*h/3,h/3] pcs.append(xis[-3:]) fpcs.append(fxis[-3:]) elif steps%3==1: wis[-2:] += [h/2,h/2] pcs.append(xis[-2:]) fpcs.append(fxis[-2:]) fapprox = lambda x: np.piecewise(x, [np.logical_and(p[0]<=x,x<=p[-1]) for p in pcs], [lagrange(pcs[i],fpcs[i]) for i in xrange(len(pcs))])# np.interp(x,xis,fxis) # fapprox = lambda x: np.interp(x,xis,fxis) return (sum(fxis*wis),xis,fxis,wis,fapprox) # h/2 * sum(np.array([f(x) for x in xs]) * np.array([1]+[2]*(len(xs)-2)+[1]))
def test_interp_telles(): # The problem I solve: # exact is from mathematica sing_pt = 1.005; denom = lambda x: (sing_pt - x) ** 2; numer = lambda x: x ** 3; f = lambda x: numer(x) / denom(x); exact_f = lambda s: (s * (-4 + 6 * s ** 2 - 3 * s * (-1 + s ** 2) * \ (log((-1 - s) / (1 - s))))) / (-1 + s ** 2) exact = exact_f(sing_pt) # Solved with standard Telles quadrature x_nearest = 1.0; D = sing_pt - 1.0; N = 14; [tx, tw] = telles_quasi_singular(N, x_nearest, D); est_telles = np.sum(f(tx) * tw) # Solved with gauss quadrature [gx, gw] = gaussxw(N) est_gauss = np.sum(f(gx) * gw) # Solved with interpolation and Telles quadrature # X = Interpolation Points X = gx; # Y = Value of function at the interpolation points Y = f(gx) * denom(gx); # WARNING, WARNING, WARNING: This implementation of lagrange interpolation # is super unstable. I just downloaded it from somewhere online. A # reimplementation using barycentric Lagrange interpolation is necessary to # go above N = appx 20. P = spi.lagrange(X, Y) est_interp_telles = sum(P(tx) / denom(tx) * tw) np.testing.assert_almost_equal(est_telles, est_interp_telles)
def _find_coefficients(self): polynomials = [] for curve in self.curves: xdata = [x[0] for x in curve] ydata = [x[1] for x in curve] p = interpolate.lagrange(xdata, ydata) polynomials.append(p) return polynomials
def intgl_glquad(f,a,b,n): ans = spintegrate.fixed_quad(f,a,b,n=n) xis,wis = np.polynomial.legendre.leggauss(n) # print(xis,wis) xis = (b+a)/2 + (b-a)/2*xis fxis = f(xis) wis = (b-a)/2*wis return (ans[0],xis,fxis,wis,lagrange(xis,fxis))
def lagrangeBasis(self, x): "Returns lagrange interpolant which has value 1 in x" xGrid = self.getList() yGrid = [0]*len(self.wnodes) i = xGrid.index(x) yGrid[i] = 1 return lagrange(xGrid, yGrid)
def card_poly(k): x = [] y = [] for i in range(k + 1): n = k + 2 + i x.append(n) y.append(Ank.card_ank(n, k)) p = si.lagrange(x, y) return p
def _interpol_init_guess(self): Pig = self._Pig n = len(Pig) x = np.ones(n) y = np.ones(n) for i in xrange(n): x[i], y[i], nul1, nul2 = Pig[i].split() from scipy import interpolate f = interpolate.lagrange(x, y) self._yp = f(self._xp)
def interpolate(self, mode=InterpolateMode.LAGRANGE): xy = self.asarray() if mode == InterpolateMode.LAGRANGE or mode is None: delegate = interpolate.lagrange(xy.T[0], xy.T[1]) else: kind = InterpolateMode(mode).to_string() delegate = interpolate.interp1d(xy.T[0], xy.T[1], kind=kind) self.delegate = delegate return self
def matrixN(tau, rows=-1, last_value=1.0): n = tau.shape[0] if rows == -1: rows = n N = np.zeros((rows, n)) # construct the lagrange polynomials circulating_one = np.asarray([1.0]+[0.0]*(n-1)) lag_pol = [] for i in range(n): lag_pol.append(intpl.lagrange(tau, np.roll(circulating_one, i))) N[:, i] = -np.ones(rows)*lag_pol[-1](last_value) return N
def lazy(): from scipy import interpolate x = list(range(1, 11)) y = [u(n) for n in range(1, 11)] FITs = 0 for d in range(1, 11): z = interpolate.lagrange(x[:d], y[:d]) FITs += round(z(d+1)) return FITs
def updateApproximation(self): self.logger.debug('') self.logger.debug('entering updateApproximation') self.logger.debug('self.x = \n%s' % self.x) self.logger.debug('self.fx = \n%s' % self.fx) if len(self.x[0]) == 1: # we are dealing with the one-dimensional case self.logger.debug('self.x[0] == 1') xIn = self.sorted_x.copy() fIn = self.sorted_fx.copy() withinDistance = ( self.sortedNormedDistances[1] / self.sortedNormedDistances ) < 10 withinDistance[0] = True # need at least two values withinDistance[1] = True # if self.protected_ix: self.logger.debug('protected exists') try: lenProtected_ix = len(self.protected_ix) except: lenProtected_ix = 1 actual_nIntpoints_max = self.nIntpoints_max - lenProtected_ix withinDistance[self.protected_ix] = True # protected_ix must always be carried over else: self.logger.debug('protected doesnt exist') actual_nIntpoints_max = self.nIntpoints_max actual_nIntpoints = np.min([actual_nIntpoints_max, len(xIn)]) self.logger.debug('actual_nIntpoints = %s' % actual_nIntpoints) self.logger.debug('len(xIn) = %s' % len(xIn)) withinMaxIntpoints = np.array([ True ] * actual_nIntpoints + [ False ] * ( len(xIn) - actual_nIntpoints ) ) withinMaxIntpoints[self.protected_ix] = True self.logger.debug('withinMaxIntpoints = %s' % withinMaxIntpoints) self.logger.debug('withinDistance = %s' % withinDistance) self.intPoints_ix = withinMaxIntpoints * withinDistance xIn = xIn[self.intPoints_ix] fIn = fIn[self.intPoints_ix] self.logger.debug('after nIntpoints xIn = %s \n' % xIn) self.logger.debug('after nIntpoints fIn = %s \n' % fIn) self.logger.debug('transforming fIn:') fIn = np.log((1. - self.target_fx) + fIn) self.logger.debug('sending xIn = %s to lagrange\n' % xIn) self.logger.debug('sending fIn = %s to lagrange\n' % fIn) ### create approximation ### self.gx = si.lagrange(xIn[:, 0], fIn) ### -------------------- ### else: self.logger.debug('multi-dimensional case not implemented... exiting') os._exit(1) if self.makePlots: self.plot() self.logger.debug('done updating approximation') self.logger.debug('')
def join(self, parts): secret = '' pieces = zip(*parts) for piece in pieces: domains = [d for (d, r) in piece] ranges = [r for (d, r) in piece] poly = interpolate.lagrange(domains, ranges) # Convert an integer into a hexidecimal string, less the leading '0x' # part added by the `hex` built-in. constant = hex(int(poly.coeffs[poly.order]))[2:] # Add padding in case it is missing. if len(constant) % 2: constant = '0' + constant secret += binascii.unhexlify(constant) return base64.urlsafe_b64encode(secret)
def interpolate_to_t_end(nodes_on_unit, values): """ Assume a GaussLegendre nodes, we are interested in the value at the end of the interval, but we now only the values in the interior of the interval. We compute the value by legendre interpolation. :param nodes_on_unit: nodes transformed to the unit interval :param values: values on those nodes :return: interpolation to the end of the interval """ n = nodes_on_unit.shape[0] circulating_one = np.asarray([1.0]+[0.0]*(n-1)) lag_pol = [] result = np.zeros(values[0].shape) for i in range(n): lag_pol.append(intpl.lagrange(nodes_on_unit, np.roll(circulating_one, i))) result += values[i]*lag_pol[-1](1.0) return result
def _interpolate_solution(self, ts): h = self.tf / self.nk stage_starts = pd.Series(h * np.arange(self.nk)) stages = stage_starts.searchsorted(ts, side='right') - 1 out = np.empty((len(ts), self.nx)) for ki in range(self.nk): for ni in range(self.nx): interp = lagrange(self.col_vars['tau_root'], self.var.x_op[ki, :, ni]) out[stages == ki, ni] = interp( (ts[stages == ki] - stage_starts[ki])/h) return out
def interpolate2(self, fubar, timing, interp): l = len(fubar) x = np.linspace(0, l-1, num=l, endpoint=True) y = fubar # f = interp1d(x,y) if interp == 'cubic' or interp == 'linear': f2 = interp1d(x,y, kind=interp) elif interp == 'lagrange': f2 = lagrange(x, y) else: raise ValueError('Invalid interpolation type!') steps = 0 for t in timing['Timer']: steps += int(t * 8/50.0) xnew = np.linspace(0, l-1, num=steps, endpoint=True) fx = [self.mapp(f) for f in f2(xnew)] return fx
def _interpolate_solution(self, ts): out = np.empty((len(ts), self.nx)) stage_starts = [0.] for i in xrange(self.nk-1): stage_starts += [self.var.h_op[self._get_stage_index(i)] + stage_starts[-1]] stage_starts = pd.Series(stage_starts) stages = stage_starts.searchsorted(ts, side='right') - 1 for ki in range(self.nk): for ni in range(self.nx): interp = lagrange(self.col_vars['tau_root'], self.var.x_op[ki, :, ni]) out[stages == ki, ni] = interp( (ts[stages == ki] - stage_starts[ki]) / self.var.h_op[self._get_stage_index(ki)]) return out
def integrate1d_romberg(f,a,b,N): if a == b: return 0 k = np.log2(N) if not k % 1 == 0: raise ValueError("N has to be a power of 2") k = int(k) h = b - a tf = h*(f(a)+f(b))/2. h_list = [h] tf_list = [tf] for i in range(0,k): tf = 0.5*tf + 0.5 * h * sum(f(a+(np.arange(0,2**i) + 0.5)*h)) h *= 0.5 tf_list.append(tf) h_list.append(h) tf = np.array(tf_list) h = np.array(h_list) return lagrange(h**2, tf)(0)
def intgl_simp13(f,a,b,steps=-1,h=1): if steps>0: xis = np.linspace(a,b,steps+1) h = xis[1]-xis[0] fxis = f(xis) wis = np.zeros(steps+1) pcs = []; fpcs = [] for i in xrange(0,steps-1,2): wis[i:i+3] += [1,4,1] pcs.append(xis[i:i+3]) fpcs.append(fxis[i:i+3]) wis *= h/3 if steps%2: wis[-2:] += [h/2.0,h/2.0] pcs.append(xis[-2:]) fpcs.append(fxis[-2:]) # print(wis) fapprox = lambda x: np.piecewise(x, [np.logical_and(p[0]<=x,x<=p[-1]) for p in pcs], [lagrange(pcs[i],fpcs[i]) for i in xrange(len(pcs))])# np.interp(x,xis,fxis) return (sum(fxis*wis),xis,fxis,wis,fapprox) # h/2 * sum(np.array([f(x) for x in xs]) * np.array([1]+[2]*(len(xs)-2)+[1]))
def basis_from_nodes(nodes): """ Create a interpolated polynomial basis from arbitrary nodes. """ n_fncs = len(nodes) fncs = np.empty((n_fncs, n_fncs)) derivs = np.empty((n_fncs, n_fncs)) for (i, n) in enumerate(nodes): w = np.zeros_like(nodes) w[i] = 1.0 # scipy.interpolate.lagrange has trouble above 20 nodes, but that # shouldn't be an issue for this code poly = spi.lagrange(nodes, w) fncs[i, :] = poly.c derivs[i, 0] = 0.0 derivs[i, 1:] = poly.deriv().c point_sources = [] point_sources.append([0.0, 1.0, 1.0]) point_sources.append([1.0, 1.0, 1.0]) point_source_dependency = [0, n_fncs - 1] return PolyBasis(fncs, derivs, point_sources, point_source_dependency, nodes)
def t_interpol(): print 'interpol...' def test_it(expected, result, max_error): max_diff = max(abs(expected-result)) if max_diff < max_error: print 'OK' else: print 'FAIL' print ' Expected:', expected print ' Got:', result print ' Difference:', max_diff print ' Tolerance:', max_error # How much can the tests differ from the expected results? Adjust # according to the method and data set used. max_error = 10**-6 print ' Lagrange...', # The function used in the testing, change it if you want def f(x): return numpy.sin(2*numpy.pi*x)+numpy.cos(3*numpy.pi*x) xs = numpy.arange(-1, 1, 10**-1) ys = f(xs) expected = numpy.array(interpolate.lagrange(xs, ys).c[::-1]) x = sympy.symbols('x') result_ = sympy.simplify(interpol.lagrange(x, xs, ys)) result = [] for i in xrange(len(expected)): result.append(result_.coeff(x, i)) result = numpy.array(result) test_it(expected, result, max_error)
def _pc(self): m1, m2, nc, lc, type = self._m1, self._m2, self._nc, self._lc, self._type """ equispaced control point along x """ if type == 1: dx = lc/(nc-1) dy1 = dx*m1 p01 = Point(-lc, self._Ain) p11 = p01 + Point(dx, dy1, 0.0, 0.0) pn1 = Point(0.0, 1.0) dy2 = dx*m2 pn_11 = pn1 - Point(dx,dy2, 0.0, 0.0) pint = [p01, p11, pn_11, pn1] n = len(pint) x = np.ones(n) y = np.ones(n) for i in xrange(n): x[i], y[i] = pint[i].split() xp = np.ones(nc) for i in xrange(nc): xp[i] = -lc + i*dx from scipy import interpolate f = interpolate.lagrange(x, y) yp = f(xp) # print x, y # print xp, yp # f = interpolate.interp1d(x, y) pct = [] for i in xrange(nc): pct.append(Point(xp[i], yp[i])) # pct.append(pn1) return pct
def ployinterp_column(s, n, k=3): y = s[list(range(n-k, n)) + list(range(n+1, n+1+k))] #取数 y = y[y.notnull()] #剔除空值 return lagrange(y.index, list(y))(n) # 最后的括号就是我们要插值的n
#Polinomio de lagrange punto 13, grado 2 import numpy as np from scipy.interpolate import lagrange import matplotlib.pyplot as plt x = np.array([4410000, 4830000, 5250000]) y = np.array([1165978, 1329190, 1501474]) polinomio = lagrange(x, y) xi = 5000000 yi = polinomio(xi) print(yi) xs = np.linspace(x.min(), x.max()) ys = polinomio(xs) plt.plot(x, y, 'o') plt.plot(xi, yi, 'sr') plt.plot(xs, ys, ':') plt.grid() plt.show()
def lagrangeMethod(): #Leer Xi del usuario #Los while validan que el usuario escriba un valor correcto while True: try: iteration_num = int(input('¿Cuantas iteraciones vas a calcular? ')) if iteration_num > 0: break else: print("O P C I Ó N N O V A L I D A") except ValueError: print("O P C I Ó N N O V A L I D A") print('Introduce los valores de Xi') Xi = np.array([0.00] * iteration_num) for i in range(0, iteration_num): while True: try: Xi[i] = float(input('Xi en la posición {}: '.format(i))) break except ValueError: print("O P C I Ó N N O V A L I D A") #Leer f(Xi) del usuario print('Introduce los valores de f(Xi)') fXi = np.array([0.00] * iteration_num) for i in range(0, iteration_num): while True: try: fXi[i] = float(input('f(Xi) en la posición {}: '.format(i))) break except ValueError: print("O P C I Ó N N O V A L I D A") #Lee la posicion de X que busca el usuario while True: try: question = str(input('¿Deseas calcular algún valor? || Si/No ')) break except ValueError: print("O P C I Ó N N O V A L I D A") #Variables inicializadas work = False user_xi = 0 result = 0 if question.upper() == 'SI': while True: try: user_xi = float(input('¿Qué valor deseas calcular? ')) break except ValueError: print("O P C I Ó N N O V A L I D A") #Con resultado work = True #Aqui va el resultado result = calculate(Xi, fXi, user_xi) graph(Xi, fXi, user_xi, result, iteration_num, work) print('El resultado de f(Xi) en el punto Xi = {:.2f} es de {:.4f}'. format(user_xi, result)) else: #Sin resultado graph(Xi, fXi, user_xi, result, iteration_num, work) #Crea el polinomio en formato legible polynomial = lagrange(Xi, fXi) print('Polinomio') print(polynomial) print_table(Xi, fXi, iteration_num)
def gen_poly(y): x = range(0, len(y)) poly = lagrange(x, y) poly = [float(x) for x in reversed(poly.coefficients)] return poly
def levantar_polinomio_lagrange(dados_x, dados_y): polinomio = lagrange(dados_x, dados_y) return polinomio
def ploy(s, n, k=3): # 拉格朗日插值函数 y = s.reindex(list(range(n-k, n))+list(range(n+1, n+1+k))) # 取数 y = y[y.notnull()] return lagrange(y.index, list(y))(n)
def lagrangeInterp(x, y, x_interp): func = interpolate.lagrange(x, y) y_interp = func(x_interp) return y_interp
def ployinterp_column(s, n, k=5): y = s[list(range(n - k, n)) + list(range(n, n + k + 1))] y = y[y.notnull()] return lagrange(y.index, list(y))(n)
#function2 def f2(x): return (np.exp(np.cos(x))) #dense points x=np.linspace(-1,1,120) #uniform points n=12 x_uniform=np.linspace(-1,1,n) #chebyshev points x_chebyshev=np.zeros(n) for i in range(1,n+1): x_chebyshev[i-1]=np.cos((2*i - 1) * np.pi/(2*n)) # lagrange with uniform points lu=si.lagrange(x_uniform,f1(x_uniform)) # cubic spines with uniform points cs=si.CubicSpline(x_uniform,f1(x_uniform)) # lagrange with chebyshev points lc=si.lagrange(x_chebyshev,f1(x_chebyshev)) #plot plt.figure() o,=plt.plot(x,f1(x),label='original function with uniform points') lu,=plt.plot(x,lu(x),label='lagrange with uniform points') cs,=plt.plot(x,cs(x),label='cubic spines with uniform points') lc,=plt.plot(x,lc(x),label='lagrange with chebyshev points') plt.xlabel('x') plt.ylabel('f') plt.legend(handles=[o,lu,cs,lc],bbox_to_anchor=(0.6, 0.6)) plt.title('three interpolants and the original function')
x = [ 14.6, 14.7, 14.6, 14.8, 15.2, 15.6, 15.7, 17.0, 17.6, 17.5, 17.3, 16.8, 15.4, 14.8, 14.4, 14.5, 15.0, 15.1, 15.0, 14.9, 14.6, 14.3, 14.0, 13.9, 13.8, 13.5, 13.1, 13.0, 13.3, 13.2, 13.1, 12.9, 12.4, 11.9, 11.7, 11.6, 11.3, 10.9, 10.7, 10.6, 10.6, 10.1, 9.7, 9.4, 9.3, 9.6, 9.9, 10.1, 10.2, 10.3, 9.10, 8.6, 7.5, 7.0, 6.7, 6.6, 7.70, 8.00, 8.10, 8.40, 9.00, 9.30, 10, 10.2, 10.3, 10.0, 9.50 ] y = [ 14.7, 14.0, 13.4, 12.3, 11.0, 10.5, 10.2, 8.20, 7.10, 6.70, 6.60, 6.80, 8.30, 8.80, 9.30, 8.80, 6.30, 5.50, 5.00, 4.70, 4.60, 4.50, 4.90, 5.40, 5.80, 6.90, 8.20, 7.60, 5.80, 4.50, 4.30, 3.90, 4.20, 5.70, 7.00, 7.90, 8.20, 7.30, 6.70, 5.50, 5.10, 4.60, 4.7, 5.0, 5.5, 7.2, 7.8, 8.60, 9.40, 10.0, 10.7, 9.9, 9.0, 9.1, 9.3, 9.7, 11.7, 12.3, 12.5, 13.0, 13.9, 14.9, 16, 16.4, 16.8, 10.7, 11.0 ] f1 = lagrange(x[32:36], y[32:36]) x1 = np.linspace(x[32], x[35], 10) y1 = f1(x1) plt.plot(x1, y1, label='interpolación lagrange') plt.plot(x, y, 'x', mew=2, label='Datos') plt.xlabel("X") plt.ylabel("Y") plt.legend() plt.show()
def ployinterp_column(s, n, k=5): # s为列向量 n为被插值的位置 k代表取前后五个数据 y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 + k))] #取数 y = y[y.notnull()] #剔除空值 return lagrange(y.index, list(y))(n) #插值并返回结果
import matplotlib.pyplot as plt from scipy.interpolate import lagrange from sympy import * #Coordenadas de la funciones F(x) y G(x) x_f = [3, 0.5, -2] y_f = [0, 6.25, 0] x_g = [0.30278, -1.5, -3.3028] y_g = [0, -3.25, 0] x = symbols('x') #Interpolacion de las funciones fx = lagrange(x_f, y_f) gx = lagrange(x_g, y_g) print('interpo: ', fx) print('interpo: ', gx) #Busqueda de puntos de corte y conversion de poli1d a funcion expresionAB = fx - gx funcionAB = expresionAB.__call__(x) derivadaF = funcionAB.diff(x) print(funcionAB) #Declaracion del X inicial y tolerancia X0 = -5 Tol = 0.0001 cont_iteraciones = 0.0 err = 1.0 #Busqueda de raices de la funcion while (err > Tol) & (cont_iteraciones < 50.0):
]) # mejorCaso = np.array([1685.4,3848.8,7012,9205.8,10321.4,11572.8,10519.2,15604,12448.4,16273.6]) # peorCaso = np.array([639109,2.66626e+06,6.22243e+06,1.1447e+07,1.84727e+07,2.71582e+07,3.77588e+07,5.01973e+07,6.44684e+07,8.09294e+07]) # peorCaso = np.array([1457,2173,3109,4427,5207,6045,7091,7547,8605,9105,9955,10104,11430,12085,13260,14430,15644,16441,17814]) # mejorCaso = np.array([1015,1104,1269,1430,1685,2016,2162,3966,3956,3997,4695,4268,4567,4350,4493,4685,5925,5411,5685]) xdel1 = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) x1 = np.array([ 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000 ]) x2 = np.array([1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]) inter = lagrange(x2, Promedios) # peorCaso = np.array([0.000004,0.000016,0.000035,0.000038,0.000085,0.000207,0.000166,0.000208,0.00026,0.000406,0.000383,0.000493,0.000615]) # mejorCaso = np.array([0.000005,0.000004,0.000008,0.000009,0.000009,0.00001,0.000011,0.000011,0.000012,0.000013,0.000014,0.000016,0.000016]) # inter1 = lagrange(x2,mejorCaso) # , # inter2 = lagrange(x2,peorCaso) x = np.linspace(1, 100000, num=3000000, endpoint=True) # x, 0.3*x,'b-','b-',x2,inter2(x2),'ys-',x2,inter1(x2),'g*-', plt.plot(x, 0.01 * (x + (x * x) / 2), x2, inter(x2) / 100, 'r^-', x2, peorCaso / 100, 'ys-', x2, mejorCaso / 100, 'g*-', xdel1 * 1000, p1000 / 100, '.', xdel1 * 2000, p2000 / 100, '.', xdel1 * 3000, p3000 / 100, '.', xdel1 * 4000, p4000 / 100, '.', xdel1 * 5000, p5000 / 100, '.', xdel1 * 6000,
from scipy.interpolate import splrep, splev, lagrange from numpy import exp DELTA = 0.0000000001 def f(x): return 1 - exp(-x) def F(x, c): return x + exp(-x) + c def spline_func(x): array_of_x, array_of_y = make_arrays(0, 3, 0.3) spline_coefficients = splrep(array_of_x, array_of_y) return splev(x, spline_coefficients) def make_arrays(x0, x1, h): array_of_x = numpy.arange(x0, x1 + DELTA, h) array_of_y = numpy.array([f(xk) for xk in array_of_x]) return array_of_x, array_of_y array_of_x, array_of_y = make_arrays(0, 3, 0.3) polynom = lagrange(array_of_x, array_of_y) print('Integral of f(x): ' + str(F(3, 0) - F(0, 0))) y, _ = quad(spline_func, 0, 3) print('Integral of spline: ' + str(y)) y, _ = quad(polynom, 0, 3) print('Integral of polynom: ' + str(y))
def _optimize_curve_parameter(curve, x0, set_value, factor, max_shrinking, max_value=None, threshold_factor=None, res_decrease_factor=None, verbose=True, recursions=1, num=None, full_output=False, _cache=None): r"""Vary a parameter to minimize the required resolution. This varies a parameter and repeatedly checks the residual expansion of the resulting curve to see at which value the residual has its minimal value. This should lead to a lower required resolution when using the found parameter value for reparametrizing the curve. """ def _p(msg): if verbose: print(msg) res_cache = dict() if _cache is None else _cache def _max_residual(num, value): key = (num, value) try: return res_cache[key] except KeyError: pass modified_curve = set_value(value, num=num) c1 = RefParamCurve.from_curve(modified_curve, num=0, metric=curve.metric) space = np.linspace(0, np.pi, 2 * num + 1, endpoint=False)[1:] residual = np.absolute(c1.expansions(params=space)).max() res_cache[key] = residual return residual a = x0 if num is None: if threshold_factor is None or res_decrease_factor is None: raise TypeError("With `num` not specified, `threshold_factor` " "and `res_decrease_factor` are mandatory.") err0 = _max_residual(num=curve.num, value=a) _p("residual expansion after conversion: %s" % err0) threshold = threshold_factor * err0 num = curve.num while True: num = res_decrease_factor * num if _max_residual(num=int(num), value=a) >= threshold: break num = int(num) _p("performing search with resolution %s" % num) def f(x): value = _max_residual(num=num, value=x) _p(" residual for value=%s is: %.6e" % (x, value)) return value def _step(x): x1 = factor * x return min(x1, max_value) if max_value else x1 fa = f(a) b = _step(a) fb = f(b) if fb >= fa: factor = 1. / factor c = _step(a) fc = f(c) if fc >= fa: # worse or equal in both directions data = sorted( # set() removes any duplicate entries set([(a, fa), (b, fb), (c, fc)]), key=lambda x: x[0]) xs, ys = zip(*data) if len(xs) < 3: if recursions > 0: smaller_factor = 0.5 * (factor - 1.0) + 1.0 opt = x0 * smaller_factor else: _p("Ending search at boundary.") return (a, num) if full_output else a else: opt = lagrange(xs, np.log10(ys)).deriv().roots.real[0] if recursions > 0: _p("Worse or equal in both directions. Recursing...") new_factor = _limit_factor_shrinking( opt / x0, factor, max_shrinking, verbose=verbose, ) opt = _optimize_curve_parameter( curve=curve, x0=x0, max_shrinking=max_shrinking, max_value=max_value, set_value=set_value, factor=new_factor, num=num, verbose=verbose, recursions=recursions - 1, _cache=res_cache, ) return (opt, num) if full_output else opt a, b = b, c fa, fb = fb, fc while True: c = _step(b) if c == b: _p("Search reached boundary. Ending here.") return (c, num) if full_output else c fc = f(c) if fc > fb: opt = lagrange([a, b, c], np.log10([fa, fb, fc])).deriv().roots.real[0] return (opt, num) if full_output else opt a, b = b, c fa, fb = fb, fc
import numpy as np import matplotlib.pyplot as plt import scipy.interpolate as interp from matplotlib import rc data=np.loadtxt("tb2.txt"); time=data[:,0]; mag=data[:,1]; # Lagrange interpolation lagrange=interp.lagrange(time,mag) t=np.linspace(0.0,1.0,200) lag_interp=lagrange(t) # piecewise linear linear=interp.interp1d(time,mag,kind='linear') linear_interp=linear(t) # piecewise cubic quad=interp.interp1d(time,mag,kind='quadratic') quad_interp=quad(t) # cubic Hermite interpolation cubic=interp.interp1d(time,mag,kind='cubic') cubic_interp=cubic(t) # natural cubic spline tck=interp.splrep(time,mag,k=3) cspline_interp=interp.splev(t,tck) # set the axes and ticks of the plots rc('axes',linewidth=2,labelsize=16);
t21 = np.arange(-1, 1, 0.1) #print(t21) y21 = [functionOriginal(item) for item in t21] #for elem in y21: # print(str(round(elem,5))) #Todo calculate values of splines tck21 = interpolate.splrep(t21, y21, k=3, s=0) sol = np.array(interpolate.splev(np.array([-0.95, 0.11, 0.76]), tck21)) sol = [round(item, 5) for item in sol] print('solucion para splines en valores [-0.95,0.11,0.76]:: ') print(sol) #p20_r = np.poly1d(np.polyfit(t21, y21, 20)) p20_r = lagrange(t21, y21) value = [round(p20_r(e), 5) for e in [-0.95, 0.11, 0.76]] print('solucion para poly 20 en valores [-0.95,0.11,0.76]:: ') print(value) list_fo21 = [functionOriginal(xi) for xi in [-0.95, 0.11, 0.76]] print('solucion para original en valores [-0.95,0.11,0.76]:: ') print(str(np.round(list_fo21, 5))) # observamos que los polinomios interpolantes estan mas cerca , pero aun asi por la naturaleza del polinomio de la grange # hya ciertas partes que tienen a desviarse abruptamente cuando llega a los extremos. #un poco mas ajustado los valores respecto a la funcion original para splines. lin50 = np.arange(-1, 1, 0.1) list21_spline = np.array(interpolate.splev(lin50, tck21)) list21_poly = p20_r(lin50)
from scipy.interpolate import lagrange from numpy.polynomial.polynomial import Polynomial import Fermat import numpy as np x = np.array([0, 1, 2]) y = [41, 43, 47] poly = lagrange(x, y) a = Polynomial(poly).coef print(a) liste = [] cpt = 0 dcpt = [] for i in range(1000): res = int(poly(i)) if res > 1: if Fermat.fermat(res): liste.append(res) cpt += 1 else: if len(liste) > 0: dcpt.append(liste) cpt = 0 liste = [] else:
def ployinterp_column(s, n, k=5): y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 + k))] # 取数 y = y[y.notnull()] # 剔除空值 return lagrange(y.index, list(y))(n) # 插值并返回插值结果
#Si la opción dentro del rango es SI ingresa al if if(op == 1): while True: #Solicita el valor de la x, la cual debe estar entre el rango de las x ingresadas como par ordenado xi = int(input("\n\tIngrese el valor de X a interpolar: ")) #Si es mayor o menor a este rango, se imprimirá un mensaje y repetira el bucle if xi < xmin: print("\n\tIngresa un valor que se encuentre entre "+str(xmin)+" y "+str(xmax)) elif xi > xmax: print("\n\tIngresa un valor que se encuentre entre "+str(xmin)+" y "+str(xmax)) else: break break #Se realiza el polinomio de lagrange mediante la libreria scipy p = lagrange(x, y) #Solicitamos un rango de numero con intervalos 0.1 entre la x maximo y minima de los pares ordenados xprueba = np.arange(xmin, (xmax + 0.1), 0.1) yprueba = [] #Se prueban los valoren en x para el polinomio de lagrange for i in xprueba: #Se rellena el vector y que será utilizado para el gráfico yprueba.append(p(i)) #Se imprimen los puntos ingresados por el usuario en el gráfico y los obtenidos en las pruebas plt.plot(x , y, 'ok', label='puntos conocidos') plt.plot(xprueba, yprueba, '--k', label='valores verdaderos') #Etiquetas de los ejes
def lagrange_interpolate(shares): xs = [idx for idx, _ in shares] ys = [share for _, share in shares] return CustomPolynomial(lagrange(xs, ys)).coef[-1]
def ployinter(n,k=50): y = data['distance_from_home'][list(range(n-k,n)) + list(range(n+1,n+1+k))] y = y[y.notnull()] #剔除空值 return lagrange(y.index,list(y))(n)
def ployinterp_column(s, n, k=5): y = s[list(range(n-k, n)) + list(range(n+1, n+1+k))] y = y[y.notnull()] return lagrange(y.index, list(y))(n)
def ployinterp_column(s, n, k=5): y = s.reindex(list(range(n - k, n)) + list(range(n + 1, n + 1 + k))) #取数,有可能会取到空值。另外这里用series[list(range(x))]时会出现警告,修改为series.reindex(list(range(x))) y = y[y.notnull()] #剔除空值 return lagrange(y.index, list(y))(n) #插值并返回插值结果n
ax.plot(xVals, fxVals) # plot actual values (non standardized) ax.plot(self.x, self.fx, marker = 'o', markersize = 2, linestyle = '') ax.plot(self.sorted_x[self.intPoints_ix], self.sorted_fx[self.intPoints_ix], marker = 'o', markersize = 2, linestyle = '', color = 'r') # xVals = np.linspace(-1., 0., 1.e2) # fxVals = np.log((1. - self.target_fx) + fIn) figureFile = os.path.join(self.optimFolder, 'lagrangeApprox_' + str(self.nUpdates) + '.eps') fig.savefig(figureFile) os.system('chmod 660 ' + figureFile) self.logger.debug('done making plot') if __name__ == '__main__': a = np.linspace(0.1, 2, 10) b = -np.log(a) c = si.lagrange(a, b) plt.plot(a, c(a)) plt.plot(a, b) #plt.show() fun = lambda x: -np.log(x) x = np.array([0.01, 5]) xhat = np.array([10]) iter = 0 while np.abs(fun(xhat)) > 1.e-4: print 'iter %d' % iter fx = fun(x) gx = si.lagrange(x, fx) x0 = xhat
print("data 的列索引:\n", data.columns) # 设置使用缺失值 前 后的n 个来进行构建拉格朗日关系 n = 5 # 循环查看 缺失值的位置 for i in range(data.shape[0]): # print(i) # 判断 如果是缺失值,就进行插值 if np.isnan(data.iloc[i, 1]): print("第%d行为缺失值" % i) if i - n < 0: start = 0 else: start = i - n # 获取缺失值的前后n个数据----这前后n个数据是否存在缺失值???? mask = data.iloc[start:i + n + 1, 1] # 获取index x = mask.index # 将含有缺失值的行的索引去掉 x = x[mask.notnull()] print("x:\n", x) # 不管有无 缺失值,去除掉 其中含有缺失值的部分 y = mask[mask.notnull()].values # 含有缺失值的数组 print("y:\n", y) # 构建拉格朗日 多项式---返回拉格朗日多项式对象 la = lagrange(x=x, w=y) # 使用拉格朗日多项式进行插值 data.iloc[i, 1] = la([i]) print("插值完成之后的结果:", data)
# 莱布尼兹方法 for n in n_list: flag = True time_start = time() while flag: temp = 4 / (2 * i + 1) i += 1 if temp < 10**(-n): time_end = time() time_list.append(time_end - time_start) flag = False # 插值 n_la = np.linspace(0, 10, 100) la_result = lagrange(n_list, time_list) # 验证插值精度 for n in n_exam: time_start = time() flag = True while flag: temp = 4 / (2 * i + 1) i += 1 if temp < 10**(-n): time_end = time() time_exam.append(time_end - time_start) flag = False # 绘制图像
"""coded by: rakeeb purpose: to study interpolation by various techniques""" import numpy as np import scipy.interpolate as spi import matplotlib.pyplot as plt x = np.array([0, 1, 2, 3, 4, 5]) y = np.array([1.0, 2.0, 1.0, 0.5, 4.0, 8.0]) uspl = spi.interp1d(x, y, kind='slinear', fill_value='extrapolate') #univariate spline bspl = spi.interp1d(x, y, kind='quadratic', fill_value='extrapolate') #bivariate spline cspl = spi.CubicSpline(x, y) #cubic spline lint = spi.lagrange(x, y) #lagrange interpolation xnew = np.arange(0, 5, 0.001) y_u = uspl(xnew) y_b = bspl(xnew) y_c = cspl(xnew) y_l = lint(xnew) plt.plot(x, y, 'o', color='red') plt.plot(xnew, y_u, '-', color='blue', label='univariate spline') plt.plot(xnew, y_b, '-', color='orange', label='bivariant spline') plt.plot(xnew, y_c, '-', color='green', label='cubic spline') plt.plot(xnew, y_l, '-', color='violet', label='lagrange interpolatio') plt.xlabel('x axis') plt.ylabel('y axis') plt.legend()
import numpy as np from scipy.misc import derivative as deri from scipy.interpolate import lagrange from scipy.interpolate import interp1d xi = np.array([0.0, 0.1, 0.2, 0.3, 0.4]) yi = np.array([0.0, 0.078348, 0.13891, 0.192916, 0.244981]) intp = lagrange(xi, yi) kubik = interp1d(xi, yi, kind='cubic') lagr = deri(intp, 0.2, dx=0.2, order=5) kubi = deri(kubik, 0.2, dx=0.01, order=5) cent = (yi[0] - 8 * yi[1] + 8 * yi[3] - yi[4]) / 1.2 print("lagranż:\t%12.10f \ncubic spline:\t%12.10f \ncentralna:\t%12.10f" % (lagr, kubi, cent))
def configure_instrumentation_measurment_unit(dev, channel_nb, is_ins1): default_nb_samples = 0 default_units = [] if is_ins1: print("Set display mode to relative ratio") dev.set_display_mode(CN0503.DISPLAY_MODE.RELATIVE_RATIO) default_nb_samples = DEFAULT_INS1_NB_VALUES default_units = DEFAULT_INS1_UNITS else: print("Set display mode to ins1") dev.set_display_mode(CN0503.DISPLAY_MODE.INSTRUMENTATION_UNIT_1) default_nb_samples = DEFAULT_INS2_NB_VALUES default_units = DEFAULT_INS2_UNITS nb_samples = input('How many samples do you want to use to calculate the '+\ 'polinom for the instrumenatation unit? (%d) :' %\ default_nb_samples) if nb_samples == '': nb_samples = default_nb_samples else: nb_samples = int(nb_samples) ok = False while not ok: unit_values = input("Input the know unit values for the samples (%s) :"%\ " ".join(str(x) for x in default_units)) if (unit_values == ''): unit_values = default_units else: unit_values = [int(val) for val in unit_values.split()] if len(unit_values) == nb_samples: ok = True mean = [] for i in range(nb_samples): print("Please add sample number %d" % i) data = read_samples(dev, channel_nb, DEFAULT_NB_SAMPLES) mean.append(np.mean(data)) print("Mean(%d): %f" % (i, mean[i])) x = np.array(mean) y = np.array(unit_values) poly = lagrange(x, y) coefs = poly.c.tolist() #Reverse list coefs = coefs[::-1] print("Coefficients for instrumentation measurment unit polynomial \n") print(coefs) print("Setting polinomyal coefficients") if is_ins1: dev.set_instrumentation_unit_1_polynomial(channel_nb, coefs) else: dev.set_instrumentation_unit_2_polynomial(channel_nb, coefs) print("Set display mode to instrumentation unit") if is_ins1: dev.set_display_mode(CN0503.DISPLAY_MODE.INSTRUMENTATION_UNIT_1) else: dev.set_display_mode(CN0503.DISPLAY_MODE.INSTRUMENTATION_UNIT_2) print( "Ready to read instrumentation unit data. Please add sample for measurment" ) data = read_samples(dev, channel_nb, DEFAULT_NB_SAMPLES) mean = np.mean(data) print("Mean: %f" % (mean)) nb = 2 if is_ins1: nb = 1 if promt_yes_or_no("Do you want current data to be plotted?", True): plot_data(data, 'Instrumentation unit %d' % (nb)) print("Configure instrumentation measurment unit done")
def ployinterp_column(s, n, k=5): # k=5表示用空值的前后5个数值来拟合曲线,从而预测空值 y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 - k))] # 取值,range函数返回一个左闭右开([left,right))的序列数 y = y[y.notnull()] # 取上一行中取出数值列表中的非空值,保证y的每行都有数值,便于拟合函数 return lagrange(y.index, list(y))(n) # 调用拉格朗日函数,并添加索引
def _interpolate_table(self, key, leap_second_correction=False, derivative_order=0): """Interpolate daily values to the given time epochs Uses Lagrange interpolation with the given interpolation window. We have observed that the Lagrange interpolation introduces instabilities when the EOP data are constant (as for instance in the VASCC-data). In this case, we force the Lagrange polynomial to be constant. Args: key (String): Name of data to be interpolated, key in `self.data`. leap_second_correction (Bool): Whether data should be corrected for leap seconds before interpolation. Returns: Array: Interpolated values, one value for each time epoch. """ days = np.unique(self.time.utc.mjd_int) offsets = range(int(-np.ceil(self.window / 2) + 1), int(np.floor(self.window / 2) + 1)) if leap_second_correction: leap = { d: np.array([ self.data[d + o].get("leap_offset", np.nan) - self.data[d]["leap_offset"] for o in offsets ]) for d in days } for lo in leap.values(): lo[np.isnan(lo)] = 0 else: leap = {d: 0 for d in days} table_values = { d: np.array([self.data[d + o][key] for o in offsets]) + leap[d] for d in days } interpolators = { d: interpolate.lagrange(offsets, v) for d, v in table_values.items() } for poly in interpolators.values(): poly.c[ np.abs(poly.c) < 1e-15] = 0 # Avoid numerical instabilities for constant values if derivative_order: interp_values = { d: np.polyder(ip, derivative_order)(self.time.utc.mjd_frac) for d, ip in interpolators.items() } else: interp_values = { d: ip(self.time.utc.mjd_frac) for d, ip in interpolators.items() } if self.time.size == 1: return interp_values[self.time.utc.mjd_int] values = np.empty(self.time.size) for day in days: idx = self.time.utc.mjd_int == day values[idx] = interp_values[day][idx] return values
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt from scipy import interpolate import numpy as np A = np.zeros([22,2]) A[:,0] = np.arange(0, 43, 2) A[0:11,1] = [2, 6, 9, 12, 14, 16, 17.5, 18.5, 20, 20.5, 21.5] A[11:22,1] = [22, 22.5, 22.7, 23.5, 23.5, 23.7, 24, 24, 24.2, 24.2, 24.5] print(A[:]) plt.plot(A[:,0], A[:,1], 'o', label = "Messwerte") plt.xlabel('Zeit [s]') plt.ylabel('Spannung [V]') # plt.show() # interpolieren mit polynom 2. ordnung p2 = interpolate.lagrange(A[[0,10,21],0], A[[0,10,21],1]) xnew = np.arange(-2, 50, 2) ynew = p2(xnew) error = (( p2(A[:,0]) - A[:,1])**2).sum() print('P2 => Quadratische Fehler: %.4e; gemittelt %.4e.' % (error, error/22)) plt.plot(xnew, ynew, label="Polynome Ordnung 2", linestyle='-', c='k') # polynom 5. ordnung p5 = interpolate.lagrange(A[::4,0], A[::4,1]) xnew = np.arange(-2, 50, 2) ynew = p5(xnew) error = (( p5(A[:,0]) - A[:,1])**2).sum() print('P5 => Quadratische Fehler: %.4e; gemittelt %.4e.' % (error, error/22)) plt.plot(xnew, ynew, label="Polynome Ordnung 5", linestyle='--', c='r') # legende braucht label aus den plots plt.legend(loc="lower right") plt.show()