ufunc 的循环不支持 Float 类型的参数 0,该类型没有可调用的 log 方法

问题描述 投票:0回答:1
a = 0.5
b = 1
l = Symbol('l')
l = solve(a*b/2+b/l-1, l)[0]
num = 1-l/b*(r-a*b/2)
-1/l*np.log(num)

给出错误 TypeError: ufunc 循环不支持 Float 类型的参数 0,该类型没有可调用的 log 方法

我该如何解决这个问题?

python numpy solver
1个回答
0
投票

如上所述,

r
未定义。

In [83]: a = 0.5
    ...: b = 1
    ...: l = sp.Symbol('l')
    ...: l = sp.solve(a*b/2+b/l-1, l)[0]
    ...: num = 1-l/b*(r-a*b/2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[83], line 5
      3 l = sp.Symbol('l')
      4 l = sp.solve(a*b/2+b/l-1, l)[0]
----> 5 num = 1-l/b*(r-a*b/2)

NameError: name 'r' is not defined

但是检查

l

In [84]: l
Out[84]: 
1.33333333333333

In [85]: type(l)
Out[85]: sympy.core.numbers.Float

尝试记录会产生错误:

In [86]: np.log(l)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Float' object has no attribute 'log'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Cell In[86], line 1
----> 1 np.log(l)

TypeError: loop of ufunc does not support argument 0 of type Float which has no callable log method

sympy 有一个有效的日志:

In [88]: sp.log(l)
Out[88]: 
0.287682072451781

你的

l
看起来像一个普通的浮动,但实际上是一个sympy版本。
np.log
如果给定一个非数字数组,首先创建一个数组:

In [89]: np.array(l)
Out[89]: array(1.33333333333333, dtype=object)

如果是对象数据类型,它会尝试将

log
方法应用于数组的每个元素。几乎没有人实现
x.log()
方法。

一般来说,将

numpy
与 sympy 一起使用效果不佳。零碎的东西可以工作,但它们并不是为了协同工作而设计的。如果可用,请使用
sympy
功能。在某些情况下,
sp.lambdify
可以将表达式转换为可以工作的Python函数。

© www.soinside.com 2019 - 2024. All rights reserved.