小编per*_*sse的帖子

强制乘法使用 __rmul__() 而不是 Numpy 数组 __mul__() 或绕过广播

这个问题与Overriding other __rmul__ with your class's __mul__中提出的问题很接近,但我的印象是,这是一个比数值数据更普遍的问题。另外,这个问题没有得到解答,我真的不想使用矩阵乘法@来进行此操作。因此,问题。

我确实有一个接受标量和数值数组相乘的对象。与往常一样,左乘法工作得很好,因为它myobj()使用的是方法,但在右乘法中,NumPy 使用广播规则并给出元素级结果dtype=object

这还有一个副作用,即无法检查数组的大小是否兼容。

因此,问题是

有没有办法强制 numpy 数组查找__rmul__()另一个对象的 ,而不是广播和按元素执行__mul__()

在我的特定情况下,对象是 MIMO(多输入、多输出)传递函数矩阵(或者滤波器系数矩阵,如果您愿意),因此矩阵乘法在线性系统的加法和乘法方面具有特殊含义。因此在每个条目中都有SISO系统。

import numpy as np

class myobj():
    def __init__(self):
        pass

    def __mul__(self, other):
        if isinstance(other, type(np.array([0.]))):
            if other.size == 1:
                print('Scalar multiplication')
            else:
                print('Multiplication of arrays')

    def __rmul__(self, other):
        if isinstance(other, type(np.array([0.]))):
            if other.size == 1:
                print('Scalar multiplication')
            else:
                print('Multiplication of arrays')

A = myobj()
a = np.array([[[1+1j]]])  # some generic scalar
B …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy python-3.x array-broadcasting

5
推荐指数
1
解决办法
1161
查看次数

用scipy在python中求解二维微分方程

我是python的新手。我有一个简单的微分系统,它由两个变量和两个微分方程和初始条件组成x0=1, y0=2

dx/dt=6*y
dy/dt=(2t-3x)/4y
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试解决这两个微分方程,我选择odeint. 这是我的代码:

import matplotlib.pyplot as pl
import numpy as np
from scipy.integrate import odeint

def func(z,b):
    x, y=z
    return [6*y, (b-3*x)/(4*y)]    

z0=[1,2]
t = np.linspace(0,10,11)
b=2*t
xx=odeint(func, z0, b)
pl.figure(1)
pl.plot(t, xx[:,0])
pl.legend()
pl.show()
Run Code Online (Sandbox Code Playgroud)

但结果不正确,并出现错误信息:

在此处输入图片说明

Excess work done on this call (perhaps wrong Dfun type).
Run with full_output = 1 to get quantitative information.
Run Code Online (Sandbox Code Playgroud)

我不知道我的代码有什么问题,我该如何解决。任何帮助都会对我有用。

python scipy ode

2
推荐指数
1
解决办法
6797
查看次数

标签 统计

python ×2

array-broadcasting ×1

arrays ×1

numpy ×1

ode ×1

python-3.x ×1

scipy ×1