Difficult with numpy array using oop python

Viewed 62

ValueError: x and y must have same first dimension, but have shapes (50,) and (0,). the values of instance of the foor loop aren't storing in the method init

import numpy as np
import matplotlib.pyplot as plt

class inter():


    def __init__(self):

        self.x = np.array([0, 20, 40, 60, 80, 100], float)
        self.y = np.array([20.0, 48.6, 61.6, 71.2, 74.8, 75.2], float)
        self.xplt = np.linspace(self.x[0], self.x[-1])
        self.yplt = np.array([], float)
        self.yp = 0


   def loop(self):

      for xp in self.xplt:
         for xi, yi in zip(self.x, self.y):
            self.yp += yi * np.prod((xp - self.x[self.x != xi]) / (xi - self.x[self.x != xi]))
         self.yplt = np.append(self.yplt, self.yp)


      return self.yplt

  def draw(self):

     plt.plot(self.xplt, self.yplt)
     plt.show()

int = inter()

int.draw()
1 Answers

I think you forgot to call : int.loop()

It worked for me : either call int.loop() before int.draw() or self.loop() in __init__()

import numpy as np
import matplotlib.pyplot as plt

class inter():


    def __init__(self):

        self.x = np.array([0, 20, 40, 60, 80, 100], float)
        self.y = np.array([20.0, 48.6, 61.6, 71.2, 74.8, 75.2], float)
        self.xplt = np.linspace(self.x[0], self.x[-1])
        self.yplt = np.array([], float)
        self.yp = 0

        self.loop()

    def loop(self):

        for xp in self.xplt:
            for xi, yi in zip(self.x, self.y):
                self.yp += yi * np.prod((xp - self.x[self.x != xi]) / (xi - self.x[self.x != xi]))
            self.yplt = np.append(self.yplt, self.yp)


        return self.yplt

    def draw(self):

        plt.plot(self.xplt, self.yplt)
        plt.show()

int = inter()

int.draw()
Related