#! /usr/bin/env python # def pwl_value_1d ( nd, xd, yd, ni, xi ): #*****************************************************************************80 # ## PWL_VALUE_1D evaluates the piecewise linear interpolant. # # Discussion: # # The piecewise linear interpolant L(ND,XD,YD)(X) is the piecewise # linear function which interpolates the data (XD(I),YD(I)) for I = 1 # to ND. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 02 July 2015 # # Author: # # John Burkardt # # Parameters: # # Input, integer ND, the number of data points. # ND must be at least 1. # # Input, real XD(ND), the data points. # # Input, real YD(ND), the data values. # # Input, integer NI, the number of interpolation points. # # Input, real XI(NI), the interpolation points. # # Output, real YI(NI), the interpolated values. # import numpy as np if ( nd == 1 ): yi = np.ones ( ni ) * yd[0] return yi yi = np.zeros ( ni ) for i in range ( 0, ni ): if ( xi[i] <= xd[0] ): t = ( xi[i] - xd[0] ) / ( xd[1] - xd[0] ) yi[i] = ( 1.0 - t ) * yd[0] + t * yd[1] elif ( xd[nd-2] <= xi[i] ): t = ( xi[i] - xd[nd-2] ) / ( xd[nd-1] - xd[nd-2] ) yi[i] = ( 1.0 - t ) * yd[nd-2] + t * yd[nd-1] else: for k in range ( 1, nd ): if ( xd[k-1] <= xi[i] and xi[i] <= xd[k] ): t = ( xi[i] - xd[k-1] ) / ( xd[k] - xd[k-1] ) yi[i] = ( 1.0 - t ) * yd[k-1] + t * yd[k] return yi def pwl_value_1d_test ( ): #*****************************************************************************80 # ## PWL_VALUE_1D_TEST tests PWL_VALUE_1D. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 02 July 2015 # # Author: # # John Burkardt # import numpy as np import platform from r8vec2_print import r8vec2_print nd = 4 ni = 21 # # Values of f(x) = x^3 - 12 x^2 + 39 x -28 = ( x - 1 ) * ( x - 4 ) * ( x - 7 ) # xd = np.array ( [ 0.0, 2.0, 5.0, 10.0 ] ) yd = np.array ( [ -28.0, +10.0, -8.0, +162.0 ] ) print ( '' ) print ( 'PWL_VALUE_1D_TEST:' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' PWL_VALUE_1D evaluates a piecewise linear 1D interpolant.' ) x_min = 0.0 x_max = 10.0 xi = np.linspace ( x_min, x_max, ni ) yi = pwl_value_1d ( nd, xd, yd, ni, xi ) r8vec2_print ( ni, xi, yi, ' Table of interpolant values:' ) # # Terminate. # print ( '' ) print ( 'PWL_VALUE_1D_TEST:' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): from timestamp import timestamp timestamp ( ) pwl_value_1d_test ( ) timestamp ( )