4

我的变量 C0 以 pint.UnitRegistry 单位 mol/L 定义。我需要在函数中使用它,但为了让 Python 不会在通用函数的不一致单位上调用我,我必须在函数中使用单位定义一个新变量,如下所示。

import pint
u = pint.UnitRegistry()

C0      = [10**(-3),10**(-6),0] *u.mol/u.L

def r(c,t):
    C = c * u.mol/u.L   #Python expects c to be dimensionless
    return ν * k[3]*C0[1]*C[0] / ((k[2]+k[3])/k[1] + C[0]) #k and ν are arrays for the problem I'm working on.

我想添加一个 if 语句,这样我就不会以 r(C0,t) 中的 C 为单位 mol^2/L^2 结束。我所拥有的是

def r(c,t):
    if c.dimensionless == True:
        C = c * u.mol/u.L
    else:
        C = c
    return ν * k[3]*C0[1]*C[0] / ((k[2]+k[3])/k[1] + C[0])

但是当我用 C0 运行它时,它告诉我 C0 没有称为无量纲的属性。我应该如何编辑我的 if 语句,以便它可以检查任何类型的单位输入?

追溯:

File [Redacted], line 32, in <module>
    Ct = odeint(r,C0,t)

  File "C:\Users\Spencer\Anaconda3\lib\site-packages\scipy\integrate\odepack.py", line 233, in odeint
    int(bool(tfirst)))

  File [Redacted], line 24, in r
    if c.dimensionless == True:

AttributeError: 'numpy.ndarray' object has no attribute 'dimensionless'
4

1 回答 1

1

环顾四周后,我发现 pint.UnitRegistry.Quantity 函数允许对没有原生“维度”属性的项目进行维度检查。还要注意从上面复制和添加单位的相反顺序。

def r(c,t):
    if u.Quantity(c).dimensionality == 'substance/length**3':
        C = c
    else:
        C = c   * u.mol/u.L
    return ν * k[3]*C0[1]*C[0] / ((k[2]+k[3])/k[1] + C[0])
于 2020-01-26T06:52:19.957 回答