【问题标题】:Difficult with numpy array using oop python使用 oop python 难以处理 numpy 数组
【发布时间】:2021-09-21 06:26:18
【问题描述】:

ValueError: x 和 y 必须具有相同的第一个维度,但具有 (50,) 和 (0,) 形状。 for 循环实例的值未存储在方法 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()

【问题讨论】:

    标签: python arrays matplotlib oop numpy-ndarray


    【解决方案1】:

    我想你忘记打电话了:int.loop()

    它对我有用:在int.draw() 之前调用int.loop() 或在__init__() 中调用self.loop()

    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()
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 2018-01-31
      • 2021-12-19
      • 1970-01-01
      • 2021-03-19
      相关资源
      最近更新 更多