Search code examples
pythonscipy

2 dimensional interpolation problem


I have DATA on x and y axes and the output is on z

for example

y = 10
x = [1,2,3,4,5,6]
z = [2.3,3.4,5.6,7.8,9.6,11.2]

y = 20 
x = [1,2,3,4,5,6]
z = [4.3,5.4,7.6,9.8,11.6,13.2]

y = 30 
x = [1,2,3,4,5,6]
z = [6.3,7.4,8.6,10.8,13.6,15.2]

how can i find the value of z when y = 15 x = 3.5

I was trying to use scipy but i am very new at it

Thanks a lot for the help

vibhor


Solution

  • scipy.interpolate.bisplrep

    Reference: http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html

    import scipy
    import math
    import numpy
    from scipy import interpolate
    
    
    x= [1,2,3,4,5,6]
    y= [10,20,30]
    
    Y = numpy.array([[i]*len(x) for i in y])
    X = numpy.array([x for i in y])
    Z = numpy.array([[2.3,3.4,5.6,7.8,9.6,11.2],
                     [4.3,5.4,7.6,9.8,11.6,13.2],
                     [6.3,7.4,8.6,10.8,13.6,15.2]]) 
    
    tck = interpolate.bisplrep(X,Y,Z)
    print interpolate.bisplev(3.5,15,tck) 
    
    
    7.84921875
    

    Upper solution does not give you perfect fit. check

    print interpolate.bisplev(x,y,tck)
    
    [[  2.2531746    4.2531746    6.39603175]
     [  3.54126984   5.54126984   7.11269841]
     [  5.5031746    7.5031746    8.78888889]
     [  7.71111111   9.71111111  10.9968254 ]
     [  9.73730159  11.73730159  13.30873016]
     [ 11.15396825  13.15396825  15.2968254 ]]
    

    to overcome this interpolate whit polyinomials of 5rd degree in x and 2nd degree in y direction

    tck = interpolate.bisplrep(X,Y,Z,kx=5,ky=2)
    print interpolate.bisplev(x,y,tck) 
    
    [[  2.3   4.3   6.3]
     [  3.4   5.4   7.4]
     [  5.6   7.6   8.6]
     [  7.8   9.8  10.8]
     [  9.6  11.6  13.6]
     [ 11.2  13.2  15.2]]
    

    This yield

    print interpolate.bisplev(3.5,15,tck)
    
    7.88671875
    

    Plotting:
    reference http://matplotlib.sourceforge.net/examples/mplot3d/surface3d_demo.html

    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(X, Y, Z,rstride=1, cstride=1, cmap=cm.jet)
    plt.show()