Newton interpolation in python using matplotlib












0















I want to use matplotlib to draw a picture of Newton interpolation, but I met with some difficulties. My figure don't through the last some points. Can you help me? If my code is wrong, please tell me the details, thank you.



import numpy as np
import matplotlib.pyplot as plt


def coef(x, y):
'''x : array of data points
y : array of f(x) '''
x.astype(float)
y.astype(float)
n = len(x)
a =
for i in range(n):
a.append(y[i])

for j in range(1, n):

for i in range(n - 1, j - 1, -1):
a[i] = float(a[i] - a[i - 1]) / float(x[i] - x[i - j])

return np.array(a) # return an array of coefficient


def Eval(a, x, r):
''' a : array returned by function coef()
x : array of data points
r : the node to interpolate at '''
x.astype(float)
n = len(a) - 1
temp = a[n]
for i in range(n - 1, -1, -1):
temp = temp * (r - x[i]) + a[i]
return temp # return the y_value interpolation


if __name__ == '__main__':
x = np.linspace(0, 20, 11)
y = np.random.randint(0, 10, 11)
# y = np.asarray([i ** 2 for i in x])

a = coef(x, y)
tmp_x = np.linspace(0, 21, 21)
tmp_y = [Eval(a, tmp_x, i) for i in tmp_x]

plt.plot(x, y, linestyle='', marker='o', color='b')
plt.plot(tmp_x, tmp_y, linestyle='--', color='r')
plt.show()


picture of code










share|improve this question



























    0















    I want to use matplotlib to draw a picture of Newton interpolation, but I met with some difficulties. My figure don't through the last some points. Can you help me? If my code is wrong, please tell me the details, thank you.



    import numpy as np
    import matplotlib.pyplot as plt


    def coef(x, y):
    '''x : array of data points
    y : array of f(x) '''
    x.astype(float)
    y.astype(float)
    n = len(x)
    a =
    for i in range(n):
    a.append(y[i])

    for j in range(1, n):

    for i in range(n - 1, j - 1, -1):
    a[i] = float(a[i] - a[i - 1]) / float(x[i] - x[i - j])

    return np.array(a) # return an array of coefficient


    def Eval(a, x, r):
    ''' a : array returned by function coef()
    x : array of data points
    r : the node to interpolate at '''
    x.astype(float)
    n = len(a) - 1
    temp = a[n]
    for i in range(n - 1, -1, -1):
    temp = temp * (r - x[i]) + a[i]
    return temp # return the y_value interpolation


    if __name__ == '__main__':
    x = np.linspace(0, 20, 11)
    y = np.random.randint(0, 10, 11)
    # y = np.asarray([i ** 2 for i in x])

    a = coef(x, y)
    tmp_x = np.linspace(0, 21, 21)
    tmp_y = [Eval(a, tmp_x, i) for i in tmp_x]

    plt.plot(x, y, linestyle='', marker='o', color='b')
    plt.plot(tmp_x, tmp_y, linestyle='--', color='r')
    plt.show()


    picture of code










    share|improve this question

























      0












      0








      0








      I want to use matplotlib to draw a picture of Newton interpolation, but I met with some difficulties. My figure don't through the last some points. Can you help me? If my code is wrong, please tell me the details, thank you.



      import numpy as np
      import matplotlib.pyplot as plt


      def coef(x, y):
      '''x : array of data points
      y : array of f(x) '''
      x.astype(float)
      y.astype(float)
      n = len(x)
      a =
      for i in range(n):
      a.append(y[i])

      for j in range(1, n):

      for i in range(n - 1, j - 1, -1):
      a[i] = float(a[i] - a[i - 1]) / float(x[i] - x[i - j])

      return np.array(a) # return an array of coefficient


      def Eval(a, x, r):
      ''' a : array returned by function coef()
      x : array of data points
      r : the node to interpolate at '''
      x.astype(float)
      n = len(a) - 1
      temp = a[n]
      for i in range(n - 1, -1, -1):
      temp = temp * (r - x[i]) + a[i]
      return temp # return the y_value interpolation


      if __name__ == '__main__':
      x = np.linspace(0, 20, 11)
      y = np.random.randint(0, 10, 11)
      # y = np.asarray([i ** 2 for i in x])

      a = coef(x, y)
      tmp_x = np.linspace(0, 21, 21)
      tmp_y = [Eval(a, tmp_x, i) for i in tmp_x]

      plt.plot(x, y, linestyle='', marker='o', color='b')
      plt.plot(tmp_x, tmp_y, linestyle='--', color='r')
      plt.show()


      picture of code










      share|improve this question














      I want to use matplotlib to draw a picture of Newton interpolation, but I met with some difficulties. My figure don't through the last some points. Can you help me? If my code is wrong, please tell me the details, thank you.



      import numpy as np
      import matplotlib.pyplot as plt


      def coef(x, y):
      '''x : array of data points
      y : array of f(x) '''
      x.astype(float)
      y.astype(float)
      n = len(x)
      a =
      for i in range(n):
      a.append(y[i])

      for j in range(1, n):

      for i in range(n - 1, j - 1, -1):
      a[i] = float(a[i] - a[i - 1]) / float(x[i] - x[i - j])

      return np.array(a) # return an array of coefficient


      def Eval(a, x, r):
      ''' a : array returned by function coef()
      x : array of data points
      r : the node to interpolate at '''
      x.astype(float)
      n = len(a) - 1
      temp = a[n]
      for i in range(n - 1, -1, -1):
      temp = temp * (r - x[i]) + a[i]
      return temp # return the y_value interpolation


      if __name__ == '__main__':
      x = np.linspace(0, 20, 11)
      y = np.random.randint(0, 10, 11)
      # y = np.asarray([i ** 2 for i in x])

      a = coef(x, y)
      tmp_x = np.linspace(0, 21, 21)
      tmp_y = [Eval(a, tmp_x, i) for i in tmp_x]

      plt.plot(x, y, linestyle='', marker='o', color='b')
      plt.plot(tmp_x, tmp_y, linestyle='--', color='r')
      plt.show()


      picture of code







      python matplotlib






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 '18 at 17:05









      CarlCarl

      11




      11
























          1 Answer
          1






          active

          oldest

          votes


















          0














          OK, I had solve my problem after reading some paper about Newton Interprolation. But the comments are written in Chinese, when I have time, I will translate it into Engilsh.
          image of Newton Interpolation



          import numpy as np
          import matplotlib.pyplot as plt


          class Newton(object):
          def __init__(self, x, y):
          self.x = x
          self.y = y

          def run(self, tmp_x):
          # 构造差商表
          table = np.zeros([len(self.x), len(self.x) + 1], dtype=float)

          for i in range(len(self.x)): # 将x 和 y 放入 差商表的前两列
          table[i][0] = self.x[i]
          table[i][1] = self.y[i]
          # 计算差商
          for i in range(2, table.shape[1]): # i is 2 to 5
          for j in range(i - 1, table.shape[0]): # j is
          table[j][i] = (table[j][i - 1] - table[j - 1][i - 1]) / (self.x[j] - self.x[j - i + 1])

          # print(table) # 输出差商表
          # for i in range(table.shape[0]):
          # for j in range(table.shape[1]):
          # print(table[i][j], end=' ')
          # print('n')
          # print('nn')

          # 由牛顿插值函数求给出的x序列对应的y序列
          tmp_y =
          for ans_x in tmp_x: # 遍历每个x
          ans_y = 0 # 对应于输入序列每个x的相应y值
          for i in range(table.shape[0]):
          tmp = table[i][i + 1] # 求值多项式第 i 项, tab[i][i + 1]为其系数
          for j in range(i):
          tmp *= (ans_x - self.x[j])
          ans_y += tmp
          tmp_y.append(ans_y)
          return tmp_y


          if __name__ == '__main__':
          plt.rcParams['font.sans-serif'] = ['SimHei']
          plt.rcParams['axes.unicode_minus'] = False

          sr_x = np.linspace(0, 20, 11)
          sr_fx = np.random.randint(0, 20, 11)

          tmp_x = np.linspace(0, 20)

          demo = Newton(sr_x, sr_fx)
          tmp_y = demo.run(tmp_x)

          print(tmp_x)
          print(tmp_y)

          plt.plot(sr_x, sr_fx, 'ro', label='插值节点')
          plt.plot(tmp_x, tmp_y, label='牛顿插值')
          enter code here
          plt.xlabel('x')
          plt.ylabel('y')
          plt.legend()
          plt.show()





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53266900%2fnewton-interpolation-in-python-using-matplotlib%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            OK, I had solve my problem after reading some paper about Newton Interprolation. But the comments are written in Chinese, when I have time, I will translate it into Engilsh.
            image of Newton Interpolation



            import numpy as np
            import matplotlib.pyplot as plt


            class Newton(object):
            def __init__(self, x, y):
            self.x = x
            self.y = y

            def run(self, tmp_x):
            # 构造差商表
            table = np.zeros([len(self.x), len(self.x) + 1], dtype=float)

            for i in range(len(self.x)): # 将x 和 y 放入 差商表的前两列
            table[i][0] = self.x[i]
            table[i][1] = self.y[i]
            # 计算差商
            for i in range(2, table.shape[1]): # i is 2 to 5
            for j in range(i - 1, table.shape[0]): # j is
            table[j][i] = (table[j][i - 1] - table[j - 1][i - 1]) / (self.x[j] - self.x[j - i + 1])

            # print(table) # 输出差商表
            # for i in range(table.shape[0]):
            # for j in range(table.shape[1]):
            # print(table[i][j], end=' ')
            # print('n')
            # print('nn')

            # 由牛顿插值函数求给出的x序列对应的y序列
            tmp_y =
            for ans_x in tmp_x: # 遍历每个x
            ans_y = 0 # 对应于输入序列每个x的相应y值
            for i in range(table.shape[0]):
            tmp = table[i][i + 1] # 求值多项式第 i 项, tab[i][i + 1]为其系数
            for j in range(i):
            tmp *= (ans_x - self.x[j])
            ans_y += tmp
            tmp_y.append(ans_y)
            return tmp_y


            if __name__ == '__main__':
            plt.rcParams['font.sans-serif'] = ['SimHei']
            plt.rcParams['axes.unicode_minus'] = False

            sr_x = np.linspace(0, 20, 11)
            sr_fx = np.random.randint(0, 20, 11)

            tmp_x = np.linspace(0, 20)

            demo = Newton(sr_x, sr_fx)
            tmp_y = demo.run(tmp_x)

            print(tmp_x)
            print(tmp_y)

            plt.plot(sr_x, sr_fx, 'ro', label='插值节点')
            plt.plot(tmp_x, tmp_y, label='牛顿插值')
            enter code here
            plt.xlabel('x')
            plt.ylabel('y')
            plt.legend()
            plt.show()





            share|improve this answer




























              0














              OK, I had solve my problem after reading some paper about Newton Interprolation. But the comments are written in Chinese, when I have time, I will translate it into Engilsh.
              image of Newton Interpolation



              import numpy as np
              import matplotlib.pyplot as plt


              class Newton(object):
              def __init__(self, x, y):
              self.x = x
              self.y = y

              def run(self, tmp_x):
              # 构造差商表
              table = np.zeros([len(self.x), len(self.x) + 1], dtype=float)

              for i in range(len(self.x)): # 将x 和 y 放入 差商表的前两列
              table[i][0] = self.x[i]
              table[i][1] = self.y[i]
              # 计算差商
              for i in range(2, table.shape[1]): # i is 2 to 5
              for j in range(i - 1, table.shape[0]): # j is
              table[j][i] = (table[j][i - 1] - table[j - 1][i - 1]) / (self.x[j] - self.x[j - i + 1])

              # print(table) # 输出差商表
              # for i in range(table.shape[0]):
              # for j in range(table.shape[1]):
              # print(table[i][j], end=' ')
              # print('n')
              # print('nn')

              # 由牛顿插值函数求给出的x序列对应的y序列
              tmp_y =
              for ans_x in tmp_x: # 遍历每个x
              ans_y = 0 # 对应于输入序列每个x的相应y值
              for i in range(table.shape[0]):
              tmp = table[i][i + 1] # 求值多项式第 i 项, tab[i][i + 1]为其系数
              for j in range(i):
              tmp *= (ans_x - self.x[j])
              ans_y += tmp
              tmp_y.append(ans_y)
              return tmp_y


              if __name__ == '__main__':
              plt.rcParams['font.sans-serif'] = ['SimHei']
              plt.rcParams['axes.unicode_minus'] = False

              sr_x = np.linspace(0, 20, 11)
              sr_fx = np.random.randint(0, 20, 11)

              tmp_x = np.linspace(0, 20)

              demo = Newton(sr_x, sr_fx)
              tmp_y = demo.run(tmp_x)

              print(tmp_x)
              print(tmp_y)

              plt.plot(sr_x, sr_fx, 'ro', label='插值节点')
              plt.plot(tmp_x, tmp_y, label='牛顿插值')
              enter code here
              plt.xlabel('x')
              plt.ylabel('y')
              plt.legend()
              plt.show()





              share|improve this answer


























                0












                0








                0







                OK, I had solve my problem after reading some paper about Newton Interprolation. But the comments are written in Chinese, when I have time, I will translate it into Engilsh.
                image of Newton Interpolation



                import numpy as np
                import matplotlib.pyplot as plt


                class Newton(object):
                def __init__(self, x, y):
                self.x = x
                self.y = y

                def run(self, tmp_x):
                # 构造差商表
                table = np.zeros([len(self.x), len(self.x) + 1], dtype=float)

                for i in range(len(self.x)): # 将x 和 y 放入 差商表的前两列
                table[i][0] = self.x[i]
                table[i][1] = self.y[i]
                # 计算差商
                for i in range(2, table.shape[1]): # i is 2 to 5
                for j in range(i - 1, table.shape[0]): # j is
                table[j][i] = (table[j][i - 1] - table[j - 1][i - 1]) / (self.x[j] - self.x[j - i + 1])

                # print(table) # 输出差商表
                # for i in range(table.shape[0]):
                # for j in range(table.shape[1]):
                # print(table[i][j], end=' ')
                # print('n')
                # print('nn')

                # 由牛顿插值函数求给出的x序列对应的y序列
                tmp_y =
                for ans_x in tmp_x: # 遍历每个x
                ans_y = 0 # 对应于输入序列每个x的相应y值
                for i in range(table.shape[0]):
                tmp = table[i][i + 1] # 求值多项式第 i 项, tab[i][i + 1]为其系数
                for j in range(i):
                tmp *= (ans_x - self.x[j])
                ans_y += tmp
                tmp_y.append(ans_y)
                return tmp_y


                if __name__ == '__main__':
                plt.rcParams['font.sans-serif'] = ['SimHei']
                plt.rcParams['axes.unicode_minus'] = False

                sr_x = np.linspace(0, 20, 11)
                sr_fx = np.random.randint(0, 20, 11)

                tmp_x = np.linspace(0, 20)

                demo = Newton(sr_x, sr_fx)
                tmp_y = demo.run(tmp_x)

                print(tmp_x)
                print(tmp_y)

                plt.plot(sr_x, sr_fx, 'ro', label='插值节点')
                plt.plot(tmp_x, tmp_y, label='牛顿插值')
                enter code here
                plt.xlabel('x')
                plt.ylabel('y')
                plt.legend()
                plt.show()





                share|improve this answer













                OK, I had solve my problem after reading some paper about Newton Interprolation. But the comments are written in Chinese, when I have time, I will translate it into Engilsh.
                image of Newton Interpolation



                import numpy as np
                import matplotlib.pyplot as plt


                class Newton(object):
                def __init__(self, x, y):
                self.x = x
                self.y = y

                def run(self, tmp_x):
                # 构造差商表
                table = np.zeros([len(self.x), len(self.x) + 1], dtype=float)

                for i in range(len(self.x)): # 将x 和 y 放入 差商表的前两列
                table[i][0] = self.x[i]
                table[i][1] = self.y[i]
                # 计算差商
                for i in range(2, table.shape[1]): # i is 2 to 5
                for j in range(i - 1, table.shape[0]): # j is
                table[j][i] = (table[j][i - 1] - table[j - 1][i - 1]) / (self.x[j] - self.x[j - i + 1])

                # print(table) # 输出差商表
                # for i in range(table.shape[0]):
                # for j in range(table.shape[1]):
                # print(table[i][j], end=' ')
                # print('n')
                # print('nn')

                # 由牛顿插值函数求给出的x序列对应的y序列
                tmp_y =
                for ans_x in tmp_x: # 遍历每个x
                ans_y = 0 # 对应于输入序列每个x的相应y值
                for i in range(table.shape[0]):
                tmp = table[i][i + 1] # 求值多项式第 i 项, tab[i][i + 1]为其系数
                for j in range(i):
                tmp *= (ans_x - self.x[j])
                ans_y += tmp
                tmp_y.append(ans_y)
                return tmp_y


                if __name__ == '__main__':
                plt.rcParams['font.sans-serif'] = ['SimHei']
                plt.rcParams['axes.unicode_minus'] = False

                sr_x = np.linspace(0, 20, 11)
                sr_fx = np.random.randint(0, 20, 11)

                tmp_x = np.linspace(0, 20)

                demo = Newton(sr_x, sr_fx)
                tmp_y = demo.run(tmp_x)

                print(tmp_x)
                print(tmp_y)

                plt.plot(sr_x, sr_fx, 'ro', label='插值节点')
                plt.plot(tmp_x, tmp_y, label='牛顿插值')
                enter code here
                plt.xlabel('x')
                plt.ylabel('y')
                plt.legend()
                plt.show()






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 12:48









                CarlCarl

                11




                11






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53266900%2fnewton-interpolation-in-python-using-matplotlib%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Full-time equivalent

                    さくらももこ

                    13 indicted, 8 arrested in Calif. drug cartel investigation