【问题标题】:ValueError: setting an array element with a sequence. Can anyone show me what to do to fix the problemValueError:使用序列设置数组元素。谁能告诉我如何解决这个问题
【发布时间】:2021-09-22 23:57:50
【问题描述】:

我在python oop中有这个数值方法,这个错误出现在控制台窗口。谁能告诉我如何解决这个问题

self.y[i+1] = self.y[i]+(h / 6) * (k1 + 2 * k2 + 2 * k3 + k4) ValueError: 使用序列设置数组元素。

 class runge():

    def __init__(self):

       self.x = np.linspace(1, 5, 50)
       self.y = np.zeros(len(self.x))
       self.y[0] = 4
       self.loop()
       self.f()

   def f(self, x, y):

      return (self.x*np.sqrt(self.y))

   def loop(self):
      h = 0.2
      for i in range(len(self.x) - 1):
          k1 = self.f(self.x[i], self.y[i])
          k2 = self.f(self.x[i] + h / 2, self.y[i] + k1 * (h / 2))
          k3 = self.f(self.x[i] + h / 2, self.y[i] + k2 * (h / 2))
          k4 = self.f(self.x[i] + h, self.y[i] + k3 * h)
         self.y[i+1] = self.y[i]+(h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
    
   def draw(self):
      plt.plot(self.x, self.y)
      plt.show()

 run = runge()
 run.draw()

【问题讨论】:

  • 错误很明显:你实现的计算没有意义。我们无法知道你到底想做什么...How to Ask
  • 该作业的 rhs 大小是多少? lhs 只能容纳 1 个数字。

标签: python arrays numpy class oop


【解决方案1】:

您生成的 k1、k2、k3 和 k4 是 shape=(50,) 的一维数组。您正在尝试分配此数组

z = (k1 + 2 * k2 + 2 * k3 + k4) # shape=(50,)

self.y[i+1],它是数组self.y中的单个元素(标量)

【讨论】:

  • 谢谢,我在 python 中做了 runge kutta 方法,我正在学习 oop,但仍然出现错误。 import numpy as np import matplotlib.pyplot as plt h = 0.2 x = np.linspace(1, 5, 50) y = np.zeros(len(x)) for i in range(len(x)-1): y [0] = 4 k1 = x[i]*np.sqrt(y[i]) k2 = (x[i] + h/2)*np.sqrt(y[i] + k1*h/2) k3 = (x[i] + h/2)*np.sqrt(y[i] + k2*h/2) k4= (x[i] + h)*np.sqrt(y[i] + k3*h ) y[i+1] = y[i] + h/6*(k1+2*k2+2*k3+k4) plt.plot(x,y) plt.show()
猜你喜欢
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 2017-12-11
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多