无法将表达式转换为浮点型 [英] Can't convert expression to float

查看:444
本文介绍了无法将表达式转换为浮点型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习python中符号操作的来龙去脉(我是一个初学者).

I'm trying to learn the ins and outs of symbolic manipulation in python (I'm a beginner).

我有以下基本代码,并且输出给我一个错误,告诉我它无法将表达式转换为浮点数".

I have the following basic code, and the output is giving me an error telling me that it "can't convert expression to float".

此代码出了什么问题?

from sympy import *
from math import *

def h(x):
    return log(0.75392 * x)

x = symbols('x')
hprime = h(x).diff(x)

print(hprime)

推荐答案

这是

应避免通配符导入(from <module> import *),因为通配符使不清楚名称空间中存在哪些名称,使读者和许多自动化工具都感到困惑.

Wildcard imports ( from <module> import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.

问题是您需要使用 math.log 函数代替,它可用于 float 对象,而不适用于 Symbol 对象.

The problem is that you need to work with sympy.log class, but using math.log function instead which works on float objects, not Symbol objects.

写作时

from sympy import *

您要在模块名称空间中导入sympy软件包在顶层提供的所有内容(并且有很多东西,其中很多根本不需要),包括sympy.log类.

you are importing in your module namespace everything that sympy package providing at the top level (and there are a lot of stuff, much of that you don't need at all), including sympy.log class.

下一条语句后

from math import *

您正在导入math模块中的所有内容,包括math.log,该模块将覆盖以前导入的sympy.log类.

you are importing everything in math module, including math.log, which overwrites previously imported sympy.log class.

考虑到这一点,您的示例可能会写成

Considering this your example may be written like

import sympy


def h(x):
    return sympy.log(0.485022 * x)


x = sympy.symbols('x')
h_x = h(x)
hprime = h_x.diff(x)

print(hprime)

给我们

1.0/x

P. S.:由于math导入在给定的示例中未使用,因此我将其删除.

P. S.: I've removed math import since it is not used in given example.

这篇关于无法将表达式转换为浮点型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆